Merge tag 'drm-fixes-for-4.10-rc1' of git://people.freedesktop.org/~airlied/linux
[sfrench/cifs-2.6.git] / drivers / gpu / drm / i915 / intel_display.c
1 /*
2  * Copyright © 2006-2007 Intel Corporation
3  *
4  * Permission is hereby granted, free of charge, to any person obtaining a
5  * copy of this software and associated documentation files (the "Software"),
6  * to deal in the Software without restriction, including without limitation
7  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
8  * and/or sell copies of the Software, and to permit persons to whom the
9  * Software is furnished to do so, subject to the following conditions:
10  *
11  * The above copyright notice and this permission notice (including the next
12  * paragraph) shall be included in all copies or substantial portions of the
13  * Software.
14  *
15  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
18  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
21  * DEALINGS IN THE SOFTWARE.
22  *
23  * Authors:
24  *      Eric Anholt <eric@anholt.net>
25  */
26
27 #include <linux/dmi.h>
28 #include <linux/module.h>
29 #include <linux/input.h>
30 #include <linux/i2c.h>
31 #include <linux/kernel.h>
32 #include <linux/slab.h>
33 #include <linux/vgaarb.h>
34 #include <drm/drm_edid.h>
35 #include <drm/drmP.h>
36 #include "intel_drv.h"
37 #include "intel_frontbuffer.h"
38 #include <drm/i915_drm.h>
39 #include "i915_drv.h"
40 #include "intel_dsi.h"
41 #include "i915_trace.h"
42 #include <drm/drm_atomic.h>
43 #include <drm/drm_atomic_helper.h>
44 #include <drm/drm_dp_helper.h>
45 #include <drm/drm_crtc_helper.h>
46 #include <drm/drm_plane_helper.h>
47 #include <drm/drm_rect.h>
48 #include <linux/dma_remapping.h>
49 #include <linux/reservation.h>
50
51 static bool is_mmio_work(struct intel_flip_work *work)
52 {
53         return work->mmio_work.func;
54 }
55
56 /* Primary plane formats for gen <= 3 */
57 static const uint32_t i8xx_primary_formats[] = {
58         DRM_FORMAT_C8,
59         DRM_FORMAT_RGB565,
60         DRM_FORMAT_XRGB1555,
61         DRM_FORMAT_XRGB8888,
62 };
63
64 /* Primary plane formats for gen >= 4 */
65 static const uint32_t i965_primary_formats[] = {
66         DRM_FORMAT_C8,
67         DRM_FORMAT_RGB565,
68         DRM_FORMAT_XRGB8888,
69         DRM_FORMAT_XBGR8888,
70         DRM_FORMAT_XRGB2101010,
71         DRM_FORMAT_XBGR2101010,
72 };
73
74 static const uint32_t skl_primary_formats[] = {
75         DRM_FORMAT_C8,
76         DRM_FORMAT_RGB565,
77         DRM_FORMAT_XRGB8888,
78         DRM_FORMAT_XBGR8888,
79         DRM_FORMAT_ARGB8888,
80         DRM_FORMAT_ABGR8888,
81         DRM_FORMAT_XRGB2101010,
82         DRM_FORMAT_XBGR2101010,
83         DRM_FORMAT_YUYV,
84         DRM_FORMAT_YVYU,
85         DRM_FORMAT_UYVY,
86         DRM_FORMAT_VYUY,
87 };
88
89 /* Cursor formats */
90 static const uint32_t intel_cursor_formats[] = {
91         DRM_FORMAT_ARGB8888,
92 };
93
94 static void i9xx_crtc_clock_get(struct intel_crtc *crtc,
95                                 struct intel_crtc_state *pipe_config);
96 static void ironlake_pch_clock_get(struct intel_crtc *crtc,
97                                    struct intel_crtc_state *pipe_config);
98
99 static int intel_framebuffer_init(struct drm_device *dev,
100                                   struct intel_framebuffer *ifb,
101                                   struct drm_mode_fb_cmd2 *mode_cmd,
102                                   struct drm_i915_gem_object *obj);
103 static void i9xx_set_pipeconf(struct intel_crtc *intel_crtc);
104 static void intel_set_pipe_timings(struct intel_crtc *intel_crtc);
105 static void intel_set_pipe_src_size(struct intel_crtc *intel_crtc);
106 static void intel_cpu_transcoder_set_m_n(struct intel_crtc *crtc,
107                                          struct intel_link_m_n *m_n,
108                                          struct intel_link_m_n *m2_n2);
109 static void ironlake_set_pipeconf(struct drm_crtc *crtc);
110 static void haswell_set_pipeconf(struct drm_crtc *crtc);
111 static void haswell_set_pipemisc(struct drm_crtc *crtc);
112 static void vlv_prepare_pll(struct intel_crtc *crtc,
113                             const struct intel_crtc_state *pipe_config);
114 static void chv_prepare_pll(struct intel_crtc *crtc,
115                             const struct intel_crtc_state *pipe_config);
116 static void intel_begin_crtc_commit(struct drm_crtc *, struct drm_crtc_state *);
117 static void intel_finish_crtc_commit(struct drm_crtc *, struct drm_crtc_state *);
118 static void skl_init_scalers(struct drm_i915_private *dev_priv,
119                              struct intel_crtc *crtc,
120                              struct intel_crtc_state *crtc_state);
121 static void skylake_pfit_enable(struct intel_crtc *crtc);
122 static void ironlake_pfit_disable(struct intel_crtc *crtc, bool force);
123 static void ironlake_pfit_enable(struct intel_crtc *crtc);
124 static void intel_modeset_setup_hw_state(struct drm_device *dev);
125 static void intel_pre_disable_primary_noatomic(struct drm_crtc *crtc);
126 static int ilk_max_pixel_rate(struct drm_atomic_state *state);
127 static int bxt_calc_cdclk(int max_pixclk);
128
129 struct intel_limit {
130         struct {
131                 int min, max;
132         } dot, vco, n, m, m1, m2, p, p1;
133
134         struct {
135                 int dot_limit;
136                 int p2_slow, p2_fast;
137         } p2;
138 };
139
140 /* returns HPLL frequency in kHz */
141 static int valleyview_get_vco(struct drm_i915_private *dev_priv)
142 {
143         int hpll_freq, vco_freq[] = { 800, 1600, 2000, 2400 };
144
145         /* Obtain SKU information */
146         mutex_lock(&dev_priv->sb_lock);
147         hpll_freq = vlv_cck_read(dev_priv, CCK_FUSE_REG) &
148                 CCK_FUSE_HPLL_FREQ_MASK;
149         mutex_unlock(&dev_priv->sb_lock);
150
151         return vco_freq[hpll_freq] * 1000;
152 }
153
154 int vlv_get_cck_clock(struct drm_i915_private *dev_priv,
155                       const char *name, u32 reg, int ref_freq)
156 {
157         u32 val;
158         int divider;
159
160         mutex_lock(&dev_priv->sb_lock);
161         val = vlv_cck_read(dev_priv, reg);
162         mutex_unlock(&dev_priv->sb_lock);
163
164         divider = val & CCK_FREQUENCY_VALUES;
165
166         WARN((val & CCK_FREQUENCY_STATUS) !=
167              (divider << CCK_FREQUENCY_STATUS_SHIFT),
168              "%s change in progress\n", name);
169
170         return DIV_ROUND_CLOSEST(ref_freq << 1, divider + 1);
171 }
172
173 static int vlv_get_cck_clock_hpll(struct drm_i915_private *dev_priv,
174                                   const char *name, u32 reg)
175 {
176         if (dev_priv->hpll_freq == 0)
177                 dev_priv->hpll_freq = valleyview_get_vco(dev_priv);
178
179         return vlv_get_cck_clock(dev_priv, name, reg,
180                                  dev_priv->hpll_freq);
181 }
182
183 static int
184 intel_pch_rawclk(struct drm_i915_private *dev_priv)
185 {
186         return (I915_READ(PCH_RAWCLK_FREQ) & RAWCLK_FREQ_MASK) * 1000;
187 }
188
189 static int
190 intel_vlv_hrawclk(struct drm_i915_private *dev_priv)
191 {
192         /* RAWCLK_FREQ_VLV register updated from power well code */
193         return vlv_get_cck_clock_hpll(dev_priv, "hrawclk",
194                                       CCK_DISPLAY_REF_CLOCK_CONTROL);
195 }
196
197 static int
198 intel_g4x_hrawclk(struct drm_i915_private *dev_priv)
199 {
200         uint32_t clkcfg;
201
202         /* hrawclock is 1/4 the FSB frequency */
203         clkcfg = I915_READ(CLKCFG);
204         switch (clkcfg & CLKCFG_FSB_MASK) {
205         case CLKCFG_FSB_400:
206                 return 100000;
207         case CLKCFG_FSB_533:
208                 return 133333;
209         case CLKCFG_FSB_667:
210                 return 166667;
211         case CLKCFG_FSB_800:
212                 return 200000;
213         case CLKCFG_FSB_1067:
214                 return 266667;
215         case CLKCFG_FSB_1333:
216                 return 333333;
217         /* these two are just a guess; one of them might be right */
218         case CLKCFG_FSB_1600:
219         case CLKCFG_FSB_1600_ALT:
220                 return 400000;
221         default:
222                 return 133333;
223         }
224 }
225
226 void intel_update_rawclk(struct drm_i915_private *dev_priv)
227 {
228         if (HAS_PCH_SPLIT(dev_priv))
229                 dev_priv->rawclk_freq = intel_pch_rawclk(dev_priv);
230         else if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
231                 dev_priv->rawclk_freq = intel_vlv_hrawclk(dev_priv);
232         else if (IS_G4X(dev_priv) || IS_PINEVIEW(dev_priv))
233                 dev_priv->rawclk_freq = intel_g4x_hrawclk(dev_priv);
234         else
235                 return; /* no rawclk on other platforms, or no need to know it */
236
237         DRM_DEBUG_DRIVER("rawclk rate: %d kHz\n", dev_priv->rawclk_freq);
238 }
239
240 static void intel_update_czclk(struct drm_i915_private *dev_priv)
241 {
242         if (!(IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv)))
243                 return;
244
245         dev_priv->czclk_freq = vlv_get_cck_clock_hpll(dev_priv, "czclk",
246                                                       CCK_CZ_CLOCK_CONTROL);
247
248         DRM_DEBUG_DRIVER("CZ clock rate: %d kHz\n", dev_priv->czclk_freq);
249 }
250
251 static inline u32 /* units of 100MHz */
252 intel_fdi_link_freq(struct drm_i915_private *dev_priv,
253                     const struct intel_crtc_state *pipe_config)
254 {
255         if (HAS_DDI(dev_priv))
256                 return pipe_config->port_clock; /* SPLL */
257         else if (IS_GEN5(dev_priv))
258                 return ((I915_READ(FDI_PLL_BIOS_0) & FDI_PLL_FB_CLOCK_MASK) + 2) * 10000;
259         else
260                 return 270000;
261 }
262
263 static const struct intel_limit intel_limits_i8xx_dac = {
264         .dot = { .min = 25000, .max = 350000 },
265         .vco = { .min = 908000, .max = 1512000 },
266         .n = { .min = 2, .max = 16 },
267         .m = { .min = 96, .max = 140 },
268         .m1 = { .min = 18, .max = 26 },
269         .m2 = { .min = 6, .max = 16 },
270         .p = { .min = 4, .max = 128 },
271         .p1 = { .min = 2, .max = 33 },
272         .p2 = { .dot_limit = 165000,
273                 .p2_slow = 4, .p2_fast = 2 },
274 };
275
276 static const struct intel_limit intel_limits_i8xx_dvo = {
277         .dot = { .min = 25000, .max = 350000 },
278         .vco = { .min = 908000, .max = 1512000 },
279         .n = { .min = 2, .max = 16 },
280         .m = { .min = 96, .max = 140 },
281         .m1 = { .min = 18, .max = 26 },
282         .m2 = { .min = 6, .max = 16 },
283         .p = { .min = 4, .max = 128 },
284         .p1 = { .min = 2, .max = 33 },
285         .p2 = { .dot_limit = 165000,
286                 .p2_slow = 4, .p2_fast = 4 },
287 };
288
289 static const struct intel_limit intel_limits_i8xx_lvds = {
290         .dot = { .min = 25000, .max = 350000 },
291         .vco = { .min = 908000, .max = 1512000 },
292         .n = { .min = 2, .max = 16 },
293         .m = { .min = 96, .max = 140 },
294         .m1 = { .min = 18, .max = 26 },
295         .m2 = { .min = 6, .max = 16 },
296         .p = { .min = 4, .max = 128 },
297         .p1 = { .min = 1, .max = 6 },
298         .p2 = { .dot_limit = 165000,
299                 .p2_slow = 14, .p2_fast = 7 },
300 };
301
302 static const struct intel_limit intel_limits_i9xx_sdvo = {
303         .dot = { .min = 20000, .max = 400000 },
304         .vco = { .min = 1400000, .max = 2800000 },
305         .n = { .min = 1, .max = 6 },
306         .m = { .min = 70, .max = 120 },
307         .m1 = { .min = 8, .max = 18 },
308         .m2 = { .min = 3, .max = 7 },
309         .p = { .min = 5, .max = 80 },
310         .p1 = { .min = 1, .max = 8 },
311         .p2 = { .dot_limit = 200000,
312                 .p2_slow = 10, .p2_fast = 5 },
313 };
314
315 static const struct intel_limit intel_limits_i9xx_lvds = {
316         .dot = { .min = 20000, .max = 400000 },
317         .vco = { .min = 1400000, .max = 2800000 },
318         .n = { .min = 1, .max = 6 },
319         .m = { .min = 70, .max = 120 },
320         .m1 = { .min = 8, .max = 18 },
321         .m2 = { .min = 3, .max = 7 },
322         .p = { .min = 7, .max = 98 },
323         .p1 = { .min = 1, .max = 8 },
324         .p2 = { .dot_limit = 112000,
325                 .p2_slow = 14, .p2_fast = 7 },
326 };
327
328
329 static const struct intel_limit intel_limits_g4x_sdvo = {
330         .dot = { .min = 25000, .max = 270000 },
331         .vco = { .min = 1750000, .max = 3500000},
332         .n = { .min = 1, .max = 4 },
333         .m = { .min = 104, .max = 138 },
334         .m1 = { .min = 17, .max = 23 },
335         .m2 = { .min = 5, .max = 11 },
336         .p = { .min = 10, .max = 30 },
337         .p1 = { .min = 1, .max = 3},
338         .p2 = { .dot_limit = 270000,
339                 .p2_slow = 10,
340                 .p2_fast = 10
341         },
342 };
343
344 static const struct intel_limit intel_limits_g4x_hdmi = {
345         .dot = { .min = 22000, .max = 400000 },
346         .vco = { .min = 1750000, .max = 3500000},
347         .n = { .min = 1, .max = 4 },
348         .m = { .min = 104, .max = 138 },
349         .m1 = { .min = 16, .max = 23 },
350         .m2 = { .min = 5, .max = 11 },
351         .p = { .min = 5, .max = 80 },
352         .p1 = { .min = 1, .max = 8},
353         .p2 = { .dot_limit = 165000,
354                 .p2_slow = 10, .p2_fast = 5 },
355 };
356
357 static const struct intel_limit intel_limits_g4x_single_channel_lvds = {
358         .dot = { .min = 20000, .max = 115000 },
359         .vco = { .min = 1750000, .max = 3500000 },
360         .n = { .min = 1, .max = 3 },
361         .m = { .min = 104, .max = 138 },
362         .m1 = { .min = 17, .max = 23 },
363         .m2 = { .min = 5, .max = 11 },
364         .p = { .min = 28, .max = 112 },
365         .p1 = { .min = 2, .max = 8 },
366         .p2 = { .dot_limit = 0,
367                 .p2_slow = 14, .p2_fast = 14
368         },
369 };
370
371 static const struct intel_limit intel_limits_g4x_dual_channel_lvds = {
372         .dot = { .min = 80000, .max = 224000 },
373         .vco = { .min = 1750000, .max = 3500000 },
374         .n = { .min = 1, .max = 3 },
375         .m = { .min = 104, .max = 138 },
376         .m1 = { .min = 17, .max = 23 },
377         .m2 = { .min = 5, .max = 11 },
378         .p = { .min = 14, .max = 42 },
379         .p1 = { .min = 2, .max = 6 },
380         .p2 = { .dot_limit = 0,
381                 .p2_slow = 7, .p2_fast = 7
382         },
383 };
384
385 static const struct intel_limit intel_limits_pineview_sdvo = {
386         .dot = { .min = 20000, .max = 400000},
387         .vco = { .min = 1700000, .max = 3500000 },
388         /* Pineview's Ncounter is a ring counter */
389         .n = { .min = 3, .max = 6 },
390         .m = { .min = 2, .max = 256 },
391         /* Pineview only has one combined m divider, which we treat as m2. */
392         .m1 = { .min = 0, .max = 0 },
393         .m2 = { .min = 0, .max = 254 },
394         .p = { .min = 5, .max = 80 },
395         .p1 = { .min = 1, .max = 8 },
396         .p2 = { .dot_limit = 200000,
397                 .p2_slow = 10, .p2_fast = 5 },
398 };
399
400 static const struct intel_limit intel_limits_pineview_lvds = {
401         .dot = { .min = 20000, .max = 400000 },
402         .vco = { .min = 1700000, .max = 3500000 },
403         .n = { .min = 3, .max = 6 },
404         .m = { .min = 2, .max = 256 },
405         .m1 = { .min = 0, .max = 0 },
406         .m2 = { .min = 0, .max = 254 },
407         .p = { .min = 7, .max = 112 },
408         .p1 = { .min = 1, .max = 8 },
409         .p2 = { .dot_limit = 112000,
410                 .p2_slow = 14, .p2_fast = 14 },
411 };
412
413 /* Ironlake / Sandybridge
414  *
415  * We calculate clock using (register_value + 2) for N/M1/M2, so here
416  * the range value for them is (actual_value - 2).
417  */
418 static const struct intel_limit intel_limits_ironlake_dac = {
419         .dot = { .min = 25000, .max = 350000 },
420         .vco = { .min = 1760000, .max = 3510000 },
421         .n = { .min = 1, .max = 5 },
422         .m = { .min = 79, .max = 127 },
423         .m1 = { .min = 12, .max = 22 },
424         .m2 = { .min = 5, .max = 9 },
425         .p = { .min = 5, .max = 80 },
426         .p1 = { .min = 1, .max = 8 },
427         .p2 = { .dot_limit = 225000,
428                 .p2_slow = 10, .p2_fast = 5 },
429 };
430
431 static const struct intel_limit intel_limits_ironlake_single_lvds = {
432         .dot = { .min = 25000, .max = 350000 },
433         .vco = { .min = 1760000, .max = 3510000 },
434         .n = { .min = 1, .max = 3 },
435         .m = { .min = 79, .max = 118 },
436         .m1 = { .min = 12, .max = 22 },
437         .m2 = { .min = 5, .max = 9 },
438         .p = { .min = 28, .max = 112 },
439         .p1 = { .min = 2, .max = 8 },
440         .p2 = { .dot_limit = 225000,
441                 .p2_slow = 14, .p2_fast = 14 },
442 };
443
444 static const struct intel_limit intel_limits_ironlake_dual_lvds = {
445         .dot = { .min = 25000, .max = 350000 },
446         .vco = { .min = 1760000, .max = 3510000 },
447         .n = { .min = 1, .max = 3 },
448         .m = { .min = 79, .max = 127 },
449         .m1 = { .min = 12, .max = 22 },
450         .m2 = { .min = 5, .max = 9 },
451         .p = { .min = 14, .max = 56 },
452         .p1 = { .min = 2, .max = 8 },
453         .p2 = { .dot_limit = 225000,
454                 .p2_slow = 7, .p2_fast = 7 },
455 };
456
457 /* LVDS 100mhz refclk limits. */
458 static const struct intel_limit intel_limits_ironlake_single_lvds_100m = {
459         .dot = { .min = 25000, .max = 350000 },
460         .vco = { .min = 1760000, .max = 3510000 },
461         .n = { .min = 1, .max = 2 },
462         .m = { .min = 79, .max = 126 },
463         .m1 = { .min = 12, .max = 22 },
464         .m2 = { .min = 5, .max = 9 },
465         .p = { .min = 28, .max = 112 },
466         .p1 = { .min = 2, .max = 8 },
467         .p2 = { .dot_limit = 225000,
468                 .p2_slow = 14, .p2_fast = 14 },
469 };
470
471 static const struct intel_limit intel_limits_ironlake_dual_lvds_100m = {
472         .dot = { .min = 25000, .max = 350000 },
473         .vco = { .min = 1760000, .max = 3510000 },
474         .n = { .min = 1, .max = 3 },
475         .m = { .min = 79, .max = 126 },
476         .m1 = { .min = 12, .max = 22 },
477         .m2 = { .min = 5, .max = 9 },
478         .p = { .min = 14, .max = 42 },
479         .p1 = { .min = 2, .max = 6 },
480         .p2 = { .dot_limit = 225000,
481                 .p2_slow = 7, .p2_fast = 7 },
482 };
483
484 static const struct intel_limit intel_limits_vlv = {
485          /*
486           * These are the data rate limits (measured in fast clocks)
487           * since those are the strictest limits we have. The fast
488           * clock and actual rate limits are more relaxed, so checking
489           * them would make no difference.
490           */
491         .dot = { .min = 25000 * 5, .max = 270000 * 5 },
492         .vco = { .min = 4000000, .max = 6000000 },
493         .n = { .min = 1, .max = 7 },
494         .m1 = { .min = 2, .max = 3 },
495         .m2 = { .min = 11, .max = 156 },
496         .p1 = { .min = 2, .max = 3 },
497         .p2 = { .p2_slow = 2, .p2_fast = 20 }, /* slow=min, fast=max */
498 };
499
500 static const struct intel_limit intel_limits_chv = {
501         /*
502          * These are the data rate limits (measured in fast clocks)
503          * since those are the strictest limits we have.  The fast
504          * clock and actual rate limits are more relaxed, so checking
505          * them would make no difference.
506          */
507         .dot = { .min = 25000 * 5, .max = 540000 * 5},
508         .vco = { .min = 4800000, .max = 6480000 },
509         .n = { .min = 1, .max = 1 },
510         .m1 = { .min = 2, .max = 2 },
511         .m2 = { .min = 24 << 22, .max = 175 << 22 },
512         .p1 = { .min = 2, .max = 4 },
513         .p2 = { .p2_slow = 1, .p2_fast = 14 },
514 };
515
516 static const struct intel_limit intel_limits_bxt = {
517         /* FIXME: find real dot limits */
518         .dot = { .min = 0, .max = INT_MAX },
519         .vco = { .min = 4800000, .max = 6700000 },
520         .n = { .min = 1, .max = 1 },
521         .m1 = { .min = 2, .max = 2 },
522         /* FIXME: find real m2 limits */
523         .m2 = { .min = 2 << 22, .max = 255 << 22 },
524         .p1 = { .min = 2, .max = 4 },
525         .p2 = { .p2_slow = 1, .p2_fast = 20 },
526 };
527
528 static bool
529 needs_modeset(struct drm_crtc_state *state)
530 {
531         return drm_atomic_crtc_needs_modeset(state);
532 }
533
534 /*
535  * Platform specific helpers to calculate the port PLL loopback- (clock.m),
536  * and post-divider (clock.p) values, pre- (clock.vco) and post-divided fast
537  * (clock.dot) clock rates. This fast dot clock is fed to the port's IO logic.
538  * The helpers' return value is the rate of the clock that is fed to the
539  * display engine's pipe which can be the above fast dot clock rate or a
540  * divided-down version of it.
541  */
542 /* m1 is reserved as 0 in Pineview, n is a ring counter */
543 static int pnv_calc_dpll_params(int refclk, struct dpll *clock)
544 {
545         clock->m = clock->m2 + 2;
546         clock->p = clock->p1 * clock->p2;
547         if (WARN_ON(clock->n == 0 || clock->p == 0))
548                 return 0;
549         clock->vco = DIV_ROUND_CLOSEST(refclk * clock->m, clock->n);
550         clock->dot = DIV_ROUND_CLOSEST(clock->vco, clock->p);
551
552         return clock->dot;
553 }
554
555 static uint32_t i9xx_dpll_compute_m(struct dpll *dpll)
556 {
557         return 5 * (dpll->m1 + 2) + (dpll->m2 + 2);
558 }
559
560 static int i9xx_calc_dpll_params(int refclk, struct dpll *clock)
561 {
562         clock->m = i9xx_dpll_compute_m(clock);
563         clock->p = clock->p1 * clock->p2;
564         if (WARN_ON(clock->n + 2 == 0 || clock->p == 0))
565                 return 0;
566         clock->vco = DIV_ROUND_CLOSEST(refclk * clock->m, clock->n + 2);
567         clock->dot = DIV_ROUND_CLOSEST(clock->vco, clock->p);
568
569         return clock->dot;
570 }
571
572 static int vlv_calc_dpll_params(int refclk, struct dpll *clock)
573 {
574         clock->m = clock->m1 * clock->m2;
575         clock->p = clock->p1 * clock->p2;
576         if (WARN_ON(clock->n == 0 || clock->p == 0))
577                 return 0;
578         clock->vco = DIV_ROUND_CLOSEST(refclk * clock->m, clock->n);
579         clock->dot = DIV_ROUND_CLOSEST(clock->vco, clock->p);
580
581         return clock->dot / 5;
582 }
583
584 int chv_calc_dpll_params(int refclk, struct dpll *clock)
585 {
586         clock->m = clock->m1 * clock->m2;
587         clock->p = clock->p1 * clock->p2;
588         if (WARN_ON(clock->n == 0 || clock->p == 0))
589                 return 0;
590         clock->vco = DIV_ROUND_CLOSEST_ULL((uint64_t)refclk * clock->m,
591                         clock->n << 22);
592         clock->dot = DIV_ROUND_CLOSEST(clock->vco, clock->p);
593
594         return clock->dot / 5;
595 }
596
597 #define INTELPllInvalid(s)   do { /* DRM_DEBUG(s); */ return false; } while (0)
598 /**
599  * Returns whether the given set of divisors are valid for a given refclk with
600  * the given connectors.
601  */
602
603 static bool intel_PLL_is_valid(struct drm_i915_private *dev_priv,
604                                const struct intel_limit *limit,
605                                const struct dpll *clock)
606 {
607         if (clock->n   < limit->n.min   || limit->n.max   < clock->n)
608                 INTELPllInvalid("n out of range\n");
609         if (clock->p1  < limit->p1.min  || limit->p1.max  < clock->p1)
610                 INTELPllInvalid("p1 out of range\n");
611         if (clock->m2  < limit->m2.min  || limit->m2.max  < clock->m2)
612                 INTELPllInvalid("m2 out of range\n");
613         if (clock->m1  < limit->m1.min  || limit->m1.max  < clock->m1)
614                 INTELPllInvalid("m1 out of range\n");
615
616         if (!IS_PINEVIEW(dev_priv) && !IS_VALLEYVIEW(dev_priv) &&
617             !IS_CHERRYVIEW(dev_priv) && !IS_BROXTON(dev_priv))
618                 if (clock->m1 <= clock->m2)
619                         INTELPllInvalid("m1 <= m2\n");
620
621         if (!IS_VALLEYVIEW(dev_priv) && !IS_CHERRYVIEW(dev_priv) &&
622             !IS_BROXTON(dev_priv)) {
623                 if (clock->p < limit->p.min || limit->p.max < clock->p)
624                         INTELPllInvalid("p out of range\n");
625                 if (clock->m < limit->m.min || limit->m.max < clock->m)
626                         INTELPllInvalid("m out of range\n");
627         }
628
629         if (clock->vco < limit->vco.min || limit->vco.max < clock->vco)
630                 INTELPllInvalid("vco out of range\n");
631         /* XXX: We may need to be checking "Dot clock" depending on the multiplier,
632          * connector, etc., rather than just a single range.
633          */
634         if (clock->dot < limit->dot.min || limit->dot.max < clock->dot)
635                 INTELPllInvalid("dot out of range\n");
636
637         return true;
638 }
639
640 static int
641 i9xx_select_p2_div(const struct intel_limit *limit,
642                    const struct intel_crtc_state *crtc_state,
643                    int target)
644 {
645         struct drm_device *dev = crtc_state->base.crtc->dev;
646
647         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
648                 /*
649                  * For LVDS just rely on its current settings for dual-channel.
650                  * We haven't figured out how to reliably set up different
651                  * single/dual channel state, if we even can.
652                  */
653                 if (intel_is_dual_link_lvds(dev))
654                         return limit->p2.p2_fast;
655                 else
656                         return limit->p2.p2_slow;
657         } else {
658                 if (target < limit->p2.dot_limit)
659                         return limit->p2.p2_slow;
660                 else
661                         return limit->p2.p2_fast;
662         }
663 }
664
665 /*
666  * Returns a set of divisors for the desired target clock with the given
667  * refclk, or FALSE.  The returned values represent the clock equation:
668  * reflck * (5 * (m1 + 2) + (m2 + 2)) / (n + 2) / p1 / p2.
669  *
670  * Target and reference clocks are specified in kHz.
671  *
672  * If match_clock is provided, then best_clock P divider must match the P
673  * divider from @match_clock used for LVDS downclocking.
674  */
675 static bool
676 i9xx_find_best_dpll(const struct intel_limit *limit,
677                     struct intel_crtc_state *crtc_state,
678                     int target, int refclk, struct dpll *match_clock,
679                     struct dpll *best_clock)
680 {
681         struct drm_device *dev = crtc_state->base.crtc->dev;
682         struct dpll clock;
683         int err = target;
684
685         memset(best_clock, 0, sizeof(*best_clock));
686
687         clock.p2 = i9xx_select_p2_div(limit, crtc_state, target);
688
689         for (clock.m1 = limit->m1.min; clock.m1 <= limit->m1.max;
690              clock.m1++) {
691                 for (clock.m2 = limit->m2.min;
692                      clock.m2 <= limit->m2.max; clock.m2++) {
693                         if (clock.m2 >= clock.m1)
694                                 break;
695                         for (clock.n = limit->n.min;
696                              clock.n <= limit->n.max; clock.n++) {
697                                 for (clock.p1 = limit->p1.min;
698                                         clock.p1 <= limit->p1.max; clock.p1++) {
699                                         int this_err;
700
701                                         i9xx_calc_dpll_params(refclk, &clock);
702                                         if (!intel_PLL_is_valid(to_i915(dev),
703                                                                 limit,
704                                                                 &clock))
705                                                 continue;
706                                         if (match_clock &&
707                                             clock.p != match_clock->p)
708                                                 continue;
709
710                                         this_err = abs(clock.dot - target);
711                                         if (this_err < err) {
712                                                 *best_clock = clock;
713                                                 err = this_err;
714                                         }
715                                 }
716                         }
717                 }
718         }
719
720         return (err != target);
721 }
722
723 /*
724  * Returns a set of divisors for the desired target clock with the given
725  * refclk, or FALSE.  The returned values represent the clock equation:
726  * reflck * (5 * (m1 + 2) + (m2 + 2)) / (n + 2) / p1 / p2.
727  *
728  * Target and reference clocks are specified in kHz.
729  *
730  * If match_clock is provided, then best_clock P divider must match the P
731  * divider from @match_clock used for LVDS downclocking.
732  */
733 static bool
734 pnv_find_best_dpll(const struct intel_limit *limit,
735                    struct intel_crtc_state *crtc_state,
736                    int target, int refclk, struct dpll *match_clock,
737                    struct dpll *best_clock)
738 {
739         struct drm_device *dev = crtc_state->base.crtc->dev;
740         struct dpll clock;
741         int err = target;
742
743         memset(best_clock, 0, sizeof(*best_clock));
744
745         clock.p2 = i9xx_select_p2_div(limit, crtc_state, target);
746
747         for (clock.m1 = limit->m1.min; clock.m1 <= limit->m1.max;
748              clock.m1++) {
749                 for (clock.m2 = limit->m2.min;
750                      clock.m2 <= limit->m2.max; clock.m2++) {
751                         for (clock.n = limit->n.min;
752                              clock.n <= limit->n.max; clock.n++) {
753                                 for (clock.p1 = limit->p1.min;
754                                         clock.p1 <= limit->p1.max; clock.p1++) {
755                                         int this_err;
756
757                                         pnv_calc_dpll_params(refclk, &clock);
758                                         if (!intel_PLL_is_valid(to_i915(dev),
759                                                                 limit,
760                                                                 &clock))
761                                                 continue;
762                                         if (match_clock &&
763                                             clock.p != match_clock->p)
764                                                 continue;
765
766                                         this_err = abs(clock.dot - target);
767                                         if (this_err < err) {
768                                                 *best_clock = clock;
769                                                 err = this_err;
770                                         }
771                                 }
772                         }
773                 }
774         }
775
776         return (err != target);
777 }
778
779 /*
780  * Returns a set of divisors for the desired target clock with the given
781  * refclk, or FALSE.  The returned values represent the clock equation:
782  * reflck * (5 * (m1 + 2) + (m2 + 2)) / (n + 2) / p1 / p2.
783  *
784  * Target and reference clocks are specified in kHz.
785  *
786  * If match_clock is provided, then best_clock P divider must match the P
787  * divider from @match_clock used for LVDS downclocking.
788  */
789 static bool
790 g4x_find_best_dpll(const struct intel_limit *limit,
791                    struct intel_crtc_state *crtc_state,
792                    int target, int refclk, struct dpll *match_clock,
793                    struct dpll *best_clock)
794 {
795         struct drm_device *dev = crtc_state->base.crtc->dev;
796         struct dpll clock;
797         int max_n;
798         bool found = false;
799         /* approximately equals target * 0.00585 */
800         int err_most = (target >> 8) + (target >> 9);
801
802         memset(best_clock, 0, sizeof(*best_clock));
803
804         clock.p2 = i9xx_select_p2_div(limit, crtc_state, target);
805
806         max_n = limit->n.max;
807         /* based on hardware requirement, prefer smaller n to precision */
808         for (clock.n = limit->n.min; clock.n <= max_n; clock.n++) {
809                 /* based on hardware requirement, prefere larger m1,m2 */
810                 for (clock.m1 = limit->m1.max;
811                      clock.m1 >= limit->m1.min; clock.m1--) {
812                         for (clock.m2 = limit->m2.max;
813                              clock.m2 >= limit->m2.min; clock.m2--) {
814                                 for (clock.p1 = limit->p1.max;
815                                      clock.p1 >= limit->p1.min; clock.p1--) {
816                                         int this_err;
817
818                                         i9xx_calc_dpll_params(refclk, &clock);
819                                         if (!intel_PLL_is_valid(to_i915(dev),
820                                                                 limit,
821                                                                 &clock))
822                                                 continue;
823
824                                         this_err = abs(clock.dot - target);
825                                         if (this_err < err_most) {
826                                                 *best_clock = clock;
827                                                 err_most = this_err;
828                                                 max_n = clock.n;
829                                                 found = true;
830                                         }
831                                 }
832                         }
833                 }
834         }
835         return found;
836 }
837
838 /*
839  * Check if the calculated PLL configuration is more optimal compared to the
840  * best configuration and error found so far. Return the calculated error.
841  */
842 static bool vlv_PLL_is_optimal(struct drm_device *dev, int target_freq,
843                                const struct dpll *calculated_clock,
844                                const struct dpll *best_clock,
845                                unsigned int best_error_ppm,
846                                unsigned int *error_ppm)
847 {
848         /*
849          * For CHV ignore the error and consider only the P value.
850          * Prefer a bigger P value based on HW requirements.
851          */
852         if (IS_CHERRYVIEW(to_i915(dev))) {
853                 *error_ppm = 0;
854
855                 return calculated_clock->p > best_clock->p;
856         }
857
858         if (WARN_ON_ONCE(!target_freq))
859                 return false;
860
861         *error_ppm = div_u64(1000000ULL *
862                                 abs(target_freq - calculated_clock->dot),
863                              target_freq);
864         /*
865          * Prefer a better P value over a better (smaller) error if the error
866          * is small. Ensure this preference for future configurations too by
867          * setting the error to 0.
868          */
869         if (*error_ppm < 100 && calculated_clock->p > best_clock->p) {
870                 *error_ppm = 0;
871
872                 return true;
873         }
874
875         return *error_ppm + 10 < best_error_ppm;
876 }
877
878 /*
879  * Returns a set of divisors for the desired target clock with the given
880  * refclk, or FALSE.  The returned values represent the clock equation:
881  * reflck * (5 * (m1 + 2) + (m2 + 2)) / (n + 2) / p1 / p2.
882  */
883 static bool
884 vlv_find_best_dpll(const struct intel_limit *limit,
885                    struct intel_crtc_state *crtc_state,
886                    int target, int refclk, struct dpll *match_clock,
887                    struct dpll *best_clock)
888 {
889         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
890         struct drm_device *dev = crtc->base.dev;
891         struct dpll clock;
892         unsigned int bestppm = 1000000;
893         /* min update 19.2 MHz */
894         int max_n = min(limit->n.max, refclk / 19200);
895         bool found = false;
896
897         target *= 5; /* fast clock */
898
899         memset(best_clock, 0, sizeof(*best_clock));
900
901         /* based on hardware requirement, prefer smaller n to precision */
902         for (clock.n = limit->n.min; clock.n <= max_n; clock.n++) {
903                 for (clock.p1 = limit->p1.max; clock.p1 >= limit->p1.min; clock.p1--) {
904                         for (clock.p2 = limit->p2.p2_fast; clock.p2 >= limit->p2.p2_slow;
905                              clock.p2 -= clock.p2 > 10 ? 2 : 1) {
906                                 clock.p = clock.p1 * clock.p2;
907                                 /* based on hardware requirement, prefer bigger m1,m2 values */
908                                 for (clock.m1 = limit->m1.min; clock.m1 <= limit->m1.max; clock.m1++) {
909                                         unsigned int ppm;
910
911                                         clock.m2 = DIV_ROUND_CLOSEST(target * clock.p * clock.n,
912                                                                      refclk * clock.m1);
913
914                                         vlv_calc_dpll_params(refclk, &clock);
915
916                                         if (!intel_PLL_is_valid(to_i915(dev),
917                                                                 limit,
918                                                                 &clock))
919                                                 continue;
920
921                                         if (!vlv_PLL_is_optimal(dev, target,
922                                                                 &clock,
923                                                                 best_clock,
924                                                                 bestppm, &ppm))
925                                                 continue;
926
927                                         *best_clock = clock;
928                                         bestppm = ppm;
929                                         found = true;
930                                 }
931                         }
932                 }
933         }
934
935         return found;
936 }
937
938 /*
939  * Returns a set of divisors for the desired target clock with the given
940  * refclk, or FALSE.  The returned values represent the clock equation:
941  * reflck * (5 * (m1 + 2) + (m2 + 2)) / (n + 2) / p1 / p2.
942  */
943 static bool
944 chv_find_best_dpll(const struct intel_limit *limit,
945                    struct intel_crtc_state *crtc_state,
946                    int target, int refclk, struct dpll *match_clock,
947                    struct dpll *best_clock)
948 {
949         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
950         struct drm_device *dev = crtc->base.dev;
951         unsigned int best_error_ppm;
952         struct dpll clock;
953         uint64_t m2;
954         int found = false;
955
956         memset(best_clock, 0, sizeof(*best_clock));
957         best_error_ppm = 1000000;
958
959         /*
960          * Based on hardware doc, the n always set to 1, and m1 always
961          * set to 2.  If requires to support 200Mhz refclk, we need to
962          * revisit this because n may not 1 anymore.
963          */
964         clock.n = 1, clock.m1 = 2;
965         target *= 5;    /* fast clock */
966
967         for (clock.p1 = limit->p1.max; clock.p1 >= limit->p1.min; clock.p1--) {
968                 for (clock.p2 = limit->p2.p2_fast;
969                                 clock.p2 >= limit->p2.p2_slow;
970                                 clock.p2 -= clock.p2 > 10 ? 2 : 1) {
971                         unsigned int error_ppm;
972
973                         clock.p = clock.p1 * clock.p2;
974
975                         m2 = DIV_ROUND_CLOSEST_ULL(((uint64_t)target * clock.p *
976                                         clock.n) << 22, refclk * clock.m1);
977
978                         if (m2 > INT_MAX/clock.m1)
979                                 continue;
980
981                         clock.m2 = m2;
982
983                         chv_calc_dpll_params(refclk, &clock);
984
985                         if (!intel_PLL_is_valid(to_i915(dev), limit, &clock))
986                                 continue;
987
988                         if (!vlv_PLL_is_optimal(dev, target, &clock, best_clock,
989                                                 best_error_ppm, &error_ppm))
990                                 continue;
991
992                         *best_clock = clock;
993                         best_error_ppm = error_ppm;
994                         found = true;
995                 }
996         }
997
998         return found;
999 }
1000
1001 bool bxt_find_best_dpll(struct intel_crtc_state *crtc_state, int target_clock,
1002                         struct dpll *best_clock)
1003 {
1004         int refclk = 100000;
1005         const struct intel_limit *limit = &intel_limits_bxt;
1006
1007         return chv_find_best_dpll(limit, crtc_state,
1008                                   target_clock, refclk, NULL, best_clock);
1009 }
1010
1011 bool intel_crtc_active(struct intel_crtc *crtc)
1012 {
1013         /* Be paranoid as we can arrive here with only partial
1014          * state retrieved from the hardware during setup.
1015          *
1016          * We can ditch the adjusted_mode.crtc_clock check as soon
1017          * as Haswell has gained clock readout/fastboot support.
1018          *
1019          * We can ditch the crtc->primary->fb check as soon as we can
1020          * properly reconstruct framebuffers.
1021          *
1022          * FIXME: The intel_crtc->active here should be switched to
1023          * crtc->state->active once we have proper CRTC states wired up
1024          * for atomic.
1025          */
1026         return crtc->active && crtc->base.primary->state->fb &&
1027                 crtc->config->base.adjusted_mode.crtc_clock;
1028 }
1029
1030 enum transcoder intel_pipe_to_cpu_transcoder(struct drm_i915_private *dev_priv,
1031                                              enum pipe pipe)
1032 {
1033         struct intel_crtc *crtc = intel_get_crtc_for_pipe(dev_priv, pipe);
1034
1035         return crtc->config->cpu_transcoder;
1036 }
1037
1038 static bool pipe_dsl_stopped(struct drm_i915_private *dev_priv, enum pipe pipe)
1039 {
1040         i915_reg_t reg = PIPEDSL(pipe);
1041         u32 line1, line2;
1042         u32 line_mask;
1043
1044         if (IS_GEN2(dev_priv))
1045                 line_mask = DSL_LINEMASK_GEN2;
1046         else
1047                 line_mask = DSL_LINEMASK_GEN3;
1048
1049         line1 = I915_READ(reg) & line_mask;
1050         msleep(5);
1051         line2 = I915_READ(reg) & line_mask;
1052
1053         return line1 == line2;
1054 }
1055
1056 /*
1057  * intel_wait_for_pipe_off - wait for pipe to turn off
1058  * @crtc: crtc whose pipe to wait for
1059  *
1060  * After disabling a pipe, we can't wait for vblank in the usual way,
1061  * spinning on the vblank interrupt status bit, since we won't actually
1062  * see an interrupt when the pipe is disabled.
1063  *
1064  * On Gen4 and above:
1065  *   wait for the pipe register state bit to turn off
1066  *
1067  * Otherwise:
1068  *   wait for the display line value to settle (it usually
1069  *   ends up stopping at the start of the next frame).
1070  *
1071  */
1072 static void intel_wait_for_pipe_off(struct intel_crtc *crtc)
1073 {
1074         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1075         enum transcoder cpu_transcoder = crtc->config->cpu_transcoder;
1076         enum pipe pipe = crtc->pipe;
1077
1078         if (INTEL_GEN(dev_priv) >= 4) {
1079                 i915_reg_t reg = PIPECONF(cpu_transcoder);
1080
1081                 /* Wait for the Pipe State to go off */
1082                 if (intel_wait_for_register(dev_priv,
1083                                             reg, I965_PIPECONF_ACTIVE, 0,
1084                                             100))
1085                         WARN(1, "pipe_off wait timed out\n");
1086         } else {
1087                 /* Wait for the display line to settle */
1088                 if (wait_for(pipe_dsl_stopped(dev_priv, pipe), 100))
1089                         WARN(1, "pipe_off wait timed out\n");
1090         }
1091 }
1092
1093 /* Only for pre-ILK configs */
1094 void assert_pll(struct drm_i915_private *dev_priv,
1095                 enum pipe pipe, bool state)
1096 {
1097         u32 val;
1098         bool cur_state;
1099
1100         val = I915_READ(DPLL(pipe));
1101         cur_state = !!(val & DPLL_VCO_ENABLE);
1102         I915_STATE_WARN(cur_state != state,
1103              "PLL state assertion failure (expected %s, current %s)\n",
1104                         onoff(state), onoff(cur_state));
1105 }
1106
1107 /* XXX: the dsi pll is shared between MIPI DSI ports */
1108 void assert_dsi_pll(struct drm_i915_private *dev_priv, bool state)
1109 {
1110         u32 val;
1111         bool cur_state;
1112
1113         mutex_lock(&dev_priv->sb_lock);
1114         val = vlv_cck_read(dev_priv, CCK_REG_DSI_PLL_CONTROL);
1115         mutex_unlock(&dev_priv->sb_lock);
1116
1117         cur_state = val & DSI_PLL_VCO_EN;
1118         I915_STATE_WARN(cur_state != state,
1119              "DSI PLL state assertion failure (expected %s, current %s)\n",
1120                         onoff(state), onoff(cur_state));
1121 }
1122
1123 static void assert_fdi_tx(struct drm_i915_private *dev_priv,
1124                           enum pipe pipe, bool state)
1125 {
1126         bool cur_state;
1127         enum transcoder cpu_transcoder = intel_pipe_to_cpu_transcoder(dev_priv,
1128                                                                       pipe);
1129
1130         if (HAS_DDI(dev_priv)) {
1131                 /* DDI does not have a specific FDI_TX register */
1132                 u32 val = I915_READ(TRANS_DDI_FUNC_CTL(cpu_transcoder));
1133                 cur_state = !!(val & TRANS_DDI_FUNC_ENABLE);
1134         } else {
1135                 u32 val = I915_READ(FDI_TX_CTL(pipe));
1136                 cur_state = !!(val & FDI_TX_ENABLE);
1137         }
1138         I915_STATE_WARN(cur_state != state,
1139              "FDI TX state assertion failure (expected %s, current %s)\n",
1140                         onoff(state), onoff(cur_state));
1141 }
1142 #define assert_fdi_tx_enabled(d, p) assert_fdi_tx(d, p, true)
1143 #define assert_fdi_tx_disabled(d, p) assert_fdi_tx(d, p, false)
1144
1145 static void assert_fdi_rx(struct drm_i915_private *dev_priv,
1146                           enum pipe pipe, bool state)
1147 {
1148         u32 val;
1149         bool cur_state;
1150
1151         val = I915_READ(FDI_RX_CTL(pipe));
1152         cur_state = !!(val & FDI_RX_ENABLE);
1153         I915_STATE_WARN(cur_state != state,
1154              "FDI RX state assertion failure (expected %s, current %s)\n",
1155                         onoff(state), onoff(cur_state));
1156 }
1157 #define assert_fdi_rx_enabled(d, p) assert_fdi_rx(d, p, true)
1158 #define assert_fdi_rx_disabled(d, p) assert_fdi_rx(d, p, false)
1159
1160 static void assert_fdi_tx_pll_enabled(struct drm_i915_private *dev_priv,
1161                                       enum pipe pipe)
1162 {
1163         u32 val;
1164
1165         /* ILK FDI PLL is always enabled */
1166         if (IS_GEN5(dev_priv))
1167                 return;
1168
1169         /* On Haswell, DDI ports are responsible for the FDI PLL setup */
1170         if (HAS_DDI(dev_priv))
1171                 return;
1172
1173         val = I915_READ(FDI_TX_CTL(pipe));
1174         I915_STATE_WARN(!(val & FDI_TX_PLL_ENABLE), "FDI TX PLL assertion failure, should be active but is disabled\n");
1175 }
1176
1177 void assert_fdi_rx_pll(struct drm_i915_private *dev_priv,
1178                        enum pipe pipe, bool state)
1179 {
1180         u32 val;
1181         bool cur_state;
1182
1183         val = I915_READ(FDI_RX_CTL(pipe));
1184         cur_state = !!(val & FDI_RX_PLL_ENABLE);
1185         I915_STATE_WARN(cur_state != state,
1186              "FDI RX PLL assertion failure (expected %s, current %s)\n",
1187                         onoff(state), onoff(cur_state));
1188 }
1189
1190 void assert_panel_unlocked(struct drm_i915_private *dev_priv, enum pipe pipe)
1191 {
1192         i915_reg_t pp_reg;
1193         u32 val;
1194         enum pipe panel_pipe = PIPE_A;
1195         bool locked = true;
1196
1197         if (WARN_ON(HAS_DDI(dev_priv)))
1198                 return;
1199
1200         if (HAS_PCH_SPLIT(dev_priv)) {
1201                 u32 port_sel;
1202
1203                 pp_reg = PP_CONTROL(0);
1204                 port_sel = I915_READ(PP_ON_DELAYS(0)) & PANEL_PORT_SELECT_MASK;
1205
1206                 if (port_sel == PANEL_PORT_SELECT_LVDS &&
1207                     I915_READ(PCH_LVDS) & LVDS_PIPEB_SELECT)
1208                         panel_pipe = PIPE_B;
1209                 /* XXX: else fix for eDP */
1210         } else if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv)) {
1211                 /* presumably write lock depends on pipe, not port select */
1212                 pp_reg = PP_CONTROL(pipe);
1213                 panel_pipe = pipe;
1214         } else {
1215                 pp_reg = PP_CONTROL(0);
1216                 if (I915_READ(LVDS) & LVDS_PIPEB_SELECT)
1217                         panel_pipe = PIPE_B;
1218         }
1219
1220         val = I915_READ(pp_reg);
1221         if (!(val & PANEL_POWER_ON) ||
1222             ((val & PANEL_UNLOCK_MASK) == PANEL_UNLOCK_REGS))
1223                 locked = false;
1224
1225         I915_STATE_WARN(panel_pipe == pipe && locked,
1226              "panel assertion failure, pipe %c regs locked\n",
1227              pipe_name(pipe));
1228 }
1229
1230 static void assert_cursor(struct drm_i915_private *dev_priv,
1231                           enum pipe pipe, bool state)
1232 {
1233         bool cur_state;
1234
1235         if (IS_845G(dev_priv) || IS_I865G(dev_priv))
1236                 cur_state = I915_READ(CURCNTR(PIPE_A)) & CURSOR_ENABLE;
1237         else
1238                 cur_state = I915_READ(CURCNTR(pipe)) & CURSOR_MODE;
1239
1240         I915_STATE_WARN(cur_state != state,
1241              "cursor on pipe %c assertion failure (expected %s, current %s)\n",
1242                         pipe_name(pipe), onoff(state), onoff(cur_state));
1243 }
1244 #define assert_cursor_enabled(d, p) assert_cursor(d, p, true)
1245 #define assert_cursor_disabled(d, p) assert_cursor(d, p, false)
1246
1247 void assert_pipe(struct drm_i915_private *dev_priv,
1248                  enum pipe pipe, bool state)
1249 {
1250         bool cur_state;
1251         enum transcoder cpu_transcoder = intel_pipe_to_cpu_transcoder(dev_priv,
1252                                                                       pipe);
1253         enum intel_display_power_domain power_domain;
1254
1255         /* if we need the pipe quirk it must be always on */
1256         if ((pipe == PIPE_A && dev_priv->quirks & QUIRK_PIPEA_FORCE) ||
1257             (pipe == PIPE_B && dev_priv->quirks & QUIRK_PIPEB_FORCE))
1258                 state = true;
1259
1260         power_domain = POWER_DOMAIN_TRANSCODER(cpu_transcoder);
1261         if (intel_display_power_get_if_enabled(dev_priv, power_domain)) {
1262                 u32 val = I915_READ(PIPECONF(cpu_transcoder));
1263                 cur_state = !!(val & PIPECONF_ENABLE);
1264
1265                 intel_display_power_put(dev_priv, power_domain);
1266         } else {
1267                 cur_state = false;
1268         }
1269
1270         I915_STATE_WARN(cur_state != state,
1271              "pipe %c assertion failure (expected %s, current %s)\n",
1272                         pipe_name(pipe), onoff(state), onoff(cur_state));
1273 }
1274
1275 static void assert_plane(struct drm_i915_private *dev_priv,
1276                          enum plane plane, bool state)
1277 {
1278         u32 val;
1279         bool cur_state;
1280
1281         val = I915_READ(DSPCNTR(plane));
1282         cur_state = !!(val & DISPLAY_PLANE_ENABLE);
1283         I915_STATE_WARN(cur_state != state,
1284              "plane %c assertion failure (expected %s, current %s)\n",
1285                         plane_name(plane), onoff(state), onoff(cur_state));
1286 }
1287
1288 #define assert_plane_enabled(d, p) assert_plane(d, p, true)
1289 #define assert_plane_disabled(d, p) assert_plane(d, p, false)
1290
1291 static void assert_planes_disabled(struct drm_i915_private *dev_priv,
1292                                    enum pipe pipe)
1293 {
1294         int i;
1295
1296         /* Primary planes are fixed to pipes on gen4+ */
1297         if (INTEL_GEN(dev_priv) >= 4) {
1298                 u32 val = I915_READ(DSPCNTR(pipe));
1299                 I915_STATE_WARN(val & DISPLAY_PLANE_ENABLE,
1300                      "plane %c assertion failure, should be disabled but not\n",
1301                      plane_name(pipe));
1302                 return;
1303         }
1304
1305         /* Need to check both planes against the pipe */
1306         for_each_pipe(dev_priv, i) {
1307                 u32 val = I915_READ(DSPCNTR(i));
1308                 enum pipe cur_pipe = (val & DISPPLANE_SEL_PIPE_MASK) >>
1309                         DISPPLANE_SEL_PIPE_SHIFT;
1310                 I915_STATE_WARN((val & DISPLAY_PLANE_ENABLE) && pipe == cur_pipe,
1311                      "plane %c assertion failure, should be off on pipe %c but is still active\n",
1312                      plane_name(i), pipe_name(pipe));
1313         }
1314 }
1315
1316 static void assert_sprites_disabled(struct drm_i915_private *dev_priv,
1317                                     enum pipe pipe)
1318 {
1319         int sprite;
1320
1321         if (INTEL_GEN(dev_priv) >= 9) {
1322                 for_each_sprite(dev_priv, pipe, sprite) {
1323                         u32 val = I915_READ(PLANE_CTL(pipe, sprite));
1324                         I915_STATE_WARN(val & PLANE_CTL_ENABLE,
1325                              "plane %d assertion failure, should be off on pipe %c but is still active\n",
1326                              sprite, pipe_name(pipe));
1327                 }
1328         } else if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv)) {
1329                 for_each_sprite(dev_priv, pipe, sprite) {
1330                         u32 val = I915_READ(SPCNTR(pipe, sprite));
1331                         I915_STATE_WARN(val & SP_ENABLE,
1332                              "sprite %c assertion failure, should be off on pipe %c but is still active\n",
1333                              sprite_name(pipe, sprite), pipe_name(pipe));
1334                 }
1335         } else if (INTEL_GEN(dev_priv) >= 7) {
1336                 u32 val = I915_READ(SPRCTL(pipe));
1337                 I915_STATE_WARN(val & SPRITE_ENABLE,
1338                      "sprite %c assertion failure, should be off on pipe %c but is still active\n",
1339                      plane_name(pipe), pipe_name(pipe));
1340         } else if (INTEL_GEN(dev_priv) >= 5) {
1341                 u32 val = I915_READ(DVSCNTR(pipe));
1342                 I915_STATE_WARN(val & DVS_ENABLE,
1343                      "sprite %c assertion failure, should be off on pipe %c but is still active\n",
1344                      plane_name(pipe), pipe_name(pipe));
1345         }
1346 }
1347
1348 static void assert_vblank_disabled(struct drm_crtc *crtc)
1349 {
1350         if (I915_STATE_WARN_ON(drm_crtc_vblank_get(crtc) == 0))
1351                 drm_crtc_vblank_put(crtc);
1352 }
1353
1354 void assert_pch_transcoder_disabled(struct drm_i915_private *dev_priv,
1355                                     enum pipe pipe)
1356 {
1357         u32 val;
1358         bool enabled;
1359
1360         val = I915_READ(PCH_TRANSCONF(pipe));
1361         enabled = !!(val & TRANS_ENABLE);
1362         I915_STATE_WARN(enabled,
1363              "transcoder assertion failed, should be off on pipe %c but is still active\n",
1364              pipe_name(pipe));
1365 }
1366
1367 static bool dp_pipe_enabled(struct drm_i915_private *dev_priv,
1368                             enum pipe pipe, u32 port_sel, u32 val)
1369 {
1370         if ((val & DP_PORT_EN) == 0)
1371                 return false;
1372
1373         if (HAS_PCH_CPT(dev_priv)) {
1374                 u32 trans_dp_ctl = I915_READ(TRANS_DP_CTL(pipe));
1375                 if ((trans_dp_ctl & TRANS_DP_PORT_SEL_MASK) != port_sel)
1376                         return false;
1377         } else if (IS_CHERRYVIEW(dev_priv)) {
1378                 if ((val & DP_PIPE_MASK_CHV) != DP_PIPE_SELECT_CHV(pipe))
1379                         return false;
1380         } else {
1381                 if ((val & DP_PIPE_MASK) != (pipe << 30))
1382                         return false;
1383         }
1384         return true;
1385 }
1386
1387 static bool hdmi_pipe_enabled(struct drm_i915_private *dev_priv,
1388                               enum pipe pipe, u32 val)
1389 {
1390         if ((val & SDVO_ENABLE) == 0)
1391                 return false;
1392
1393         if (HAS_PCH_CPT(dev_priv)) {
1394                 if ((val & SDVO_PIPE_SEL_MASK_CPT) != SDVO_PIPE_SEL_CPT(pipe))
1395                         return false;
1396         } else if (IS_CHERRYVIEW(dev_priv)) {
1397                 if ((val & SDVO_PIPE_SEL_MASK_CHV) != SDVO_PIPE_SEL_CHV(pipe))
1398                         return false;
1399         } else {
1400                 if ((val & SDVO_PIPE_SEL_MASK) != SDVO_PIPE_SEL(pipe))
1401                         return false;
1402         }
1403         return true;
1404 }
1405
1406 static bool lvds_pipe_enabled(struct drm_i915_private *dev_priv,
1407                               enum pipe pipe, u32 val)
1408 {
1409         if ((val & LVDS_PORT_EN) == 0)
1410                 return false;
1411
1412         if (HAS_PCH_CPT(dev_priv)) {
1413                 if ((val & PORT_TRANS_SEL_MASK) != PORT_TRANS_SEL_CPT(pipe))
1414                         return false;
1415         } else {
1416                 if ((val & LVDS_PIPE_MASK) != LVDS_PIPE(pipe))
1417                         return false;
1418         }
1419         return true;
1420 }
1421
1422 static bool adpa_pipe_enabled(struct drm_i915_private *dev_priv,
1423                               enum pipe pipe, u32 val)
1424 {
1425         if ((val & ADPA_DAC_ENABLE) == 0)
1426                 return false;
1427         if (HAS_PCH_CPT(dev_priv)) {
1428                 if ((val & PORT_TRANS_SEL_MASK) != PORT_TRANS_SEL_CPT(pipe))
1429                         return false;
1430         } else {
1431                 if ((val & ADPA_PIPE_SELECT_MASK) != ADPA_PIPE_SELECT(pipe))
1432                         return false;
1433         }
1434         return true;
1435 }
1436
1437 static void assert_pch_dp_disabled(struct drm_i915_private *dev_priv,
1438                                    enum pipe pipe, i915_reg_t reg,
1439                                    u32 port_sel)
1440 {
1441         u32 val = I915_READ(reg);
1442         I915_STATE_WARN(dp_pipe_enabled(dev_priv, pipe, port_sel, val),
1443              "PCH DP (0x%08x) enabled on transcoder %c, should be disabled\n",
1444              i915_mmio_reg_offset(reg), pipe_name(pipe));
1445
1446         I915_STATE_WARN(HAS_PCH_IBX(dev_priv) && (val & DP_PORT_EN) == 0
1447              && (val & DP_PIPEB_SELECT),
1448              "IBX PCH dp port still using transcoder B\n");
1449 }
1450
1451 static void assert_pch_hdmi_disabled(struct drm_i915_private *dev_priv,
1452                                      enum pipe pipe, i915_reg_t reg)
1453 {
1454         u32 val = I915_READ(reg);
1455         I915_STATE_WARN(hdmi_pipe_enabled(dev_priv, pipe, val),
1456              "PCH HDMI (0x%08x) enabled on transcoder %c, should be disabled\n",
1457              i915_mmio_reg_offset(reg), pipe_name(pipe));
1458
1459         I915_STATE_WARN(HAS_PCH_IBX(dev_priv) && (val & SDVO_ENABLE) == 0
1460              && (val & SDVO_PIPE_B_SELECT),
1461              "IBX PCH hdmi port still using transcoder B\n");
1462 }
1463
1464 static void assert_pch_ports_disabled(struct drm_i915_private *dev_priv,
1465                                       enum pipe pipe)
1466 {
1467         u32 val;
1468
1469         assert_pch_dp_disabled(dev_priv, pipe, PCH_DP_B, TRANS_DP_PORT_SEL_B);
1470         assert_pch_dp_disabled(dev_priv, pipe, PCH_DP_C, TRANS_DP_PORT_SEL_C);
1471         assert_pch_dp_disabled(dev_priv, pipe, PCH_DP_D, TRANS_DP_PORT_SEL_D);
1472
1473         val = I915_READ(PCH_ADPA);
1474         I915_STATE_WARN(adpa_pipe_enabled(dev_priv, pipe, val),
1475              "PCH VGA enabled on transcoder %c, should be disabled\n",
1476              pipe_name(pipe));
1477
1478         val = I915_READ(PCH_LVDS);
1479         I915_STATE_WARN(lvds_pipe_enabled(dev_priv, pipe, val),
1480              "PCH LVDS enabled on transcoder %c, should be disabled\n",
1481              pipe_name(pipe));
1482
1483         assert_pch_hdmi_disabled(dev_priv, pipe, PCH_HDMIB);
1484         assert_pch_hdmi_disabled(dev_priv, pipe, PCH_HDMIC);
1485         assert_pch_hdmi_disabled(dev_priv, pipe, PCH_HDMID);
1486 }
1487
1488 static void _vlv_enable_pll(struct intel_crtc *crtc,
1489                             const struct intel_crtc_state *pipe_config)
1490 {
1491         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1492         enum pipe pipe = crtc->pipe;
1493
1494         I915_WRITE(DPLL(pipe), pipe_config->dpll_hw_state.dpll);
1495         POSTING_READ(DPLL(pipe));
1496         udelay(150);
1497
1498         if (intel_wait_for_register(dev_priv,
1499                                     DPLL(pipe),
1500                                     DPLL_LOCK_VLV,
1501                                     DPLL_LOCK_VLV,
1502                                     1))
1503                 DRM_ERROR("DPLL %d failed to lock\n", pipe);
1504 }
1505
1506 static void vlv_enable_pll(struct intel_crtc *crtc,
1507                            const struct intel_crtc_state *pipe_config)
1508 {
1509         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1510         enum pipe pipe = crtc->pipe;
1511
1512         assert_pipe_disabled(dev_priv, pipe);
1513
1514         /* PLL is protected by panel, make sure we can write it */
1515         assert_panel_unlocked(dev_priv, pipe);
1516
1517         if (pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE)
1518                 _vlv_enable_pll(crtc, pipe_config);
1519
1520         I915_WRITE(DPLL_MD(pipe), pipe_config->dpll_hw_state.dpll_md);
1521         POSTING_READ(DPLL_MD(pipe));
1522 }
1523
1524
1525 static void _chv_enable_pll(struct intel_crtc *crtc,
1526                             const struct intel_crtc_state *pipe_config)
1527 {
1528         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1529         enum pipe pipe = crtc->pipe;
1530         enum dpio_channel port = vlv_pipe_to_channel(pipe);
1531         u32 tmp;
1532
1533         mutex_lock(&dev_priv->sb_lock);
1534
1535         /* Enable back the 10bit clock to display controller */
1536         tmp = vlv_dpio_read(dev_priv, pipe, CHV_CMN_DW14(port));
1537         tmp |= DPIO_DCLKP_EN;
1538         vlv_dpio_write(dev_priv, pipe, CHV_CMN_DW14(port), tmp);
1539
1540         mutex_unlock(&dev_priv->sb_lock);
1541
1542         /*
1543          * Need to wait > 100ns between dclkp clock enable bit and PLL enable.
1544          */
1545         udelay(1);
1546
1547         /* Enable PLL */
1548         I915_WRITE(DPLL(pipe), pipe_config->dpll_hw_state.dpll);
1549
1550         /* Check PLL is locked */
1551         if (intel_wait_for_register(dev_priv,
1552                                     DPLL(pipe), DPLL_LOCK_VLV, DPLL_LOCK_VLV,
1553                                     1))
1554                 DRM_ERROR("PLL %d failed to lock\n", pipe);
1555 }
1556
1557 static void chv_enable_pll(struct intel_crtc *crtc,
1558                            const struct intel_crtc_state *pipe_config)
1559 {
1560         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1561         enum pipe pipe = crtc->pipe;
1562
1563         assert_pipe_disabled(dev_priv, pipe);
1564
1565         /* PLL is protected by panel, make sure we can write it */
1566         assert_panel_unlocked(dev_priv, pipe);
1567
1568         if (pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE)
1569                 _chv_enable_pll(crtc, pipe_config);
1570
1571         if (pipe != PIPE_A) {
1572                 /*
1573                  * WaPixelRepeatModeFixForC0:chv
1574                  *
1575                  * DPLLCMD is AWOL. Use chicken bits to propagate
1576                  * the value from DPLLBMD to either pipe B or C.
1577                  */
1578                 I915_WRITE(CBR4_VLV, pipe == PIPE_B ? CBR_DPLLBMD_PIPE_B : CBR_DPLLBMD_PIPE_C);
1579                 I915_WRITE(DPLL_MD(PIPE_B), pipe_config->dpll_hw_state.dpll_md);
1580                 I915_WRITE(CBR4_VLV, 0);
1581                 dev_priv->chv_dpll_md[pipe] = pipe_config->dpll_hw_state.dpll_md;
1582
1583                 /*
1584                  * DPLLB VGA mode also seems to cause problems.
1585                  * We should always have it disabled.
1586                  */
1587                 WARN_ON((I915_READ(DPLL(PIPE_B)) & DPLL_VGA_MODE_DIS) == 0);
1588         } else {
1589                 I915_WRITE(DPLL_MD(pipe), pipe_config->dpll_hw_state.dpll_md);
1590                 POSTING_READ(DPLL_MD(pipe));
1591         }
1592 }
1593
1594 static int intel_num_dvo_pipes(struct drm_i915_private *dev_priv)
1595 {
1596         struct intel_crtc *crtc;
1597         int count = 0;
1598
1599         for_each_intel_crtc(&dev_priv->drm, crtc) {
1600                 count += crtc->base.state->active &&
1601                         intel_crtc_has_type(crtc->config, INTEL_OUTPUT_DVO);
1602         }
1603
1604         return count;
1605 }
1606
1607 static void i9xx_enable_pll(struct intel_crtc *crtc)
1608 {
1609         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1610         i915_reg_t reg = DPLL(crtc->pipe);
1611         u32 dpll = crtc->config->dpll_hw_state.dpll;
1612
1613         assert_pipe_disabled(dev_priv, crtc->pipe);
1614
1615         /* PLL is protected by panel, make sure we can write it */
1616         if (IS_MOBILE(dev_priv) && !IS_I830(dev_priv))
1617                 assert_panel_unlocked(dev_priv, crtc->pipe);
1618
1619         /* Enable DVO 2x clock on both PLLs if necessary */
1620         if (IS_I830(dev_priv) && intel_num_dvo_pipes(dev_priv) > 0) {
1621                 /*
1622                  * It appears to be important that we don't enable this
1623                  * for the current pipe before otherwise configuring the
1624                  * PLL. No idea how this should be handled if multiple
1625                  * DVO outputs are enabled simultaneosly.
1626                  */
1627                 dpll |= DPLL_DVO_2X_MODE;
1628                 I915_WRITE(DPLL(!crtc->pipe),
1629                            I915_READ(DPLL(!crtc->pipe)) | DPLL_DVO_2X_MODE);
1630         }
1631
1632         /*
1633          * Apparently we need to have VGA mode enabled prior to changing
1634          * the P1/P2 dividers. Otherwise the DPLL will keep using the old
1635          * dividers, even though the register value does change.
1636          */
1637         I915_WRITE(reg, 0);
1638
1639         I915_WRITE(reg, dpll);
1640
1641         /* Wait for the clocks to stabilize. */
1642         POSTING_READ(reg);
1643         udelay(150);
1644
1645         if (INTEL_GEN(dev_priv) >= 4) {
1646                 I915_WRITE(DPLL_MD(crtc->pipe),
1647                            crtc->config->dpll_hw_state.dpll_md);
1648         } else {
1649                 /* The pixel multiplier can only be updated once the
1650                  * DPLL is enabled and the clocks are stable.
1651                  *
1652                  * So write it again.
1653                  */
1654                 I915_WRITE(reg, dpll);
1655         }
1656
1657         /* We do this three times for luck */
1658         I915_WRITE(reg, dpll);
1659         POSTING_READ(reg);
1660         udelay(150); /* wait for warmup */
1661         I915_WRITE(reg, dpll);
1662         POSTING_READ(reg);
1663         udelay(150); /* wait for warmup */
1664         I915_WRITE(reg, dpll);
1665         POSTING_READ(reg);
1666         udelay(150); /* wait for warmup */
1667 }
1668
1669 /**
1670  * i9xx_disable_pll - disable a PLL
1671  * @dev_priv: i915 private structure
1672  * @pipe: pipe PLL to disable
1673  *
1674  * Disable the PLL for @pipe, making sure the pipe is off first.
1675  *
1676  * Note!  This is for pre-ILK only.
1677  */
1678 static void i9xx_disable_pll(struct intel_crtc *crtc)
1679 {
1680         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1681         enum pipe pipe = crtc->pipe;
1682
1683         /* Disable DVO 2x clock on both PLLs if necessary */
1684         if (IS_I830(dev_priv) &&
1685             intel_crtc_has_type(crtc->config, INTEL_OUTPUT_DVO) &&
1686             !intel_num_dvo_pipes(dev_priv)) {
1687                 I915_WRITE(DPLL(PIPE_B),
1688                            I915_READ(DPLL(PIPE_B)) & ~DPLL_DVO_2X_MODE);
1689                 I915_WRITE(DPLL(PIPE_A),
1690                            I915_READ(DPLL(PIPE_A)) & ~DPLL_DVO_2X_MODE);
1691         }
1692
1693         /* Don't disable pipe or pipe PLLs if needed */
1694         if ((pipe == PIPE_A && dev_priv->quirks & QUIRK_PIPEA_FORCE) ||
1695             (pipe == PIPE_B && dev_priv->quirks & QUIRK_PIPEB_FORCE))
1696                 return;
1697
1698         /* Make sure the pipe isn't still relying on us */
1699         assert_pipe_disabled(dev_priv, pipe);
1700
1701         I915_WRITE(DPLL(pipe), DPLL_VGA_MODE_DIS);
1702         POSTING_READ(DPLL(pipe));
1703 }
1704
1705 static void vlv_disable_pll(struct drm_i915_private *dev_priv, enum pipe pipe)
1706 {
1707         u32 val;
1708
1709         /* Make sure the pipe isn't still relying on us */
1710         assert_pipe_disabled(dev_priv, pipe);
1711
1712         val = DPLL_INTEGRATED_REF_CLK_VLV |
1713                 DPLL_REF_CLK_ENABLE_VLV | DPLL_VGA_MODE_DIS;
1714         if (pipe != PIPE_A)
1715                 val |= DPLL_INTEGRATED_CRI_CLK_VLV;
1716
1717         I915_WRITE(DPLL(pipe), val);
1718         POSTING_READ(DPLL(pipe));
1719 }
1720
1721 static void chv_disable_pll(struct drm_i915_private *dev_priv, enum pipe pipe)
1722 {
1723         enum dpio_channel port = vlv_pipe_to_channel(pipe);
1724         u32 val;
1725
1726         /* Make sure the pipe isn't still relying on us */
1727         assert_pipe_disabled(dev_priv, pipe);
1728
1729         val = DPLL_SSC_REF_CLK_CHV |
1730                 DPLL_REF_CLK_ENABLE_VLV | DPLL_VGA_MODE_DIS;
1731         if (pipe != PIPE_A)
1732                 val |= DPLL_INTEGRATED_CRI_CLK_VLV;
1733
1734         I915_WRITE(DPLL(pipe), val);
1735         POSTING_READ(DPLL(pipe));
1736
1737         mutex_lock(&dev_priv->sb_lock);
1738
1739         /* Disable 10bit clock to display controller */
1740         val = vlv_dpio_read(dev_priv, pipe, CHV_CMN_DW14(port));
1741         val &= ~DPIO_DCLKP_EN;
1742         vlv_dpio_write(dev_priv, pipe, CHV_CMN_DW14(port), val);
1743
1744         mutex_unlock(&dev_priv->sb_lock);
1745 }
1746
1747 void vlv_wait_port_ready(struct drm_i915_private *dev_priv,
1748                          struct intel_digital_port *dport,
1749                          unsigned int expected_mask)
1750 {
1751         u32 port_mask;
1752         i915_reg_t dpll_reg;
1753
1754         switch (dport->port) {
1755         case PORT_B:
1756                 port_mask = DPLL_PORTB_READY_MASK;
1757                 dpll_reg = DPLL(0);
1758                 break;
1759         case PORT_C:
1760                 port_mask = DPLL_PORTC_READY_MASK;
1761                 dpll_reg = DPLL(0);
1762                 expected_mask <<= 4;
1763                 break;
1764         case PORT_D:
1765                 port_mask = DPLL_PORTD_READY_MASK;
1766                 dpll_reg = DPIO_PHY_STATUS;
1767                 break;
1768         default:
1769                 BUG();
1770         }
1771
1772         if (intel_wait_for_register(dev_priv,
1773                                     dpll_reg, port_mask, expected_mask,
1774                                     1000))
1775                 WARN(1, "timed out waiting for port %c ready: got 0x%x, expected 0x%x\n",
1776                      port_name(dport->port), I915_READ(dpll_reg) & port_mask, expected_mask);
1777 }
1778
1779 static void ironlake_enable_pch_transcoder(struct drm_i915_private *dev_priv,
1780                                            enum pipe pipe)
1781 {
1782         struct intel_crtc *intel_crtc = intel_get_crtc_for_pipe(dev_priv,
1783                                                                 pipe);
1784         i915_reg_t reg;
1785         uint32_t val, pipeconf_val;
1786
1787         /* Make sure PCH DPLL is enabled */
1788         assert_shared_dpll_enabled(dev_priv, intel_crtc->config->shared_dpll);
1789
1790         /* FDI must be feeding us bits for PCH ports */
1791         assert_fdi_tx_enabled(dev_priv, pipe);
1792         assert_fdi_rx_enabled(dev_priv, pipe);
1793
1794         if (HAS_PCH_CPT(dev_priv)) {
1795                 /* Workaround: Set the timing override bit before enabling the
1796                  * pch transcoder. */
1797                 reg = TRANS_CHICKEN2(pipe);
1798                 val = I915_READ(reg);
1799                 val |= TRANS_CHICKEN2_TIMING_OVERRIDE;
1800                 I915_WRITE(reg, val);
1801         }
1802
1803         reg = PCH_TRANSCONF(pipe);
1804         val = I915_READ(reg);
1805         pipeconf_val = I915_READ(PIPECONF(pipe));
1806
1807         if (HAS_PCH_IBX(dev_priv)) {
1808                 /*
1809                  * Make the BPC in transcoder be consistent with
1810                  * that in pipeconf reg. For HDMI we must use 8bpc
1811                  * here for both 8bpc and 12bpc.
1812                  */
1813                 val &= ~PIPECONF_BPC_MASK;
1814                 if (intel_crtc_has_type(intel_crtc->config, INTEL_OUTPUT_HDMI))
1815                         val |= PIPECONF_8BPC;
1816                 else
1817                         val |= pipeconf_val & PIPECONF_BPC_MASK;
1818         }
1819
1820         val &= ~TRANS_INTERLACE_MASK;
1821         if ((pipeconf_val & PIPECONF_INTERLACE_MASK) == PIPECONF_INTERLACED_ILK)
1822                 if (HAS_PCH_IBX(dev_priv) &&
1823                     intel_crtc_has_type(intel_crtc->config, INTEL_OUTPUT_SDVO))
1824                         val |= TRANS_LEGACY_INTERLACED_ILK;
1825                 else
1826                         val |= TRANS_INTERLACED;
1827         else
1828                 val |= TRANS_PROGRESSIVE;
1829
1830         I915_WRITE(reg, val | TRANS_ENABLE);
1831         if (intel_wait_for_register(dev_priv,
1832                                     reg, TRANS_STATE_ENABLE, TRANS_STATE_ENABLE,
1833                                     100))
1834                 DRM_ERROR("failed to enable transcoder %c\n", pipe_name(pipe));
1835 }
1836
1837 static void lpt_enable_pch_transcoder(struct drm_i915_private *dev_priv,
1838                                       enum transcoder cpu_transcoder)
1839 {
1840         u32 val, pipeconf_val;
1841
1842         /* FDI must be feeding us bits for PCH ports */
1843         assert_fdi_tx_enabled(dev_priv, (enum pipe) cpu_transcoder);
1844         assert_fdi_rx_enabled(dev_priv, TRANSCODER_A);
1845
1846         /* Workaround: set timing override bit. */
1847         val = I915_READ(TRANS_CHICKEN2(PIPE_A));
1848         val |= TRANS_CHICKEN2_TIMING_OVERRIDE;
1849         I915_WRITE(TRANS_CHICKEN2(PIPE_A), val);
1850
1851         val = TRANS_ENABLE;
1852         pipeconf_val = I915_READ(PIPECONF(cpu_transcoder));
1853
1854         if ((pipeconf_val & PIPECONF_INTERLACE_MASK_HSW) ==
1855             PIPECONF_INTERLACED_ILK)
1856                 val |= TRANS_INTERLACED;
1857         else
1858                 val |= TRANS_PROGRESSIVE;
1859
1860         I915_WRITE(LPT_TRANSCONF, val);
1861         if (intel_wait_for_register(dev_priv,
1862                                     LPT_TRANSCONF,
1863                                     TRANS_STATE_ENABLE,
1864                                     TRANS_STATE_ENABLE,
1865                                     100))
1866                 DRM_ERROR("Failed to enable PCH transcoder\n");
1867 }
1868
1869 static void ironlake_disable_pch_transcoder(struct drm_i915_private *dev_priv,
1870                                             enum pipe pipe)
1871 {
1872         i915_reg_t reg;
1873         uint32_t val;
1874
1875         /* FDI relies on the transcoder */
1876         assert_fdi_tx_disabled(dev_priv, pipe);
1877         assert_fdi_rx_disabled(dev_priv, pipe);
1878
1879         /* Ports must be off as well */
1880         assert_pch_ports_disabled(dev_priv, pipe);
1881
1882         reg = PCH_TRANSCONF(pipe);
1883         val = I915_READ(reg);
1884         val &= ~TRANS_ENABLE;
1885         I915_WRITE(reg, val);
1886         /* wait for PCH transcoder off, transcoder state */
1887         if (intel_wait_for_register(dev_priv,
1888                                     reg, TRANS_STATE_ENABLE, 0,
1889                                     50))
1890                 DRM_ERROR("failed to disable transcoder %c\n", pipe_name(pipe));
1891
1892         if (HAS_PCH_CPT(dev_priv)) {
1893                 /* Workaround: Clear the timing override chicken bit again. */
1894                 reg = TRANS_CHICKEN2(pipe);
1895                 val = I915_READ(reg);
1896                 val &= ~TRANS_CHICKEN2_TIMING_OVERRIDE;
1897                 I915_WRITE(reg, val);
1898         }
1899 }
1900
1901 void lpt_disable_pch_transcoder(struct drm_i915_private *dev_priv)
1902 {
1903         u32 val;
1904
1905         val = I915_READ(LPT_TRANSCONF);
1906         val &= ~TRANS_ENABLE;
1907         I915_WRITE(LPT_TRANSCONF, val);
1908         /* wait for PCH transcoder off, transcoder state */
1909         if (intel_wait_for_register(dev_priv,
1910                                     LPT_TRANSCONF, TRANS_STATE_ENABLE, 0,
1911                                     50))
1912                 DRM_ERROR("Failed to disable PCH transcoder\n");
1913
1914         /* Workaround: clear timing override bit. */
1915         val = I915_READ(TRANS_CHICKEN2(PIPE_A));
1916         val &= ~TRANS_CHICKEN2_TIMING_OVERRIDE;
1917         I915_WRITE(TRANS_CHICKEN2(PIPE_A), val);
1918 }
1919
1920 enum transcoder intel_crtc_pch_transcoder(struct intel_crtc *crtc)
1921 {
1922         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1923
1924         WARN_ON(!crtc->config->has_pch_encoder);
1925
1926         if (HAS_PCH_LPT(dev_priv))
1927                 return TRANSCODER_A;
1928         else
1929                 return (enum transcoder) crtc->pipe;
1930 }
1931
1932 /**
1933  * intel_enable_pipe - enable a pipe, asserting requirements
1934  * @crtc: crtc responsible for the pipe
1935  *
1936  * Enable @crtc's pipe, making sure that various hardware specific requirements
1937  * are met, if applicable, e.g. PLL enabled, LVDS pairs enabled, etc.
1938  */
1939 static void intel_enable_pipe(struct intel_crtc *crtc)
1940 {
1941         struct drm_device *dev = crtc->base.dev;
1942         struct drm_i915_private *dev_priv = to_i915(dev);
1943         enum pipe pipe = crtc->pipe;
1944         enum transcoder cpu_transcoder = crtc->config->cpu_transcoder;
1945         i915_reg_t reg;
1946         u32 val;
1947
1948         DRM_DEBUG_KMS("enabling pipe %c\n", pipe_name(pipe));
1949
1950         assert_planes_disabled(dev_priv, pipe);
1951         assert_cursor_disabled(dev_priv, pipe);
1952         assert_sprites_disabled(dev_priv, pipe);
1953
1954         /*
1955          * A pipe without a PLL won't actually be able to drive bits from
1956          * a plane.  On ILK+ the pipe PLLs are integrated, so we don't
1957          * need the check.
1958          */
1959         if (HAS_GMCH_DISPLAY(dev_priv)) {
1960                 if (intel_crtc_has_type(crtc->config, INTEL_OUTPUT_DSI))
1961                         assert_dsi_pll_enabled(dev_priv);
1962                 else
1963                         assert_pll_enabled(dev_priv, pipe);
1964         } else {
1965                 if (crtc->config->has_pch_encoder) {
1966                         /* if driving the PCH, we need FDI enabled */
1967                         assert_fdi_rx_pll_enabled(dev_priv,
1968                                                   (enum pipe) intel_crtc_pch_transcoder(crtc));
1969                         assert_fdi_tx_pll_enabled(dev_priv,
1970                                                   (enum pipe) cpu_transcoder);
1971                 }
1972                 /* FIXME: assert CPU port conditions for SNB+ */
1973         }
1974
1975         reg = PIPECONF(cpu_transcoder);
1976         val = I915_READ(reg);
1977         if (val & PIPECONF_ENABLE) {
1978                 WARN_ON(!((pipe == PIPE_A && dev_priv->quirks & QUIRK_PIPEA_FORCE) ||
1979                           (pipe == PIPE_B && dev_priv->quirks & QUIRK_PIPEB_FORCE)));
1980                 return;
1981         }
1982
1983         I915_WRITE(reg, val | PIPECONF_ENABLE);
1984         POSTING_READ(reg);
1985
1986         /*
1987          * Until the pipe starts DSL will read as 0, which would cause
1988          * an apparent vblank timestamp jump, which messes up also the
1989          * frame count when it's derived from the timestamps. So let's
1990          * wait for the pipe to start properly before we call
1991          * drm_crtc_vblank_on()
1992          */
1993         if (dev->max_vblank_count == 0 &&
1994             wait_for(intel_get_crtc_scanline(crtc) != crtc->scanline_offset, 50))
1995                 DRM_ERROR("pipe %c didn't start\n", pipe_name(pipe));
1996 }
1997
1998 /**
1999  * intel_disable_pipe - disable a pipe, asserting requirements
2000  * @crtc: crtc whose pipes is to be disabled
2001  *
2002  * Disable the pipe of @crtc, making sure that various hardware
2003  * specific requirements are met, if applicable, e.g. plane
2004  * disabled, panel fitter off, etc.
2005  *
2006  * Will wait until the pipe has shut down before returning.
2007  */
2008 static void intel_disable_pipe(struct intel_crtc *crtc)
2009 {
2010         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
2011         enum transcoder cpu_transcoder = crtc->config->cpu_transcoder;
2012         enum pipe pipe = crtc->pipe;
2013         i915_reg_t reg;
2014         u32 val;
2015
2016         DRM_DEBUG_KMS("disabling pipe %c\n", pipe_name(pipe));
2017
2018         /*
2019          * Make sure planes won't keep trying to pump pixels to us,
2020          * or we might hang the display.
2021          */
2022         assert_planes_disabled(dev_priv, pipe);
2023         assert_cursor_disabled(dev_priv, pipe);
2024         assert_sprites_disabled(dev_priv, pipe);
2025
2026         reg = PIPECONF(cpu_transcoder);
2027         val = I915_READ(reg);
2028         if ((val & PIPECONF_ENABLE) == 0)
2029                 return;
2030
2031         /*
2032          * Double wide has implications for planes
2033          * so best keep it disabled when not needed.
2034          */
2035         if (crtc->config->double_wide)
2036                 val &= ~PIPECONF_DOUBLE_WIDE;
2037
2038         /* Don't disable pipe or pipe PLLs if needed */
2039         if (!(pipe == PIPE_A && dev_priv->quirks & QUIRK_PIPEA_FORCE) &&
2040             !(pipe == PIPE_B && dev_priv->quirks & QUIRK_PIPEB_FORCE))
2041                 val &= ~PIPECONF_ENABLE;
2042
2043         I915_WRITE(reg, val);
2044         if ((val & PIPECONF_ENABLE) == 0)
2045                 intel_wait_for_pipe_off(crtc);
2046 }
2047
2048 static unsigned int intel_tile_size(const struct drm_i915_private *dev_priv)
2049 {
2050         return IS_GEN2(dev_priv) ? 2048 : 4096;
2051 }
2052
2053 static unsigned int intel_tile_width_bytes(const struct drm_i915_private *dev_priv,
2054                                            uint64_t fb_modifier, unsigned int cpp)
2055 {
2056         switch (fb_modifier) {
2057         case DRM_FORMAT_MOD_NONE:
2058                 return cpp;
2059         case I915_FORMAT_MOD_X_TILED:
2060                 if (IS_GEN2(dev_priv))
2061                         return 128;
2062                 else
2063                         return 512;
2064         case I915_FORMAT_MOD_Y_TILED:
2065                 if (IS_GEN2(dev_priv) || HAS_128_BYTE_Y_TILING(dev_priv))
2066                         return 128;
2067                 else
2068                         return 512;
2069         case I915_FORMAT_MOD_Yf_TILED:
2070                 switch (cpp) {
2071                 case 1:
2072                         return 64;
2073                 case 2:
2074                 case 4:
2075                         return 128;
2076                 case 8:
2077                 case 16:
2078                         return 256;
2079                 default:
2080                         MISSING_CASE(cpp);
2081                         return cpp;
2082                 }
2083                 break;
2084         default:
2085                 MISSING_CASE(fb_modifier);
2086                 return cpp;
2087         }
2088 }
2089
2090 unsigned int intel_tile_height(const struct drm_i915_private *dev_priv,
2091                                uint64_t fb_modifier, unsigned int cpp)
2092 {
2093         if (fb_modifier == DRM_FORMAT_MOD_NONE)
2094                 return 1;
2095         else
2096                 return intel_tile_size(dev_priv) /
2097                         intel_tile_width_bytes(dev_priv, fb_modifier, cpp);
2098 }
2099
2100 /* Return the tile dimensions in pixel units */
2101 static void intel_tile_dims(const struct drm_i915_private *dev_priv,
2102                             unsigned int *tile_width,
2103                             unsigned int *tile_height,
2104                             uint64_t fb_modifier,
2105                             unsigned int cpp)
2106 {
2107         unsigned int tile_width_bytes =
2108                 intel_tile_width_bytes(dev_priv, fb_modifier, cpp);
2109
2110         *tile_width = tile_width_bytes / cpp;
2111         *tile_height = intel_tile_size(dev_priv) / tile_width_bytes;
2112 }
2113
2114 unsigned int
2115 intel_fb_align_height(struct drm_device *dev, unsigned int height,
2116                       uint32_t pixel_format, uint64_t fb_modifier)
2117 {
2118         unsigned int cpp = drm_format_plane_cpp(pixel_format, 0);
2119         unsigned int tile_height = intel_tile_height(to_i915(dev), fb_modifier, cpp);
2120
2121         return ALIGN(height, tile_height);
2122 }
2123
2124 unsigned int intel_rotation_info_size(const struct intel_rotation_info *rot_info)
2125 {
2126         unsigned int size = 0;
2127         int i;
2128
2129         for (i = 0 ; i < ARRAY_SIZE(rot_info->plane); i++)
2130                 size += rot_info->plane[i].width * rot_info->plane[i].height;
2131
2132         return size;
2133 }
2134
2135 static void
2136 intel_fill_fb_ggtt_view(struct i915_ggtt_view *view,
2137                         const struct drm_framebuffer *fb,
2138                         unsigned int rotation)
2139 {
2140         if (drm_rotation_90_or_270(rotation)) {
2141                 *view = i915_ggtt_view_rotated;
2142                 view->params.rotated = to_intel_framebuffer(fb)->rot_info;
2143         } else {
2144                 *view = i915_ggtt_view_normal;
2145         }
2146 }
2147
2148 static unsigned int intel_linear_alignment(const struct drm_i915_private *dev_priv)
2149 {
2150         if (INTEL_INFO(dev_priv)->gen >= 9)
2151                 return 256 * 1024;
2152         else if (IS_BROADWATER(dev_priv) || IS_CRESTLINE(dev_priv) ||
2153                  IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
2154                 return 128 * 1024;
2155         else if (INTEL_INFO(dev_priv)->gen >= 4)
2156                 return 4 * 1024;
2157         else
2158                 return 0;
2159 }
2160
2161 static unsigned int intel_surf_alignment(const struct drm_i915_private *dev_priv,
2162                                          uint64_t fb_modifier)
2163 {
2164         switch (fb_modifier) {
2165         case DRM_FORMAT_MOD_NONE:
2166                 return intel_linear_alignment(dev_priv);
2167         case I915_FORMAT_MOD_X_TILED:
2168                 if (INTEL_INFO(dev_priv)->gen >= 9)
2169                         return 256 * 1024;
2170                 return 0;
2171         case I915_FORMAT_MOD_Y_TILED:
2172         case I915_FORMAT_MOD_Yf_TILED:
2173                 return 1 * 1024 * 1024;
2174         default:
2175                 MISSING_CASE(fb_modifier);
2176                 return 0;
2177         }
2178 }
2179
2180 struct i915_vma *
2181 intel_pin_and_fence_fb_obj(struct drm_framebuffer *fb, unsigned int rotation)
2182 {
2183         struct drm_device *dev = fb->dev;
2184         struct drm_i915_private *dev_priv = to_i915(dev);
2185         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
2186         struct i915_ggtt_view view;
2187         struct i915_vma *vma;
2188         u32 alignment;
2189
2190         WARN_ON(!mutex_is_locked(&dev->struct_mutex));
2191
2192         alignment = intel_surf_alignment(dev_priv, fb->modifier);
2193
2194         intel_fill_fb_ggtt_view(&view, fb, rotation);
2195
2196         /* Note that the w/a also requires 64 PTE of padding following the
2197          * bo. We currently fill all unused PTE with the shadow page and so
2198          * we should always have valid PTE following the scanout preventing
2199          * the VT-d warning.
2200          */
2201         if (intel_scanout_needs_vtd_wa(dev_priv) && alignment < 256 * 1024)
2202                 alignment = 256 * 1024;
2203
2204         /*
2205          * Global gtt pte registers are special registers which actually forward
2206          * writes to a chunk of system memory. Which means that there is no risk
2207          * that the register values disappear as soon as we call
2208          * intel_runtime_pm_put(), so it is correct to wrap only the
2209          * pin/unpin/fence and not more.
2210          */
2211         intel_runtime_pm_get(dev_priv);
2212
2213         vma = i915_gem_object_pin_to_display_plane(obj, alignment, &view);
2214         if (IS_ERR(vma))
2215                 goto err;
2216
2217         if (i915_vma_is_map_and_fenceable(vma)) {
2218                 /* Install a fence for tiled scan-out. Pre-i965 always needs a
2219                  * fence, whereas 965+ only requires a fence if using
2220                  * framebuffer compression.  For simplicity, we always, when
2221                  * possible, install a fence as the cost is not that onerous.
2222                  *
2223                  * If we fail to fence the tiled scanout, then either the
2224                  * modeset will reject the change (which is highly unlikely as
2225                  * the affected systems, all but one, do not have unmappable
2226                  * space) or we will not be able to enable full powersaving
2227                  * techniques (also likely not to apply due to various limits
2228                  * FBC and the like impose on the size of the buffer, which
2229                  * presumably we violated anyway with this unmappable buffer).
2230                  * Anyway, it is presumably better to stumble onwards with
2231                  * something and try to run the system in a "less than optimal"
2232                  * mode that matches the user configuration.
2233                  */
2234                 if (i915_vma_get_fence(vma) == 0)
2235                         i915_vma_pin_fence(vma);
2236         }
2237
2238 err:
2239         intel_runtime_pm_put(dev_priv);
2240         return vma;
2241 }
2242
2243 void intel_unpin_fb_obj(struct drm_framebuffer *fb, unsigned int rotation)
2244 {
2245         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
2246         struct i915_ggtt_view view;
2247         struct i915_vma *vma;
2248
2249         WARN_ON(!mutex_is_locked(&obj->base.dev->struct_mutex));
2250
2251         intel_fill_fb_ggtt_view(&view, fb, rotation);
2252         vma = i915_gem_object_to_ggtt(obj, &view);
2253
2254         i915_vma_unpin_fence(vma);
2255         i915_gem_object_unpin_from_display_plane(vma);
2256 }
2257
2258 static int intel_fb_pitch(const struct drm_framebuffer *fb, int plane,
2259                           unsigned int rotation)
2260 {
2261         if (drm_rotation_90_or_270(rotation))
2262                 return to_intel_framebuffer(fb)->rotated[plane].pitch;
2263         else
2264                 return fb->pitches[plane];
2265 }
2266
2267 /*
2268  * Convert the x/y offsets into a linear offset.
2269  * Only valid with 0/180 degree rotation, which is fine since linear
2270  * offset is only used with linear buffers on pre-hsw and tiled buffers
2271  * with gen2/3, and 90/270 degree rotations isn't supported on any of them.
2272  */
2273 u32 intel_fb_xy_to_linear(int x, int y,
2274                           const struct intel_plane_state *state,
2275                           int plane)
2276 {
2277         const struct drm_framebuffer *fb = state->base.fb;
2278         unsigned int cpp = drm_format_plane_cpp(fb->pixel_format, plane);
2279         unsigned int pitch = fb->pitches[plane];
2280
2281         return y * pitch + x * cpp;
2282 }
2283
2284 /*
2285  * Add the x/y offsets derived from fb->offsets[] to the user
2286  * specified plane src x/y offsets. The resulting x/y offsets
2287  * specify the start of scanout from the beginning of the gtt mapping.
2288  */
2289 void intel_add_fb_offsets(int *x, int *y,
2290                           const struct intel_plane_state *state,
2291                           int plane)
2292
2293 {
2294         const struct intel_framebuffer *intel_fb = to_intel_framebuffer(state->base.fb);
2295         unsigned int rotation = state->base.rotation;
2296
2297         if (drm_rotation_90_or_270(rotation)) {
2298                 *x += intel_fb->rotated[plane].x;
2299                 *y += intel_fb->rotated[plane].y;
2300         } else {
2301                 *x += intel_fb->normal[plane].x;
2302                 *y += intel_fb->normal[plane].y;
2303         }
2304 }
2305
2306 /*
2307  * Input tile dimensions and pitch must already be
2308  * rotated to match x and y, and in pixel units.
2309  */
2310 static u32 _intel_adjust_tile_offset(int *x, int *y,
2311                                      unsigned int tile_width,
2312                                      unsigned int tile_height,
2313                                      unsigned int tile_size,
2314                                      unsigned int pitch_tiles,
2315                                      u32 old_offset,
2316                                      u32 new_offset)
2317 {
2318         unsigned int pitch_pixels = pitch_tiles * tile_width;
2319         unsigned int tiles;
2320
2321         WARN_ON(old_offset & (tile_size - 1));
2322         WARN_ON(new_offset & (tile_size - 1));
2323         WARN_ON(new_offset > old_offset);
2324
2325         tiles = (old_offset - new_offset) / tile_size;
2326
2327         *y += tiles / pitch_tiles * tile_height;
2328         *x += tiles % pitch_tiles * tile_width;
2329
2330         /* minimize x in case it got needlessly big */
2331         *y += *x / pitch_pixels * tile_height;
2332         *x %= pitch_pixels;
2333
2334         return new_offset;
2335 }
2336
2337 /*
2338  * Adjust the tile offset by moving the difference into
2339  * the x/y offsets.
2340  */
2341 static u32 intel_adjust_tile_offset(int *x, int *y,
2342                                     const struct intel_plane_state *state, int plane,
2343                                     u32 old_offset, u32 new_offset)
2344 {
2345         const struct drm_i915_private *dev_priv = to_i915(state->base.plane->dev);
2346         const struct drm_framebuffer *fb = state->base.fb;
2347         unsigned int cpp = drm_format_plane_cpp(fb->pixel_format, plane);
2348         unsigned int rotation = state->base.rotation;
2349         unsigned int pitch = intel_fb_pitch(fb, plane, rotation);
2350
2351         WARN_ON(new_offset > old_offset);
2352
2353         if (fb->modifier != DRM_FORMAT_MOD_NONE) {
2354                 unsigned int tile_size, tile_width, tile_height;
2355                 unsigned int pitch_tiles;
2356
2357                 tile_size = intel_tile_size(dev_priv);
2358                 intel_tile_dims(dev_priv, &tile_width, &tile_height,
2359                                 fb->modifier, cpp);
2360
2361                 if (drm_rotation_90_or_270(rotation)) {
2362                         pitch_tiles = pitch / tile_height;
2363                         swap(tile_width, tile_height);
2364                 } else {
2365                         pitch_tiles = pitch / (tile_width * cpp);
2366                 }
2367
2368                 _intel_adjust_tile_offset(x, y, tile_width, tile_height,
2369                                           tile_size, pitch_tiles,
2370                                           old_offset, new_offset);
2371         } else {
2372                 old_offset += *y * pitch + *x * cpp;
2373
2374                 *y = (old_offset - new_offset) / pitch;
2375                 *x = ((old_offset - new_offset) - *y * pitch) / cpp;
2376         }
2377
2378         return new_offset;
2379 }
2380
2381 /*
2382  * Computes the linear offset to the base tile and adjusts
2383  * x, y. bytes per pixel is assumed to be a power-of-two.
2384  *
2385  * In the 90/270 rotated case, x and y are assumed
2386  * to be already rotated to match the rotated GTT view, and
2387  * pitch is the tile_height aligned framebuffer height.
2388  *
2389  * This function is used when computing the derived information
2390  * under intel_framebuffer, so using any of that information
2391  * here is not allowed. Anything under drm_framebuffer can be
2392  * used. This is why the user has to pass in the pitch since it
2393  * is specified in the rotated orientation.
2394  */
2395 static u32 _intel_compute_tile_offset(const struct drm_i915_private *dev_priv,
2396                                       int *x, int *y,
2397                                       const struct drm_framebuffer *fb, int plane,
2398                                       unsigned int pitch,
2399                                       unsigned int rotation,
2400                                       u32 alignment)
2401 {
2402         uint64_t fb_modifier = fb->modifier;
2403         unsigned int cpp = drm_format_plane_cpp(fb->pixel_format, plane);
2404         u32 offset, offset_aligned;
2405
2406         if (alignment)
2407                 alignment--;
2408
2409         if (fb_modifier != DRM_FORMAT_MOD_NONE) {
2410                 unsigned int tile_size, tile_width, tile_height;
2411                 unsigned int tile_rows, tiles, pitch_tiles;
2412
2413                 tile_size = intel_tile_size(dev_priv);
2414                 intel_tile_dims(dev_priv, &tile_width, &tile_height,
2415                                 fb_modifier, cpp);
2416
2417                 if (drm_rotation_90_or_270(rotation)) {
2418                         pitch_tiles = pitch / tile_height;
2419                         swap(tile_width, tile_height);
2420                 } else {
2421                         pitch_tiles = pitch / (tile_width * cpp);
2422                 }
2423
2424                 tile_rows = *y / tile_height;
2425                 *y %= tile_height;
2426
2427                 tiles = *x / tile_width;
2428                 *x %= tile_width;
2429
2430                 offset = (tile_rows * pitch_tiles + tiles) * tile_size;
2431                 offset_aligned = offset & ~alignment;
2432
2433                 _intel_adjust_tile_offset(x, y, tile_width, tile_height,
2434                                           tile_size, pitch_tiles,
2435                                           offset, offset_aligned);
2436         } else {
2437                 offset = *y * pitch + *x * cpp;
2438                 offset_aligned = offset & ~alignment;
2439
2440                 *y = (offset & alignment) / pitch;
2441                 *x = ((offset & alignment) - *y * pitch) / cpp;
2442         }
2443
2444         return offset_aligned;
2445 }
2446
2447 u32 intel_compute_tile_offset(int *x, int *y,
2448                               const struct intel_plane_state *state,
2449                               int plane)
2450 {
2451         const struct drm_i915_private *dev_priv = to_i915(state->base.plane->dev);
2452         const struct drm_framebuffer *fb = state->base.fb;
2453         unsigned int rotation = state->base.rotation;
2454         int pitch = intel_fb_pitch(fb, plane, rotation);
2455         u32 alignment;
2456
2457         /* AUX_DIST needs only 4K alignment */
2458         if (fb->pixel_format == DRM_FORMAT_NV12 && plane == 1)
2459                 alignment = 4096;
2460         else
2461                 alignment = intel_surf_alignment(dev_priv, fb->modifier);
2462
2463         return _intel_compute_tile_offset(dev_priv, x, y, fb, plane, pitch,
2464                                           rotation, alignment);
2465 }
2466
2467 /* Convert the fb->offset[] linear offset into x/y offsets */
2468 static void intel_fb_offset_to_xy(int *x, int *y,
2469                                   const struct drm_framebuffer *fb, int plane)
2470 {
2471         unsigned int cpp = drm_format_plane_cpp(fb->pixel_format, plane);
2472         unsigned int pitch = fb->pitches[plane];
2473         u32 linear_offset = fb->offsets[plane];
2474
2475         *y = linear_offset / pitch;
2476         *x = linear_offset % pitch / cpp;
2477 }
2478
2479 static unsigned int intel_fb_modifier_to_tiling(uint64_t fb_modifier)
2480 {
2481         switch (fb_modifier) {
2482         case I915_FORMAT_MOD_X_TILED:
2483                 return I915_TILING_X;
2484         case I915_FORMAT_MOD_Y_TILED:
2485                 return I915_TILING_Y;
2486         default:
2487                 return I915_TILING_NONE;
2488         }
2489 }
2490
2491 static int
2492 intel_fill_fb_info(struct drm_i915_private *dev_priv,
2493                    struct drm_framebuffer *fb)
2494 {
2495         struct intel_framebuffer *intel_fb = to_intel_framebuffer(fb);
2496         struct intel_rotation_info *rot_info = &intel_fb->rot_info;
2497         u32 gtt_offset_rotated = 0;
2498         unsigned int max_size = 0;
2499         uint32_t format = fb->pixel_format;
2500         int i, num_planes = drm_format_num_planes(format);
2501         unsigned int tile_size = intel_tile_size(dev_priv);
2502
2503         for (i = 0; i < num_planes; i++) {
2504                 unsigned int width, height;
2505                 unsigned int cpp, size;
2506                 u32 offset;
2507                 int x, y;
2508
2509                 cpp = drm_format_plane_cpp(format, i);
2510                 width = drm_format_plane_width(fb->width, format, i);
2511                 height = drm_format_plane_height(fb->height, format, i);
2512
2513                 intel_fb_offset_to_xy(&x, &y, fb, i);
2514
2515                 /*
2516                  * The fence (if used) is aligned to the start of the object
2517                  * so having the framebuffer wrap around across the edge of the
2518                  * fenced region doesn't really work. We have no API to configure
2519                  * the fence start offset within the object (nor could we probably
2520                  * on gen2/3). So it's just easier if we just require that the
2521                  * fb layout agrees with the fence layout. We already check that the
2522                  * fb stride matches the fence stride elsewhere.
2523                  */
2524                 if (i915_gem_object_is_tiled(intel_fb->obj) &&
2525                     (x + width) * cpp > fb->pitches[i]) {
2526                         DRM_DEBUG("bad fb plane %d offset: 0x%x\n",
2527                                   i, fb->offsets[i]);
2528                         return -EINVAL;
2529                 }
2530
2531                 /*
2532                  * First pixel of the framebuffer from
2533                  * the start of the normal gtt mapping.
2534                  */
2535                 intel_fb->normal[i].x = x;
2536                 intel_fb->normal[i].y = y;
2537
2538                 offset = _intel_compute_tile_offset(dev_priv, &x, &y,
2539                                                     fb, 0, fb->pitches[i],
2540                                                     DRM_ROTATE_0, tile_size);
2541                 offset /= tile_size;
2542
2543                 if (fb->modifier != DRM_FORMAT_MOD_NONE) {
2544                         unsigned int tile_width, tile_height;
2545                         unsigned int pitch_tiles;
2546                         struct drm_rect r;
2547
2548                         intel_tile_dims(dev_priv, &tile_width, &tile_height,
2549                                         fb->modifier, cpp);
2550
2551                         rot_info->plane[i].offset = offset;
2552                         rot_info->plane[i].stride = DIV_ROUND_UP(fb->pitches[i], tile_width * cpp);
2553                         rot_info->plane[i].width = DIV_ROUND_UP(x + width, tile_width);
2554                         rot_info->plane[i].height = DIV_ROUND_UP(y + height, tile_height);
2555
2556                         intel_fb->rotated[i].pitch =
2557                                 rot_info->plane[i].height * tile_height;
2558
2559                         /* how many tiles does this plane need */
2560                         size = rot_info->plane[i].stride * rot_info->plane[i].height;
2561                         /*
2562                          * If the plane isn't horizontally tile aligned,
2563                          * we need one more tile.
2564                          */
2565                         if (x != 0)
2566                                 size++;
2567
2568                         /* rotate the x/y offsets to match the GTT view */
2569                         r.x1 = x;
2570                         r.y1 = y;
2571                         r.x2 = x + width;
2572                         r.y2 = y + height;
2573                         drm_rect_rotate(&r,
2574                                         rot_info->plane[i].width * tile_width,
2575                                         rot_info->plane[i].height * tile_height,
2576                                         DRM_ROTATE_270);
2577                         x = r.x1;
2578                         y = r.y1;
2579
2580                         /* rotate the tile dimensions to match the GTT view */
2581                         pitch_tiles = intel_fb->rotated[i].pitch / tile_height;
2582                         swap(tile_width, tile_height);
2583
2584                         /*
2585                          * We only keep the x/y offsets, so push all of the
2586                          * gtt offset into the x/y offsets.
2587                          */
2588                         _intel_adjust_tile_offset(&x, &y, tile_size,
2589                                                   tile_width, tile_height, pitch_tiles,
2590                                                   gtt_offset_rotated * tile_size, 0);
2591
2592                         gtt_offset_rotated += rot_info->plane[i].width * rot_info->plane[i].height;
2593
2594                         /*
2595                          * First pixel of the framebuffer from
2596                          * the start of the rotated gtt mapping.
2597                          */
2598                         intel_fb->rotated[i].x = x;
2599                         intel_fb->rotated[i].y = y;
2600                 } else {
2601                         size = DIV_ROUND_UP((y + height) * fb->pitches[i] +
2602                                             x * cpp, tile_size);
2603                 }
2604
2605                 /* how many tiles in total needed in the bo */
2606                 max_size = max(max_size, offset + size);
2607         }
2608
2609         if (max_size * tile_size > to_intel_framebuffer(fb)->obj->base.size) {
2610                 DRM_DEBUG("fb too big for bo (need %u bytes, have %zu bytes)\n",
2611                           max_size * tile_size, to_intel_framebuffer(fb)->obj->base.size);
2612                 return -EINVAL;
2613         }
2614
2615         return 0;
2616 }
2617
2618 static int i9xx_format_to_fourcc(int format)
2619 {
2620         switch (format) {
2621         case DISPPLANE_8BPP:
2622                 return DRM_FORMAT_C8;
2623         case DISPPLANE_BGRX555:
2624                 return DRM_FORMAT_XRGB1555;
2625         case DISPPLANE_BGRX565:
2626                 return DRM_FORMAT_RGB565;
2627         default:
2628         case DISPPLANE_BGRX888:
2629                 return DRM_FORMAT_XRGB8888;
2630         case DISPPLANE_RGBX888:
2631                 return DRM_FORMAT_XBGR8888;
2632         case DISPPLANE_BGRX101010:
2633                 return DRM_FORMAT_XRGB2101010;
2634         case DISPPLANE_RGBX101010:
2635                 return DRM_FORMAT_XBGR2101010;
2636         }
2637 }
2638
2639 static int skl_format_to_fourcc(int format, bool rgb_order, bool alpha)
2640 {
2641         switch (format) {
2642         case PLANE_CTL_FORMAT_RGB_565:
2643                 return DRM_FORMAT_RGB565;
2644         default:
2645         case PLANE_CTL_FORMAT_XRGB_8888:
2646                 if (rgb_order) {
2647                         if (alpha)
2648                                 return DRM_FORMAT_ABGR8888;
2649                         else
2650                                 return DRM_FORMAT_XBGR8888;
2651                 } else {
2652                         if (alpha)
2653                                 return DRM_FORMAT_ARGB8888;
2654                         else
2655                                 return DRM_FORMAT_XRGB8888;
2656                 }
2657         case PLANE_CTL_FORMAT_XRGB_2101010:
2658                 if (rgb_order)
2659                         return DRM_FORMAT_XBGR2101010;
2660                 else
2661                         return DRM_FORMAT_XRGB2101010;
2662         }
2663 }
2664
2665 static bool
2666 intel_alloc_initial_plane_obj(struct intel_crtc *crtc,
2667                               struct intel_initial_plane_config *plane_config)
2668 {
2669         struct drm_device *dev = crtc->base.dev;
2670         struct drm_i915_private *dev_priv = to_i915(dev);
2671         struct i915_ggtt *ggtt = &dev_priv->ggtt;
2672         struct drm_i915_gem_object *obj = NULL;
2673         struct drm_mode_fb_cmd2 mode_cmd = { 0 };
2674         struct drm_framebuffer *fb = &plane_config->fb->base;
2675         u32 base_aligned = round_down(plane_config->base, PAGE_SIZE);
2676         u32 size_aligned = round_up(plane_config->base + plane_config->size,
2677                                     PAGE_SIZE);
2678
2679         size_aligned -= base_aligned;
2680
2681         if (plane_config->size == 0)
2682                 return false;
2683
2684         /* If the FB is too big, just don't use it since fbdev is not very
2685          * important and we should probably use that space with FBC or other
2686          * features. */
2687         if (size_aligned * 2 > ggtt->stolen_usable_size)
2688                 return false;
2689
2690         mutex_lock(&dev->struct_mutex);
2691
2692         obj = i915_gem_object_create_stolen_for_preallocated(dev,
2693                                                              base_aligned,
2694                                                              base_aligned,
2695                                                              size_aligned);
2696         if (!obj) {
2697                 mutex_unlock(&dev->struct_mutex);
2698                 return false;
2699         }
2700
2701         if (plane_config->tiling == I915_TILING_X)
2702                 obj->tiling_and_stride = fb->pitches[0] | I915_TILING_X;
2703
2704         mode_cmd.pixel_format = fb->pixel_format;
2705         mode_cmd.width = fb->width;
2706         mode_cmd.height = fb->height;
2707         mode_cmd.pitches[0] = fb->pitches[0];
2708         mode_cmd.modifier[0] = fb->modifier;
2709         mode_cmd.flags = DRM_MODE_FB_MODIFIERS;
2710
2711         if (intel_framebuffer_init(dev, to_intel_framebuffer(fb),
2712                                    &mode_cmd, obj)) {
2713                 DRM_DEBUG_KMS("intel fb init failed\n");
2714                 goto out_unref_obj;
2715         }
2716
2717         mutex_unlock(&dev->struct_mutex);
2718
2719         DRM_DEBUG_KMS("initial plane fb obj %p\n", obj);
2720         return true;
2721
2722 out_unref_obj:
2723         i915_gem_object_put(obj);
2724         mutex_unlock(&dev->struct_mutex);
2725         return false;
2726 }
2727
2728 /* Update plane->state->fb to match plane->fb after driver-internal updates */
2729 static void
2730 update_state_fb(struct drm_plane *plane)
2731 {
2732         if (plane->fb == plane->state->fb)
2733                 return;
2734
2735         if (plane->state->fb)
2736                 drm_framebuffer_unreference(plane->state->fb);
2737         plane->state->fb = plane->fb;
2738         if (plane->state->fb)
2739                 drm_framebuffer_reference(plane->state->fb);
2740 }
2741
2742 static void
2743 intel_find_initial_plane_obj(struct intel_crtc *intel_crtc,
2744                              struct intel_initial_plane_config *plane_config)
2745 {
2746         struct drm_device *dev = intel_crtc->base.dev;
2747         struct drm_i915_private *dev_priv = to_i915(dev);
2748         struct drm_crtc *c;
2749         struct intel_crtc *i;
2750         struct drm_i915_gem_object *obj;
2751         struct drm_plane *primary = intel_crtc->base.primary;
2752         struct drm_plane_state *plane_state = primary->state;
2753         struct drm_crtc_state *crtc_state = intel_crtc->base.state;
2754         struct intel_plane *intel_plane = to_intel_plane(primary);
2755         struct intel_plane_state *intel_state =
2756                 to_intel_plane_state(plane_state);
2757         struct drm_framebuffer *fb;
2758
2759         if (!plane_config->fb)
2760                 return;
2761
2762         if (intel_alloc_initial_plane_obj(intel_crtc, plane_config)) {
2763                 fb = &plane_config->fb->base;
2764                 goto valid_fb;
2765         }
2766
2767         kfree(plane_config->fb);
2768
2769         /*
2770          * Failed to alloc the obj, check to see if we should share
2771          * an fb with another CRTC instead
2772          */
2773         for_each_crtc(dev, c) {
2774                 i = to_intel_crtc(c);
2775
2776                 if (c == &intel_crtc->base)
2777                         continue;
2778
2779                 if (!i->active)
2780                         continue;
2781
2782                 fb = c->primary->fb;
2783                 if (!fb)
2784                         continue;
2785
2786                 obj = intel_fb_obj(fb);
2787                 if (i915_gem_object_ggtt_offset(obj, NULL) == plane_config->base) {
2788                         drm_framebuffer_reference(fb);
2789                         goto valid_fb;
2790                 }
2791         }
2792
2793         /*
2794          * We've failed to reconstruct the BIOS FB.  Current display state
2795          * indicates that the primary plane is visible, but has a NULL FB,
2796          * which will lead to problems later if we don't fix it up.  The
2797          * simplest solution is to just disable the primary plane now and
2798          * pretend the BIOS never had it enabled.
2799          */
2800         to_intel_plane_state(plane_state)->base.visible = false;
2801         crtc_state->plane_mask &= ~(1 << drm_plane_index(primary));
2802         intel_pre_disable_primary_noatomic(&intel_crtc->base);
2803         intel_plane->disable_plane(primary, &intel_crtc->base);
2804
2805         return;
2806
2807 valid_fb:
2808         plane_state->src_x = 0;
2809         plane_state->src_y = 0;
2810         plane_state->src_w = fb->width << 16;
2811         plane_state->src_h = fb->height << 16;
2812
2813         plane_state->crtc_x = 0;
2814         plane_state->crtc_y = 0;
2815         plane_state->crtc_w = fb->width;
2816         plane_state->crtc_h = fb->height;
2817
2818         intel_state->base.src = drm_plane_state_src(plane_state);
2819         intel_state->base.dst = drm_plane_state_dest(plane_state);
2820
2821         obj = intel_fb_obj(fb);
2822         if (i915_gem_object_is_tiled(obj))
2823                 dev_priv->preserve_bios_swizzle = true;
2824
2825         drm_framebuffer_reference(fb);
2826         primary->fb = primary->state->fb = fb;
2827         primary->crtc = primary->state->crtc = &intel_crtc->base;
2828         intel_crtc->base.state->plane_mask |= (1 << drm_plane_index(primary));
2829         atomic_or(to_intel_plane(primary)->frontbuffer_bit,
2830                   &obj->frontbuffer_bits);
2831 }
2832
2833 static int skl_max_plane_width(const struct drm_framebuffer *fb, int plane,
2834                                unsigned int rotation)
2835 {
2836         int cpp = drm_format_plane_cpp(fb->pixel_format, plane);
2837
2838         switch (fb->modifier) {
2839         case DRM_FORMAT_MOD_NONE:
2840         case I915_FORMAT_MOD_X_TILED:
2841                 switch (cpp) {
2842                 case 8:
2843                         return 4096;
2844                 case 4:
2845                 case 2:
2846                 case 1:
2847                         return 8192;
2848                 default:
2849                         MISSING_CASE(cpp);
2850                         break;
2851                 }
2852                 break;
2853         case I915_FORMAT_MOD_Y_TILED:
2854         case I915_FORMAT_MOD_Yf_TILED:
2855                 switch (cpp) {
2856                 case 8:
2857                         return 2048;
2858                 case 4:
2859                         return 4096;
2860                 case 2:
2861                 case 1:
2862                         return 8192;
2863                 default:
2864                         MISSING_CASE(cpp);
2865                         break;
2866                 }
2867                 break;
2868         default:
2869                 MISSING_CASE(fb->modifier);
2870         }
2871
2872         return 2048;
2873 }
2874
2875 static int skl_check_main_surface(struct intel_plane_state *plane_state)
2876 {
2877         const struct drm_i915_private *dev_priv = to_i915(plane_state->base.plane->dev);
2878         const struct drm_framebuffer *fb = plane_state->base.fb;
2879         unsigned int rotation = plane_state->base.rotation;
2880         int x = plane_state->base.src.x1 >> 16;
2881         int y = plane_state->base.src.y1 >> 16;
2882         int w = drm_rect_width(&plane_state->base.src) >> 16;
2883         int h = drm_rect_height(&plane_state->base.src) >> 16;
2884         int max_width = skl_max_plane_width(fb, 0, rotation);
2885         int max_height = 4096;
2886         u32 alignment, offset, aux_offset = plane_state->aux.offset;
2887
2888         if (w > max_width || h > max_height) {
2889                 DRM_DEBUG_KMS("requested Y/RGB source size %dx%d too big (limit %dx%d)\n",
2890                               w, h, max_width, max_height);
2891                 return -EINVAL;
2892         }
2893
2894         intel_add_fb_offsets(&x, &y, plane_state, 0);
2895         offset = intel_compute_tile_offset(&x, &y, plane_state, 0);
2896
2897         alignment = intel_surf_alignment(dev_priv, fb->modifier);
2898
2899         /*
2900          * AUX surface offset is specified as the distance from the
2901          * main surface offset, and it must be non-negative. Make
2902          * sure that is what we will get.
2903          */
2904         if (offset > aux_offset)
2905                 offset = intel_adjust_tile_offset(&x, &y, plane_state, 0,
2906                                                   offset, aux_offset & ~(alignment - 1));
2907
2908         /*
2909          * When using an X-tiled surface, the plane blows up
2910          * if the x offset + width exceed the stride.
2911          *
2912          * TODO: linear and Y-tiled seem fine, Yf untested,
2913          */
2914         if (fb->modifier == I915_FORMAT_MOD_X_TILED) {
2915                 int cpp = drm_format_plane_cpp(fb->pixel_format, 0);
2916
2917                 while ((x + w) * cpp > fb->pitches[0]) {
2918                         if (offset == 0) {
2919                                 DRM_DEBUG_KMS("Unable to find suitable display surface offset\n");
2920                                 return -EINVAL;
2921                         }
2922
2923                         offset = intel_adjust_tile_offset(&x, &y, plane_state, 0,
2924                                                           offset, offset - alignment);
2925                 }
2926         }
2927
2928         plane_state->main.offset = offset;
2929         plane_state->main.x = x;
2930         plane_state->main.y = y;
2931
2932         return 0;
2933 }
2934
2935 static int skl_check_nv12_aux_surface(struct intel_plane_state *plane_state)
2936 {
2937         const struct drm_framebuffer *fb = plane_state->base.fb;
2938         unsigned int rotation = plane_state->base.rotation;
2939         int max_width = skl_max_plane_width(fb, 1, rotation);
2940         int max_height = 4096;
2941         int x = plane_state->base.src.x1 >> 17;
2942         int y = plane_state->base.src.y1 >> 17;
2943         int w = drm_rect_width(&plane_state->base.src) >> 17;
2944         int h = drm_rect_height(&plane_state->base.src) >> 17;
2945         u32 offset;
2946
2947         intel_add_fb_offsets(&x, &y, plane_state, 1);
2948         offset = intel_compute_tile_offset(&x, &y, plane_state, 1);
2949
2950         /* FIXME not quite sure how/if these apply to the chroma plane */
2951         if (w > max_width || h > max_height) {
2952                 DRM_DEBUG_KMS("CbCr source size %dx%d too big (limit %dx%d)\n",
2953                               w, h, max_width, max_height);
2954                 return -EINVAL;
2955         }
2956
2957         plane_state->aux.offset = offset;
2958         plane_state->aux.x = x;
2959         plane_state->aux.y = y;
2960
2961         return 0;
2962 }
2963
2964 int skl_check_plane_surface(struct intel_plane_state *plane_state)
2965 {
2966         const struct drm_framebuffer *fb = plane_state->base.fb;
2967         unsigned int rotation = plane_state->base.rotation;
2968         int ret;
2969
2970         /* Rotate src coordinates to match rotated GTT view */
2971         if (drm_rotation_90_or_270(rotation))
2972                 drm_rect_rotate(&plane_state->base.src,
2973                                 fb->width << 16, fb->height << 16,
2974                                 DRM_ROTATE_270);
2975
2976         /*
2977          * Handle the AUX surface first since
2978          * the main surface setup depends on it.
2979          */
2980         if (fb->pixel_format == DRM_FORMAT_NV12) {
2981                 ret = skl_check_nv12_aux_surface(plane_state);
2982                 if (ret)
2983                         return ret;
2984         } else {
2985                 plane_state->aux.offset = ~0xfff;
2986                 plane_state->aux.x = 0;
2987                 plane_state->aux.y = 0;
2988         }
2989
2990         ret = skl_check_main_surface(plane_state);
2991         if (ret)
2992                 return ret;
2993
2994         return 0;
2995 }
2996
2997 static void i9xx_update_primary_plane(struct drm_plane *primary,
2998                                       const struct intel_crtc_state *crtc_state,
2999                                       const struct intel_plane_state *plane_state)
3000 {
3001         struct drm_i915_private *dev_priv = to_i915(primary->dev);
3002         struct intel_crtc *intel_crtc = to_intel_crtc(crtc_state->base.crtc);
3003         struct drm_framebuffer *fb = plane_state->base.fb;
3004         int plane = intel_crtc->plane;
3005         u32 linear_offset;
3006         u32 dspcntr;
3007         i915_reg_t reg = DSPCNTR(plane);
3008         unsigned int rotation = plane_state->base.rotation;
3009         int x = plane_state->base.src.x1 >> 16;
3010         int y = plane_state->base.src.y1 >> 16;
3011
3012         dspcntr = DISPPLANE_GAMMA_ENABLE;
3013
3014         dspcntr |= DISPLAY_PLANE_ENABLE;
3015
3016         if (INTEL_GEN(dev_priv) < 4) {
3017                 if (intel_crtc->pipe == PIPE_B)
3018                         dspcntr |= DISPPLANE_SEL_PIPE_B;
3019
3020                 /* pipesrc and dspsize control the size that is scaled from,
3021                  * which should always be the user's requested size.
3022                  */
3023                 I915_WRITE(DSPSIZE(plane),
3024                            ((crtc_state->pipe_src_h - 1) << 16) |
3025                            (crtc_state->pipe_src_w - 1));
3026                 I915_WRITE(DSPPOS(plane), 0);
3027         } else if (IS_CHERRYVIEW(dev_priv) && plane == PLANE_B) {
3028                 I915_WRITE(PRIMSIZE(plane),
3029                            ((crtc_state->pipe_src_h - 1) << 16) |
3030                            (crtc_state->pipe_src_w - 1));
3031                 I915_WRITE(PRIMPOS(plane), 0);
3032                 I915_WRITE(PRIMCNSTALPHA(plane), 0);
3033         }
3034
3035         switch (fb->pixel_format) {
3036         case DRM_FORMAT_C8:
3037                 dspcntr |= DISPPLANE_8BPP;
3038                 break;
3039         case DRM_FORMAT_XRGB1555:
3040                 dspcntr |= DISPPLANE_BGRX555;
3041                 break;
3042         case DRM_FORMAT_RGB565:
3043                 dspcntr |= DISPPLANE_BGRX565;
3044                 break;
3045         case DRM_FORMAT_XRGB8888:
3046                 dspcntr |= DISPPLANE_BGRX888;
3047                 break;
3048         case DRM_FORMAT_XBGR8888:
3049                 dspcntr |= DISPPLANE_RGBX888;
3050                 break;
3051         case DRM_FORMAT_XRGB2101010:
3052                 dspcntr |= DISPPLANE_BGRX101010;
3053                 break;
3054         case DRM_FORMAT_XBGR2101010:
3055                 dspcntr |= DISPPLANE_RGBX101010;
3056                 break;
3057         default:
3058                 BUG();
3059         }
3060
3061         if (INTEL_GEN(dev_priv) >= 4 &&
3062             fb->modifier == I915_FORMAT_MOD_X_TILED)
3063                 dspcntr |= DISPPLANE_TILED;
3064
3065         if (rotation & DRM_ROTATE_180)
3066                 dspcntr |= DISPPLANE_ROTATE_180;
3067
3068         if (rotation & DRM_REFLECT_X)
3069                 dspcntr |= DISPPLANE_MIRROR;
3070
3071         if (IS_G4X(dev_priv))
3072                 dspcntr |= DISPPLANE_TRICKLE_FEED_DISABLE;
3073
3074         intel_add_fb_offsets(&x, &y, plane_state, 0);
3075
3076         if (INTEL_GEN(dev_priv) >= 4)
3077                 intel_crtc->dspaddr_offset =
3078                         intel_compute_tile_offset(&x, &y, plane_state, 0);
3079
3080         if (rotation & DRM_ROTATE_180) {
3081                 x += crtc_state->pipe_src_w - 1;
3082                 y += crtc_state->pipe_src_h - 1;
3083         } else if (rotation & DRM_REFLECT_X) {
3084                 x += crtc_state->pipe_src_w - 1;
3085         }
3086
3087         linear_offset = intel_fb_xy_to_linear(x, y, plane_state, 0);
3088
3089         if (INTEL_GEN(dev_priv) < 4)
3090                 intel_crtc->dspaddr_offset = linear_offset;
3091
3092         intel_crtc->adjusted_x = x;
3093         intel_crtc->adjusted_y = y;
3094
3095         I915_WRITE(reg, dspcntr);
3096
3097         I915_WRITE(DSPSTRIDE(plane), fb->pitches[0]);
3098         if (INTEL_GEN(dev_priv) >= 4) {
3099                 I915_WRITE(DSPSURF(plane),
3100                            intel_fb_gtt_offset(fb, rotation) +
3101                            intel_crtc->dspaddr_offset);
3102                 I915_WRITE(DSPTILEOFF(plane), (y << 16) | x);
3103                 I915_WRITE(DSPLINOFF(plane), linear_offset);
3104         } else {
3105                 I915_WRITE(DSPADDR(plane),
3106                            intel_fb_gtt_offset(fb, rotation) +
3107                            intel_crtc->dspaddr_offset);
3108         }
3109         POSTING_READ(reg);
3110 }
3111
3112 static void i9xx_disable_primary_plane(struct drm_plane *primary,
3113                                        struct drm_crtc *crtc)
3114 {
3115         struct drm_device *dev = crtc->dev;
3116         struct drm_i915_private *dev_priv = to_i915(dev);
3117         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3118         int plane = intel_crtc->plane;
3119
3120         I915_WRITE(DSPCNTR(plane), 0);
3121         if (INTEL_INFO(dev_priv)->gen >= 4)
3122                 I915_WRITE(DSPSURF(plane), 0);
3123         else
3124                 I915_WRITE(DSPADDR(plane), 0);
3125         POSTING_READ(DSPCNTR(plane));
3126 }
3127
3128 static void ironlake_update_primary_plane(struct drm_plane *primary,
3129                                           const struct intel_crtc_state *crtc_state,
3130                                           const struct intel_plane_state *plane_state)
3131 {
3132         struct drm_device *dev = primary->dev;
3133         struct drm_i915_private *dev_priv = to_i915(dev);
3134         struct intel_crtc *intel_crtc = to_intel_crtc(crtc_state->base.crtc);
3135         struct drm_framebuffer *fb = plane_state->base.fb;
3136         int plane = intel_crtc->plane;
3137         u32 linear_offset;
3138         u32 dspcntr;
3139         i915_reg_t reg = DSPCNTR(plane);
3140         unsigned int rotation = plane_state->base.rotation;
3141         int x = plane_state->base.src.x1 >> 16;
3142         int y = plane_state->base.src.y1 >> 16;
3143
3144         dspcntr = DISPPLANE_GAMMA_ENABLE;
3145         dspcntr |= DISPLAY_PLANE_ENABLE;
3146
3147         if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv))
3148                 dspcntr |= DISPPLANE_PIPE_CSC_ENABLE;
3149
3150         switch (fb->pixel_format) {
3151         case DRM_FORMAT_C8:
3152                 dspcntr |= DISPPLANE_8BPP;
3153                 break;
3154         case DRM_FORMAT_RGB565:
3155                 dspcntr |= DISPPLANE_BGRX565;
3156                 break;
3157         case DRM_FORMAT_XRGB8888:
3158                 dspcntr |= DISPPLANE_BGRX888;
3159                 break;
3160         case DRM_FORMAT_XBGR8888:
3161                 dspcntr |= DISPPLANE_RGBX888;
3162                 break;
3163         case DRM_FORMAT_XRGB2101010:
3164                 dspcntr |= DISPPLANE_BGRX101010;
3165                 break;
3166         case DRM_FORMAT_XBGR2101010:
3167                 dspcntr |= DISPPLANE_RGBX101010;
3168                 break;
3169         default:
3170                 BUG();
3171         }
3172
3173         if (fb->modifier == I915_FORMAT_MOD_X_TILED)
3174                 dspcntr |= DISPPLANE_TILED;
3175
3176         if (rotation & DRM_ROTATE_180)
3177                 dspcntr |= DISPPLANE_ROTATE_180;
3178
3179         if (!IS_HASWELL(dev_priv) && !IS_BROADWELL(dev_priv))
3180                 dspcntr |= DISPPLANE_TRICKLE_FEED_DISABLE;
3181
3182         intel_add_fb_offsets(&x, &y, plane_state, 0);
3183
3184         intel_crtc->dspaddr_offset =
3185                 intel_compute_tile_offset(&x, &y, plane_state, 0);
3186
3187         /* HSW+ does this automagically in hardware */
3188         if (!IS_HASWELL(dev_priv) && !IS_BROADWELL(dev_priv) &&
3189             rotation & DRM_ROTATE_180) {
3190                 x += crtc_state->pipe_src_w - 1;
3191                 y += crtc_state->pipe_src_h - 1;
3192         }
3193
3194         linear_offset = intel_fb_xy_to_linear(x, y, plane_state, 0);
3195
3196         intel_crtc->adjusted_x = x;
3197         intel_crtc->adjusted_y = y;
3198
3199         I915_WRITE(reg, dspcntr);
3200
3201         I915_WRITE(DSPSTRIDE(plane), fb->pitches[0]);
3202         I915_WRITE(DSPSURF(plane),
3203                    intel_fb_gtt_offset(fb, rotation) +
3204                    intel_crtc->dspaddr_offset);
3205         if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv)) {
3206                 I915_WRITE(DSPOFFSET(plane), (y << 16) | x);
3207         } else {
3208                 I915_WRITE(DSPTILEOFF(plane), (y << 16) | x);
3209                 I915_WRITE(DSPLINOFF(plane), linear_offset);
3210         }
3211         POSTING_READ(reg);
3212 }
3213
3214 u32 intel_fb_stride_alignment(const struct drm_i915_private *dev_priv,
3215                               uint64_t fb_modifier, uint32_t pixel_format)
3216 {
3217         if (fb_modifier == DRM_FORMAT_MOD_NONE) {
3218                 return 64;
3219         } else {
3220                 int cpp = drm_format_plane_cpp(pixel_format, 0);
3221
3222                 return intel_tile_width_bytes(dev_priv, fb_modifier, cpp);
3223         }
3224 }
3225
3226 u32 intel_fb_gtt_offset(struct drm_framebuffer *fb,
3227                         unsigned int rotation)
3228 {
3229         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
3230         struct i915_ggtt_view view;
3231         struct i915_vma *vma;
3232
3233         intel_fill_fb_ggtt_view(&view, fb, rotation);
3234
3235         vma = i915_gem_object_to_ggtt(obj, &view);
3236         if (WARN(!vma, "ggtt vma for display object not found! (view=%u)\n",
3237                  view.type))
3238                 return -1;
3239
3240         return i915_ggtt_offset(vma);
3241 }
3242
3243 static void skl_detach_scaler(struct intel_crtc *intel_crtc, int id)
3244 {
3245         struct drm_device *dev = intel_crtc->base.dev;
3246         struct drm_i915_private *dev_priv = to_i915(dev);
3247
3248         I915_WRITE(SKL_PS_CTRL(intel_crtc->pipe, id), 0);
3249         I915_WRITE(SKL_PS_WIN_POS(intel_crtc->pipe, id), 0);
3250         I915_WRITE(SKL_PS_WIN_SZ(intel_crtc->pipe, id), 0);
3251 }
3252
3253 /*
3254  * This function detaches (aka. unbinds) unused scalers in hardware
3255  */
3256 static void skl_detach_scalers(struct intel_crtc *intel_crtc)
3257 {
3258         struct intel_crtc_scaler_state *scaler_state;
3259         int i;
3260
3261         scaler_state = &intel_crtc->config->scaler_state;
3262
3263         /* loop through and disable scalers that aren't in use */
3264         for (i = 0; i < intel_crtc->num_scalers; i++) {
3265                 if (!scaler_state->scalers[i].in_use)
3266                         skl_detach_scaler(intel_crtc, i);
3267         }
3268 }
3269
3270 u32 skl_plane_stride(const struct drm_framebuffer *fb, int plane,
3271                      unsigned int rotation)
3272 {
3273         const struct drm_i915_private *dev_priv = to_i915(fb->dev);
3274         u32 stride = intel_fb_pitch(fb, plane, rotation);
3275
3276         /*
3277          * The stride is either expressed as a multiple of 64 bytes chunks for
3278          * linear buffers or in number of tiles for tiled buffers.
3279          */
3280         if (drm_rotation_90_or_270(rotation)) {
3281                 int cpp = drm_format_plane_cpp(fb->pixel_format, plane);
3282
3283                 stride /= intel_tile_height(dev_priv, fb->modifier, cpp);
3284         } else {
3285                 stride /= intel_fb_stride_alignment(dev_priv, fb->modifier,
3286                                                     fb->pixel_format);
3287         }
3288
3289         return stride;
3290 }
3291
3292 u32 skl_plane_ctl_format(uint32_t pixel_format)
3293 {
3294         switch (pixel_format) {
3295         case DRM_FORMAT_C8:
3296                 return PLANE_CTL_FORMAT_INDEXED;
3297         case DRM_FORMAT_RGB565:
3298                 return PLANE_CTL_FORMAT_RGB_565;
3299         case DRM_FORMAT_XBGR8888:
3300                 return PLANE_CTL_FORMAT_XRGB_8888 | PLANE_CTL_ORDER_RGBX;
3301         case DRM_FORMAT_XRGB8888:
3302                 return PLANE_CTL_FORMAT_XRGB_8888;
3303         /*
3304          * XXX: For ARBG/ABGR formats we default to expecting scanout buffers
3305          * to be already pre-multiplied. We need to add a knob (or a different
3306          * DRM_FORMAT) for user-space to configure that.
3307          */
3308         case DRM_FORMAT_ABGR8888:
3309                 return PLANE_CTL_FORMAT_XRGB_8888 | PLANE_CTL_ORDER_RGBX |
3310                         PLANE_CTL_ALPHA_SW_PREMULTIPLY;
3311         case DRM_FORMAT_ARGB8888:
3312                 return PLANE_CTL_FORMAT_XRGB_8888 |
3313                         PLANE_CTL_ALPHA_SW_PREMULTIPLY;
3314         case DRM_FORMAT_XRGB2101010:
3315                 return PLANE_CTL_FORMAT_XRGB_2101010;
3316         case DRM_FORMAT_XBGR2101010:
3317                 return PLANE_CTL_ORDER_RGBX | PLANE_CTL_FORMAT_XRGB_2101010;
3318         case DRM_FORMAT_YUYV:
3319                 return PLANE_CTL_FORMAT_YUV422 | PLANE_CTL_YUV422_YUYV;
3320         case DRM_FORMAT_YVYU:
3321                 return PLANE_CTL_FORMAT_YUV422 | PLANE_CTL_YUV422_YVYU;
3322         case DRM_FORMAT_UYVY:
3323                 return PLANE_CTL_FORMAT_YUV422 | PLANE_CTL_YUV422_UYVY;
3324         case DRM_FORMAT_VYUY:
3325                 return PLANE_CTL_FORMAT_YUV422 | PLANE_CTL_YUV422_VYUY;
3326         default:
3327                 MISSING_CASE(pixel_format);
3328         }
3329
3330         return 0;
3331 }
3332
3333 u32 skl_plane_ctl_tiling(uint64_t fb_modifier)
3334 {
3335         switch (fb_modifier) {
3336         case DRM_FORMAT_MOD_NONE:
3337                 break;
3338         case I915_FORMAT_MOD_X_TILED:
3339                 return PLANE_CTL_TILED_X;
3340         case I915_FORMAT_MOD_Y_TILED:
3341                 return PLANE_CTL_TILED_Y;
3342         case I915_FORMAT_MOD_Yf_TILED:
3343                 return PLANE_CTL_TILED_YF;
3344         default:
3345                 MISSING_CASE(fb_modifier);
3346         }
3347
3348         return 0;
3349 }
3350
3351 u32 skl_plane_ctl_rotation(unsigned int rotation)
3352 {
3353         switch (rotation) {
3354         case DRM_ROTATE_0:
3355                 break;
3356         /*
3357          * DRM_ROTATE_ is counter clockwise to stay compatible with Xrandr
3358          * while i915 HW rotation is clockwise, thats why this swapping.
3359          */
3360         case DRM_ROTATE_90:
3361                 return PLANE_CTL_ROTATE_270;
3362         case DRM_ROTATE_180:
3363                 return PLANE_CTL_ROTATE_180;
3364         case DRM_ROTATE_270:
3365                 return PLANE_CTL_ROTATE_90;
3366         default:
3367                 MISSING_CASE(rotation);
3368         }
3369
3370         return 0;
3371 }
3372
3373 static void skylake_update_primary_plane(struct drm_plane *plane,
3374                                          const struct intel_crtc_state *crtc_state,
3375                                          const struct intel_plane_state *plane_state)
3376 {
3377         struct drm_device *dev = plane->dev;
3378         struct drm_i915_private *dev_priv = to_i915(dev);
3379         struct intel_crtc *intel_crtc = to_intel_crtc(crtc_state->base.crtc);
3380         struct drm_framebuffer *fb = plane_state->base.fb;
3381         int pipe = intel_crtc->pipe;
3382         u32 plane_ctl;
3383         unsigned int rotation = plane_state->base.rotation;
3384         u32 stride = skl_plane_stride(fb, 0, rotation);
3385         u32 surf_addr = plane_state->main.offset;
3386         int scaler_id = plane_state->scaler_id;
3387         int src_x = plane_state->main.x;
3388         int src_y = plane_state->main.y;
3389         int src_w = drm_rect_width(&plane_state->base.src) >> 16;
3390         int src_h = drm_rect_height(&plane_state->base.src) >> 16;
3391         int dst_x = plane_state->base.dst.x1;
3392         int dst_y = plane_state->base.dst.y1;
3393         int dst_w = drm_rect_width(&plane_state->base.dst);
3394         int dst_h = drm_rect_height(&plane_state->base.dst);
3395
3396         plane_ctl = PLANE_CTL_ENABLE |
3397                     PLANE_CTL_PIPE_GAMMA_ENABLE |
3398                     PLANE_CTL_PIPE_CSC_ENABLE;
3399
3400         plane_ctl |= skl_plane_ctl_format(fb->pixel_format);
3401         plane_ctl |= skl_plane_ctl_tiling(fb->modifier);
3402         plane_ctl |= PLANE_CTL_PLANE_GAMMA_DISABLE;
3403         plane_ctl |= skl_plane_ctl_rotation(rotation);
3404
3405         /* Sizes are 0 based */
3406         src_w--;
3407         src_h--;
3408         dst_w--;
3409         dst_h--;
3410
3411         intel_crtc->dspaddr_offset = surf_addr;
3412
3413         intel_crtc->adjusted_x = src_x;
3414         intel_crtc->adjusted_y = src_y;
3415
3416         I915_WRITE(PLANE_CTL(pipe, 0), plane_ctl);
3417         I915_WRITE(PLANE_OFFSET(pipe, 0), (src_y << 16) | src_x);
3418         I915_WRITE(PLANE_STRIDE(pipe, 0), stride);
3419         I915_WRITE(PLANE_SIZE(pipe, 0), (src_h << 16) | src_w);
3420
3421         if (scaler_id >= 0) {
3422                 uint32_t ps_ctrl = 0;
3423
3424                 WARN_ON(!dst_w || !dst_h);
3425                 ps_ctrl = PS_SCALER_EN | PS_PLANE_SEL(0) |
3426                         crtc_state->scaler_state.scalers[scaler_id].mode;
3427                 I915_WRITE(SKL_PS_CTRL(pipe, scaler_id), ps_ctrl);
3428                 I915_WRITE(SKL_PS_PWR_GATE(pipe, scaler_id), 0);
3429                 I915_WRITE(SKL_PS_WIN_POS(pipe, scaler_id), (dst_x << 16) | dst_y);
3430                 I915_WRITE(SKL_PS_WIN_SZ(pipe, scaler_id), (dst_w << 16) | dst_h);
3431                 I915_WRITE(PLANE_POS(pipe, 0), 0);
3432         } else {
3433                 I915_WRITE(PLANE_POS(pipe, 0), (dst_y << 16) | dst_x);
3434         }
3435
3436         I915_WRITE(PLANE_SURF(pipe, 0),
3437                    intel_fb_gtt_offset(fb, rotation) + surf_addr);
3438
3439         POSTING_READ(PLANE_SURF(pipe, 0));
3440 }
3441
3442 static void skylake_disable_primary_plane(struct drm_plane *primary,
3443                                           struct drm_crtc *crtc)
3444 {
3445         struct drm_device *dev = crtc->dev;
3446         struct drm_i915_private *dev_priv = to_i915(dev);
3447         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3448         int pipe = intel_crtc->pipe;
3449
3450         I915_WRITE(PLANE_CTL(pipe, 0), 0);
3451         I915_WRITE(PLANE_SURF(pipe, 0), 0);
3452         POSTING_READ(PLANE_SURF(pipe, 0));
3453 }
3454
3455 /* Assume fb object is pinned & idle & fenced and just update base pointers */
3456 static int
3457 intel_pipe_set_base_atomic(struct drm_crtc *crtc, struct drm_framebuffer *fb,
3458                            int x, int y, enum mode_set_atomic state)
3459 {
3460         /* Support for kgdboc is disabled, this needs a major rework. */
3461         DRM_ERROR("legacy panic handler not supported any more.\n");
3462
3463         return -ENODEV;
3464 }
3465
3466 static void intel_complete_page_flips(struct drm_i915_private *dev_priv)
3467 {
3468         struct intel_crtc *crtc;
3469
3470         for_each_intel_crtc(&dev_priv->drm, crtc)
3471                 intel_finish_page_flip_cs(dev_priv, crtc->pipe);
3472 }
3473
3474 static void intel_update_primary_planes(struct drm_device *dev)
3475 {
3476         struct drm_crtc *crtc;
3477
3478         for_each_crtc(dev, crtc) {
3479                 struct intel_plane *plane = to_intel_plane(crtc->primary);
3480                 struct intel_plane_state *plane_state =
3481                         to_intel_plane_state(plane->base.state);
3482
3483                 if (plane_state->base.visible)
3484                         plane->update_plane(&plane->base,
3485                                             to_intel_crtc_state(crtc->state),
3486                                             plane_state);
3487         }
3488 }
3489
3490 static int
3491 __intel_display_resume(struct drm_device *dev,
3492                        struct drm_atomic_state *state)
3493 {
3494         struct drm_crtc_state *crtc_state;
3495         struct drm_crtc *crtc;
3496         int i, ret;
3497
3498         intel_modeset_setup_hw_state(dev);
3499         i915_redisable_vga(to_i915(dev));
3500
3501         if (!state)
3502                 return 0;
3503
3504         for_each_crtc_in_state(state, crtc, crtc_state, i) {
3505                 /*
3506                  * Force recalculation even if we restore
3507                  * current state. With fast modeset this may not result
3508                  * in a modeset when the state is compatible.
3509                  */
3510                 crtc_state->mode_changed = true;
3511         }
3512
3513         /* ignore any reset values/BIOS leftovers in the WM registers */
3514         to_intel_atomic_state(state)->skip_intermediate_wm = true;
3515
3516         ret = drm_atomic_commit(state);
3517
3518         WARN_ON(ret == -EDEADLK);
3519         return ret;
3520 }
3521
3522 static bool gpu_reset_clobbers_display(struct drm_i915_private *dev_priv)
3523 {
3524         return intel_has_gpu_reset(dev_priv) &&
3525                 INTEL_GEN(dev_priv) < 5 && !IS_G4X(dev_priv);
3526 }
3527
3528 void intel_prepare_reset(struct drm_i915_private *dev_priv)
3529 {
3530         struct drm_device *dev = &dev_priv->drm;
3531         struct drm_modeset_acquire_ctx *ctx = &dev_priv->reset_ctx;
3532         struct drm_atomic_state *state;
3533         int ret;
3534
3535         /*
3536          * Need mode_config.mutex so that we don't
3537          * trample ongoing ->detect() and whatnot.
3538          */
3539         mutex_lock(&dev->mode_config.mutex);
3540         drm_modeset_acquire_init(ctx, 0);
3541         while (1) {
3542                 ret = drm_modeset_lock_all_ctx(dev, ctx);
3543                 if (ret != -EDEADLK)
3544                         break;
3545
3546                 drm_modeset_backoff(ctx);
3547         }
3548
3549         /* reset doesn't touch the display, but flips might get nuked anyway, */
3550         if (!i915.force_reset_modeset_test &&
3551             !gpu_reset_clobbers_display(dev_priv))
3552                 return;
3553
3554         /*
3555          * Disabling the crtcs gracefully seems nicer. Also the
3556          * g33 docs say we should at least disable all the planes.
3557          */
3558         state = drm_atomic_helper_duplicate_state(dev, ctx);
3559         if (IS_ERR(state)) {
3560                 ret = PTR_ERR(state);
3561                 state = NULL;
3562                 DRM_ERROR("Duplicating state failed with %i\n", ret);
3563                 goto err;
3564         }
3565
3566         ret = drm_atomic_helper_disable_all(dev, ctx);
3567         if (ret) {
3568                 DRM_ERROR("Suspending crtc's failed with %i\n", ret);
3569                 goto err;
3570         }
3571
3572         dev_priv->modeset_restore_state = state;
3573         state->acquire_ctx = ctx;
3574         return;
3575
3576 err:
3577         drm_atomic_state_put(state);
3578 }
3579
3580 void intel_finish_reset(struct drm_i915_private *dev_priv)
3581 {
3582         struct drm_device *dev = &dev_priv->drm;
3583         struct drm_modeset_acquire_ctx *ctx = &dev_priv->reset_ctx;
3584         struct drm_atomic_state *state = dev_priv->modeset_restore_state;
3585         int ret;
3586
3587         /*
3588          * Flips in the rings will be nuked by the reset,
3589          * so complete all pending flips so that user space
3590          * will get its events and not get stuck.
3591          */
3592         intel_complete_page_flips(dev_priv);
3593
3594         dev_priv->modeset_restore_state = NULL;
3595
3596         /* reset doesn't touch the display */
3597         if (!gpu_reset_clobbers_display(dev_priv)) {
3598                 if (!state) {
3599                         /*
3600                          * Flips in the rings have been nuked by the reset,
3601                          * so update the base address of all primary
3602                          * planes to the the last fb to make sure we're
3603                          * showing the correct fb after a reset.
3604                          *
3605                          * FIXME: Atomic will make this obsolete since we won't schedule
3606                          * CS-based flips (which might get lost in gpu resets) any more.
3607                          */
3608                         intel_update_primary_planes(dev);
3609                 } else {
3610                         ret = __intel_display_resume(dev, state);
3611                         if (ret)
3612                                 DRM_ERROR("Restoring old state failed with %i\n", ret);
3613                 }
3614         } else {
3615                 /*
3616                  * The display has been reset as well,
3617                  * so need a full re-initialization.
3618                  */
3619                 intel_runtime_pm_disable_interrupts(dev_priv);
3620                 intel_runtime_pm_enable_interrupts(dev_priv);
3621
3622                 intel_pps_unlock_regs_wa(dev_priv);
3623                 intel_modeset_init_hw(dev);
3624
3625                 spin_lock_irq(&dev_priv->irq_lock);
3626                 if (dev_priv->display.hpd_irq_setup)
3627                         dev_priv->display.hpd_irq_setup(dev_priv);
3628                 spin_unlock_irq(&dev_priv->irq_lock);
3629
3630                 ret = __intel_display_resume(dev, state);
3631                 if (ret)
3632                         DRM_ERROR("Restoring old state failed with %i\n", ret);
3633
3634                 intel_hpd_init(dev_priv);
3635         }
3636
3637         if (state)
3638                 drm_atomic_state_put(state);
3639         drm_modeset_drop_locks(ctx);
3640         drm_modeset_acquire_fini(ctx);
3641         mutex_unlock(&dev->mode_config.mutex);
3642 }
3643
3644 static bool abort_flip_on_reset(struct intel_crtc *crtc)
3645 {
3646         struct i915_gpu_error *error = &to_i915(crtc->base.dev)->gpu_error;
3647
3648         if (i915_reset_in_progress(error))
3649                 return true;
3650
3651         if (crtc->reset_count != i915_reset_count(error))
3652                 return true;
3653
3654         return false;
3655 }
3656
3657 static bool intel_crtc_has_pending_flip(struct drm_crtc *crtc)
3658 {
3659         struct drm_device *dev = crtc->dev;
3660         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3661         bool pending;
3662
3663         if (abort_flip_on_reset(intel_crtc))
3664                 return false;
3665
3666         spin_lock_irq(&dev->event_lock);
3667         pending = to_intel_crtc(crtc)->flip_work != NULL;
3668         spin_unlock_irq(&dev->event_lock);
3669
3670         return pending;
3671 }
3672
3673 static void intel_update_pipe_config(struct intel_crtc *crtc,
3674                                      struct intel_crtc_state *old_crtc_state)
3675 {
3676         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
3677         struct intel_crtc_state *pipe_config =
3678                 to_intel_crtc_state(crtc->base.state);
3679
3680         /* drm_atomic_helper_update_legacy_modeset_state might not be called. */
3681         crtc->base.mode = crtc->base.state->mode;
3682
3683         DRM_DEBUG_KMS("Updating pipe size %ix%i -> %ix%i\n",
3684                       old_crtc_state->pipe_src_w, old_crtc_state->pipe_src_h,
3685                       pipe_config->pipe_src_w, pipe_config->pipe_src_h);
3686
3687         /*
3688          * Update pipe size and adjust fitter if needed: the reason for this is
3689          * that in compute_mode_changes we check the native mode (not the pfit
3690          * mode) to see if we can flip rather than do a full mode set. In the
3691          * fastboot case, we'll flip, but if we don't update the pipesrc and
3692          * pfit state, we'll end up with a big fb scanned out into the wrong
3693          * sized surface.
3694          */
3695
3696         I915_WRITE(PIPESRC(crtc->pipe),
3697                    ((pipe_config->pipe_src_w - 1) << 16) |
3698                    (pipe_config->pipe_src_h - 1));
3699
3700         /* on skylake this is done by detaching scalers */
3701         if (INTEL_GEN(dev_priv) >= 9) {
3702                 skl_detach_scalers(crtc);
3703
3704                 if (pipe_config->pch_pfit.enabled)
3705                         skylake_pfit_enable(crtc);
3706         } else if (HAS_PCH_SPLIT(dev_priv)) {
3707                 if (pipe_config->pch_pfit.enabled)
3708                         ironlake_pfit_enable(crtc);
3709                 else if (old_crtc_state->pch_pfit.enabled)
3710                         ironlake_pfit_disable(crtc, true);
3711         }
3712 }
3713
3714 static void intel_fdi_normal_train(struct drm_crtc *crtc)
3715 {
3716         struct drm_device *dev = crtc->dev;
3717         struct drm_i915_private *dev_priv = to_i915(dev);
3718         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3719         int pipe = intel_crtc->pipe;
3720         i915_reg_t reg;
3721         u32 temp;
3722
3723         /* enable normal train */
3724         reg = FDI_TX_CTL(pipe);
3725         temp = I915_READ(reg);
3726         if (IS_IVYBRIDGE(dev_priv)) {
3727                 temp &= ~FDI_LINK_TRAIN_NONE_IVB;
3728                 temp |= FDI_LINK_TRAIN_NONE_IVB | FDI_TX_ENHANCE_FRAME_ENABLE;
3729         } else {
3730                 temp &= ~FDI_LINK_TRAIN_NONE;
3731                 temp |= FDI_LINK_TRAIN_NONE | FDI_TX_ENHANCE_FRAME_ENABLE;
3732         }
3733         I915_WRITE(reg, temp);
3734
3735         reg = FDI_RX_CTL(pipe);
3736         temp = I915_READ(reg);
3737         if (HAS_PCH_CPT(dev_priv)) {
3738                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
3739                 temp |= FDI_LINK_TRAIN_NORMAL_CPT;
3740         } else {
3741                 temp &= ~FDI_LINK_TRAIN_NONE;
3742                 temp |= FDI_LINK_TRAIN_NONE;
3743         }
3744         I915_WRITE(reg, temp | FDI_RX_ENHANCE_FRAME_ENABLE);
3745
3746         /* wait one idle pattern time */
3747         POSTING_READ(reg);
3748         udelay(1000);
3749
3750         /* IVB wants error correction enabled */
3751         if (IS_IVYBRIDGE(dev_priv))
3752                 I915_WRITE(reg, I915_READ(reg) | FDI_FS_ERRC_ENABLE |
3753                            FDI_FE_ERRC_ENABLE);
3754 }
3755
3756 /* The FDI link training functions for ILK/Ibexpeak. */
3757 static void ironlake_fdi_link_train(struct drm_crtc *crtc)
3758 {
3759         struct drm_device *dev = crtc->dev;
3760         struct drm_i915_private *dev_priv = to_i915(dev);
3761         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3762         int pipe = intel_crtc->pipe;
3763         i915_reg_t reg;
3764         u32 temp, tries;
3765
3766         /* FDI needs bits from pipe first */
3767         assert_pipe_enabled(dev_priv, pipe);
3768
3769         /* Train 1: umask FDI RX Interrupt symbol_lock and bit_lock bit
3770            for train result */
3771         reg = FDI_RX_IMR(pipe);
3772         temp = I915_READ(reg);
3773         temp &= ~FDI_RX_SYMBOL_LOCK;
3774         temp &= ~FDI_RX_BIT_LOCK;
3775         I915_WRITE(reg, temp);
3776         I915_READ(reg);
3777         udelay(150);
3778
3779         /* enable CPU FDI TX and PCH FDI RX */
3780         reg = FDI_TX_CTL(pipe);
3781         temp = I915_READ(reg);
3782         temp &= ~FDI_DP_PORT_WIDTH_MASK;
3783         temp |= FDI_DP_PORT_WIDTH(intel_crtc->config->fdi_lanes);
3784         temp &= ~FDI_LINK_TRAIN_NONE;
3785         temp |= FDI_LINK_TRAIN_PATTERN_1;
3786         I915_WRITE(reg, temp | FDI_TX_ENABLE);
3787
3788         reg = FDI_RX_CTL(pipe);
3789         temp = I915_READ(reg);
3790         temp &= ~FDI_LINK_TRAIN_NONE;
3791         temp |= FDI_LINK_TRAIN_PATTERN_1;
3792         I915_WRITE(reg, temp | FDI_RX_ENABLE);
3793
3794         POSTING_READ(reg);
3795         udelay(150);
3796
3797         /* Ironlake workaround, enable clock pointer after FDI enable*/
3798         I915_WRITE(FDI_RX_CHICKEN(pipe), FDI_RX_PHASE_SYNC_POINTER_OVR);
3799         I915_WRITE(FDI_RX_CHICKEN(pipe), FDI_RX_PHASE_SYNC_POINTER_OVR |
3800                    FDI_RX_PHASE_SYNC_POINTER_EN);
3801
3802         reg = FDI_RX_IIR(pipe);
3803         for (tries = 0; tries < 5; tries++) {
3804                 temp = I915_READ(reg);
3805                 DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
3806
3807                 if ((temp & FDI_RX_BIT_LOCK)) {
3808                         DRM_DEBUG_KMS("FDI train 1 done.\n");
3809                         I915_WRITE(reg, temp | FDI_RX_BIT_LOCK);
3810                         break;
3811                 }
3812         }
3813         if (tries == 5)
3814                 DRM_ERROR("FDI train 1 fail!\n");
3815
3816         /* Train 2 */
3817         reg = FDI_TX_CTL(pipe);
3818         temp = I915_READ(reg);
3819         temp &= ~FDI_LINK_TRAIN_NONE;
3820         temp |= FDI_LINK_TRAIN_PATTERN_2;
3821         I915_WRITE(reg, temp);
3822
3823         reg = FDI_RX_CTL(pipe);
3824         temp = I915_READ(reg);
3825         temp &= ~FDI_LINK_TRAIN_NONE;
3826         temp |= FDI_LINK_TRAIN_PATTERN_2;
3827         I915_WRITE(reg, temp);
3828
3829         POSTING_READ(reg);
3830         udelay(150);
3831
3832         reg = FDI_RX_IIR(pipe);
3833         for (tries = 0; tries < 5; tries++) {
3834                 temp = I915_READ(reg);
3835                 DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
3836
3837                 if (temp & FDI_RX_SYMBOL_LOCK) {
3838                         I915_WRITE(reg, temp | FDI_RX_SYMBOL_LOCK);
3839                         DRM_DEBUG_KMS("FDI train 2 done.\n");
3840                         break;
3841                 }
3842         }
3843         if (tries == 5)
3844                 DRM_ERROR("FDI train 2 fail!\n");
3845
3846         DRM_DEBUG_KMS("FDI train done\n");
3847
3848 }
3849
3850 static const int snb_b_fdi_train_param[] = {
3851         FDI_LINK_TRAIN_400MV_0DB_SNB_B,
3852         FDI_LINK_TRAIN_400MV_6DB_SNB_B,
3853         FDI_LINK_TRAIN_600MV_3_5DB_SNB_B,
3854         FDI_LINK_TRAIN_800MV_0DB_SNB_B,
3855 };
3856
3857 /* The FDI link training functions for SNB/Cougarpoint. */
3858 static void gen6_fdi_link_train(struct drm_crtc *crtc)
3859 {
3860         struct drm_device *dev = crtc->dev;
3861         struct drm_i915_private *dev_priv = to_i915(dev);
3862         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3863         int pipe = intel_crtc->pipe;
3864         i915_reg_t reg;
3865         u32 temp, i, retry;
3866
3867         /* Train 1: umask FDI RX Interrupt symbol_lock and bit_lock bit
3868            for train result */
3869         reg = FDI_RX_IMR(pipe);
3870         temp = I915_READ(reg);
3871         temp &= ~FDI_RX_SYMBOL_LOCK;
3872         temp &= ~FDI_RX_BIT_LOCK;
3873         I915_WRITE(reg, temp);
3874
3875         POSTING_READ(reg);
3876         udelay(150);
3877
3878         /* enable CPU FDI TX and PCH FDI RX */
3879         reg = FDI_TX_CTL(pipe);
3880         temp = I915_READ(reg);
3881         temp &= ~FDI_DP_PORT_WIDTH_MASK;
3882         temp |= FDI_DP_PORT_WIDTH(intel_crtc->config->fdi_lanes);
3883         temp &= ~FDI_LINK_TRAIN_NONE;
3884         temp |= FDI_LINK_TRAIN_PATTERN_1;
3885         temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
3886         /* SNB-B */
3887         temp |= FDI_LINK_TRAIN_400MV_0DB_SNB_B;
3888         I915_WRITE(reg, temp | FDI_TX_ENABLE);
3889
3890         I915_WRITE(FDI_RX_MISC(pipe),
3891                    FDI_RX_TP1_TO_TP2_48 | FDI_RX_FDI_DELAY_90);
3892
3893         reg = FDI_RX_CTL(pipe);
3894         temp = I915_READ(reg);
3895         if (HAS_PCH_CPT(dev_priv)) {
3896                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
3897                 temp |= FDI_LINK_TRAIN_PATTERN_1_CPT;
3898         } else {
3899                 temp &= ~FDI_LINK_TRAIN_NONE;
3900                 temp |= FDI_LINK_TRAIN_PATTERN_1;
3901         }
3902         I915_WRITE(reg, temp | FDI_RX_ENABLE);
3903
3904         POSTING_READ(reg);
3905         udelay(150);
3906
3907         for (i = 0; i < 4; i++) {
3908                 reg = FDI_TX_CTL(pipe);
3909                 temp = I915_READ(reg);
3910                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
3911                 temp |= snb_b_fdi_train_param[i];
3912                 I915_WRITE(reg, temp);
3913
3914                 POSTING_READ(reg);
3915                 udelay(500);
3916
3917                 for (retry = 0; retry < 5; retry++) {
3918                         reg = FDI_RX_IIR(pipe);
3919                         temp = I915_READ(reg);
3920                         DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
3921                         if (temp & FDI_RX_BIT_LOCK) {
3922                                 I915_WRITE(reg, temp | FDI_RX_BIT_LOCK);
3923                                 DRM_DEBUG_KMS("FDI train 1 done.\n");
3924                                 break;
3925                         }
3926                         udelay(50);
3927                 }
3928                 if (retry < 5)
3929                         break;
3930         }
3931         if (i == 4)
3932                 DRM_ERROR("FDI train 1 fail!\n");
3933
3934         /* Train 2 */
3935         reg = FDI_TX_CTL(pipe);
3936         temp = I915_READ(reg);
3937         temp &= ~FDI_LINK_TRAIN_NONE;
3938         temp |= FDI_LINK_TRAIN_PATTERN_2;
3939         if (IS_GEN6(dev_priv)) {
3940                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
3941                 /* SNB-B */
3942                 temp |= FDI_LINK_TRAIN_400MV_0DB_SNB_B;
3943         }
3944         I915_WRITE(reg, temp);
3945
3946         reg = FDI_RX_CTL(pipe);
3947         temp = I915_READ(reg);
3948         if (HAS_PCH_CPT(dev_priv)) {
3949                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
3950                 temp |= FDI_LINK_TRAIN_PATTERN_2_CPT;
3951         } else {
3952                 temp &= ~FDI_LINK_TRAIN_NONE;
3953                 temp |= FDI_LINK_TRAIN_PATTERN_2;
3954         }
3955         I915_WRITE(reg, temp);
3956
3957         POSTING_READ(reg);
3958         udelay(150);
3959
3960         for (i = 0; i < 4; i++) {
3961                 reg = FDI_TX_CTL(pipe);
3962                 temp = I915_READ(reg);
3963                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
3964                 temp |= snb_b_fdi_train_param[i];
3965                 I915_WRITE(reg, temp);
3966
3967                 POSTING_READ(reg);
3968                 udelay(500);
3969
3970                 for (retry = 0; retry < 5; retry++) {
3971                         reg = FDI_RX_IIR(pipe);
3972                         temp = I915_READ(reg);
3973                         DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
3974                         if (temp & FDI_RX_SYMBOL_LOCK) {
3975                                 I915_WRITE(reg, temp | FDI_RX_SYMBOL_LOCK);
3976                                 DRM_DEBUG_KMS("FDI train 2 done.\n");
3977                                 break;
3978                         }
3979                         udelay(50);
3980                 }
3981                 if (retry < 5)
3982                         break;
3983         }
3984         if (i == 4)
3985                 DRM_ERROR("FDI train 2 fail!\n");
3986
3987         DRM_DEBUG_KMS("FDI train done.\n");
3988 }
3989
3990 /* Manual link training for Ivy Bridge A0 parts */
3991 static void ivb_manual_fdi_link_train(struct drm_crtc *crtc)
3992 {
3993         struct drm_device *dev = crtc->dev;
3994         struct drm_i915_private *dev_priv = to_i915(dev);
3995         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3996         int pipe = intel_crtc->pipe;
3997         i915_reg_t reg;
3998         u32 temp, i, j;
3999
4000         /* Train 1: umask FDI RX Interrupt symbol_lock and bit_lock bit
4001            for train result */
4002         reg = FDI_RX_IMR(pipe);
4003         temp = I915_READ(reg);
4004         temp &= ~FDI_RX_SYMBOL_LOCK;
4005         temp &= ~FDI_RX_BIT_LOCK;
4006         I915_WRITE(reg, temp);
4007
4008         POSTING_READ(reg);
4009         udelay(150);
4010
4011         DRM_DEBUG_KMS("FDI_RX_IIR before link train 0x%x\n",
4012                       I915_READ(FDI_RX_IIR(pipe)));
4013
4014         /* Try each vswing and preemphasis setting twice before moving on */
4015         for (j = 0; j < ARRAY_SIZE(snb_b_fdi_train_param) * 2; j++) {
4016                 /* disable first in case we need to retry */
4017                 reg = FDI_TX_CTL(pipe);
4018                 temp = I915_READ(reg);
4019                 temp &= ~(FDI_LINK_TRAIN_AUTO | FDI_LINK_TRAIN_NONE_IVB);
4020                 temp &= ~FDI_TX_ENABLE;
4021                 I915_WRITE(reg, temp);
4022
4023                 reg = FDI_RX_CTL(pipe);
4024                 temp = I915_READ(reg);
4025                 temp &= ~FDI_LINK_TRAIN_AUTO;
4026                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
4027                 temp &= ~FDI_RX_ENABLE;
4028                 I915_WRITE(reg, temp);
4029
4030                 /* enable CPU FDI TX and PCH FDI RX */
4031                 reg = FDI_TX_CTL(pipe);
4032                 temp = I915_READ(reg);
4033                 temp &= ~FDI_DP_PORT_WIDTH_MASK;
4034                 temp |= FDI_DP_PORT_WIDTH(intel_crtc->config->fdi_lanes);
4035                 temp |= FDI_LINK_TRAIN_PATTERN_1_IVB;
4036                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
4037                 temp |= snb_b_fdi_train_param[j/2];
4038                 temp |= FDI_COMPOSITE_SYNC;
4039                 I915_WRITE(reg, temp | FDI_TX_ENABLE);
4040
4041                 I915_WRITE(FDI_RX_MISC(pipe),
4042                            FDI_RX_TP1_TO_TP2_48 | FDI_RX_FDI_DELAY_90);
4043
4044                 reg = FDI_RX_CTL(pipe);
4045                 temp = I915_READ(reg);
4046                 temp |= FDI_LINK_TRAIN_PATTERN_1_CPT;
4047                 temp |= FDI_COMPOSITE_SYNC;
4048                 I915_WRITE(reg, temp | FDI_RX_ENABLE);
4049
4050                 POSTING_READ(reg);
4051                 udelay(1); /* should be 0.5us */
4052
4053                 for (i = 0; i < 4; i++) {
4054                         reg = FDI_RX_IIR(pipe);
4055                         temp = I915_READ(reg);
4056                         DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
4057
4058                         if (temp & FDI_RX_BIT_LOCK ||
4059                             (I915_READ(reg) & FDI_RX_BIT_LOCK)) {
4060                                 I915_WRITE(reg, temp | FDI_RX_BIT_LOCK);
4061                                 DRM_DEBUG_KMS("FDI train 1 done, level %i.\n",
4062                                               i);
4063                                 break;
4064                         }
4065                         udelay(1); /* should be 0.5us */
4066                 }
4067                 if (i == 4) {
4068                         DRM_DEBUG_KMS("FDI train 1 fail on vswing %d\n", j / 2);
4069                         continue;
4070                 }
4071
4072                 /* Train 2 */
4073                 reg = FDI_TX_CTL(pipe);
4074                 temp = I915_READ(reg);
4075                 temp &= ~FDI_LINK_TRAIN_NONE_IVB;
4076                 temp |= FDI_LINK_TRAIN_PATTERN_2_IVB;
4077                 I915_WRITE(reg, temp);
4078
4079                 reg = FDI_RX_CTL(pipe);
4080                 temp = I915_READ(reg);
4081                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
4082                 temp |= FDI_LINK_TRAIN_PATTERN_2_CPT;
4083                 I915_WRITE(reg, temp);
4084
4085                 POSTING_READ(reg);
4086                 udelay(2); /* should be 1.5us */
4087
4088                 for (i = 0; i < 4; i++) {
4089                         reg = FDI_RX_IIR(pipe);
4090                         temp = I915_READ(reg);
4091                         DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
4092
4093                         if (temp & FDI_RX_SYMBOL_LOCK ||
4094                             (I915_READ(reg) & FDI_RX_SYMBOL_LOCK)) {
4095                                 I915_WRITE(reg, temp | FDI_RX_SYMBOL_LOCK);
4096                                 DRM_DEBUG_KMS("FDI train 2 done, level %i.\n",
4097                                               i);
4098                                 goto train_done;
4099                         }
4100                         udelay(2); /* should be 1.5us */
4101                 }
4102                 if (i == 4)
4103                         DRM_DEBUG_KMS("FDI train 2 fail on vswing %d\n", j / 2);
4104         }
4105
4106 train_done:
4107         DRM_DEBUG_KMS("FDI train done.\n");
4108 }
4109
4110 static void ironlake_fdi_pll_enable(struct intel_crtc *intel_crtc)
4111 {
4112         struct drm_device *dev = intel_crtc->base.dev;
4113         struct drm_i915_private *dev_priv = to_i915(dev);
4114         int pipe = intel_crtc->pipe;
4115         i915_reg_t reg;
4116         u32 temp;
4117
4118         /* enable PCH FDI RX PLL, wait warmup plus DMI latency */
4119         reg = FDI_RX_CTL(pipe);
4120         temp = I915_READ(reg);
4121         temp &= ~(FDI_DP_PORT_WIDTH_MASK | (0x7 << 16));
4122         temp |= FDI_DP_PORT_WIDTH(intel_crtc->config->fdi_lanes);
4123         temp |= (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) << 11;
4124         I915_WRITE(reg, temp | FDI_RX_PLL_ENABLE);
4125
4126         POSTING_READ(reg);
4127         udelay(200);
4128
4129         /* Switch from Rawclk to PCDclk */
4130         temp = I915_READ(reg);
4131         I915_WRITE(reg, temp | FDI_PCDCLK);
4132
4133         POSTING_READ(reg);
4134         udelay(200);
4135
4136         /* Enable CPU FDI TX PLL, always on for Ironlake */
4137         reg = FDI_TX_CTL(pipe);
4138         temp = I915_READ(reg);
4139         if ((temp & FDI_TX_PLL_ENABLE) == 0) {
4140                 I915_WRITE(reg, temp | FDI_TX_PLL_ENABLE);
4141
4142                 POSTING_READ(reg);
4143                 udelay(100);
4144         }
4145 }
4146
4147 static void ironlake_fdi_pll_disable(struct intel_crtc *intel_crtc)
4148 {
4149         struct drm_device *dev = intel_crtc->base.dev;
4150         struct drm_i915_private *dev_priv = to_i915(dev);
4151         int pipe = intel_crtc->pipe;
4152         i915_reg_t reg;
4153         u32 temp;
4154
4155         /* Switch from PCDclk to Rawclk */
4156         reg = FDI_RX_CTL(pipe);
4157         temp = I915_READ(reg);
4158         I915_WRITE(reg, temp & ~FDI_PCDCLK);
4159
4160         /* Disable CPU FDI TX PLL */
4161         reg = FDI_TX_CTL(pipe);
4162         temp = I915_READ(reg);
4163         I915_WRITE(reg, temp & ~FDI_TX_PLL_ENABLE);
4164
4165         POSTING_READ(reg);
4166         udelay(100);
4167
4168         reg = FDI_RX_CTL(pipe);
4169         temp = I915_READ(reg);
4170         I915_WRITE(reg, temp & ~FDI_RX_PLL_ENABLE);
4171
4172         /* Wait for the clocks to turn off. */
4173         POSTING_READ(reg);
4174         udelay(100);
4175 }
4176
4177 static void ironlake_fdi_disable(struct drm_crtc *crtc)
4178 {
4179         struct drm_device *dev = crtc->dev;
4180         struct drm_i915_private *dev_priv = to_i915(dev);
4181         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4182         int pipe = intel_crtc->pipe;
4183         i915_reg_t reg;
4184         u32 temp;
4185
4186         /* disable CPU FDI tx and PCH FDI rx */
4187         reg = FDI_TX_CTL(pipe);
4188         temp = I915_READ(reg);
4189         I915_WRITE(reg, temp & ~FDI_TX_ENABLE);
4190         POSTING_READ(reg);
4191
4192         reg = FDI_RX_CTL(pipe);
4193         temp = I915_READ(reg);
4194         temp &= ~(0x7 << 16);
4195         temp |= (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) << 11;
4196         I915_WRITE(reg, temp & ~FDI_RX_ENABLE);
4197
4198         POSTING_READ(reg);
4199         udelay(100);
4200
4201         /* Ironlake workaround, disable clock pointer after downing FDI */
4202         if (HAS_PCH_IBX(dev_priv))
4203                 I915_WRITE(FDI_RX_CHICKEN(pipe), FDI_RX_PHASE_SYNC_POINTER_OVR);
4204
4205         /* still set train pattern 1 */
4206         reg = FDI_TX_CTL(pipe);
4207         temp = I915_READ(reg);
4208         temp &= ~FDI_LINK_TRAIN_NONE;
4209         temp |= FDI_LINK_TRAIN_PATTERN_1;
4210         I915_WRITE(reg, temp);
4211
4212         reg = FDI_RX_CTL(pipe);
4213         temp = I915_READ(reg);
4214         if (HAS_PCH_CPT(dev_priv)) {
4215                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
4216                 temp |= FDI_LINK_TRAIN_PATTERN_1_CPT;
4217         } else {
4218                 temp &= ~FDI_LINK_TRAIN_NONE;
4219                 temp |= FDI_LINK_TRAIN_PATTERN_1;
4220         }
4221         /* BPC in FDI rx is consistent with that in PIPECONF */
4222         temp &= ~(0x07 << 16);
4223         temp |= (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) << 11;
4224         I915_WRITE(reg, temp);
4225
4226         POSTING_READ(reg);
4227         udelay(100);
4228 }
4229
4230 bool intel_has_pending_fb_unpin(struct drm_device *dev)
4231 {
4232         struct drm_i915_private *dev_priv = to_i915(dev);
4233         struct intel_crtc *crtc;
4234
4235         /* Note that we don't need to be called with mode_config.lock here
4236          * as our list of CRTC objects is static for the lifetime of the
4237          * device and so cannot disappear as we iterate. Similarly, we can
4238          * happily treat the predicates as racy, atomic checks as userspace
4239          * cannot claim and pin a new fb without at least acquring the
4240          * struct_mutex and so serialising with us.
4241          */
4242         for_each_intel_crtc(dev, crtc) {
4243                 if (atomic_read(&crtc->unpin_work_count) == 0)
4244                         continue;
4245
4246                 if (crtc->flip_work)
4247                         intel_wait_for_vblank(dev_priv, crtc->pipe);
4248
4249                 return true;
4250         }
4251
4252         return false;
4253 }
4254
4255 static void page_flip_completed(struct intel_crtc *intel_crtc)
4256 {
4257         struct drm_i915_private *dev_priv = to_i915(intel_crtc->base.dev);
4258         struct intel_flip_work *work = intel_crtc->flip_work;
4259
4260         intel_crtc->flip_work = NULL;
4261
4262         if (work->event)
4263                 drm_crtc_send_vblank_event(&intel_crtc->base, work->event);
4264
4265         drm_crtc_vblank_put(&intel_crtc->base);
4266
4267         wake_up_all(&dev_priv->pending_flip_queue);
4268         queue_work(dev_priv->wq, &work->unpin_work);
4269
4270         trace_i915_flip_complete(intel_crtc->plane,
4271                                  work->pending_flip_obj);
4272 }
4273
4274 static int intel_crtc_wait_for_pending_flips(struct drm_crtc *crtc)
4275 {
4276         struct drm_device *dev = crtc->dev;
4277         struct drm_i915_private *dev_priv = to_i915(dev);
4278         long ret;
4279
4280         WARN_ON(waitqueue_active(&dev_priv->pending_flip_queue));
4281
4282         ret = wait_event_interruptible_timeout(
4283                                         dev_priv->pending_flip_queue,
4284                                         !intel_crtc_has_pending_flip(crtc),
4285                                         60*HZ);
4286
4287         if (ret < 0)
4288                 return ret;
4289
4290         if (ret == 0) {
4291                 struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4292                 struct intel_flip_work *work;
4293
4294                 spin_lock_irq(&dev->event_lock);
4295                 work = intel_crtc->flip_work;
4296                 if (work && !is_mmio_work(work)) {
4297                         WARN_ONCE(1, "Removing stuck page flip\n");
4298                         page_flip_completed(intel_crtc);
4299                 }
4300                 spin_unlock_irq(&dev->event_lock);
4301         }
4302
4303         return 0;
4304 }
4305
4306 void lpt_disable_iclkip(struct drm_i915_private *dev_priv)
4307 {
4308         u32 temp;
4309
4310         I915_WRITE(PIXCLK_GATE, PIXCLK_GATE_GATE);
4311
4312         mutex_lock(&dev_priv->sb_lock);
4313
4314         temp = intel_sbi_read(dev_priv, SBI_SSCCTL6, SBI_ICLK);
4315         temp |= SBI_SSCCTL_DISABLE;
4316         intel_sbi_write(dev_priv, SBI_SSCCTL6, temp, SBI_ICLK);
4317
4318         mutex_unlock(&dev_priv->sb_lock);
4319 }
4320
4321 /* Program iCLKIP clock to the desired frequency */
4322 static void lpt_program_iclkip(struct drm_crtc *crtc)
4323 {
4324         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
4325         int clock = to_intel_crtc(crtc)->config->base.adjusted_mode.crtc_clock;
4326         u32 divsel, phaseinc, auxdiv, phasedir = 0;
4327         u32 temp;
4328
4329         lpt_disable_iclkip(dev_priv);
4330
4331         /* The iCLK virtual clock root frequency is in MHz,
4332          * but the adjusted_mode->crtc_clock in in KHz. To get the
4333          * divisors, it is necessary to divide one by another, so we
4334          * convert the virtual clock precision to KHz here for higher
4335          * precision.
4336          */
4337         for (auxdiv = 0; auxdiv < 2; auxdiv++) {
4338                 u32 iclk_virtual_root_freq = 172800 * 1000;
4339                 u32 iclk_pi_range = 64;
4340                 u32 desired_divisor;
4341
4342                 desired_divisor = DIV_ROUND_CLOSEST(iclk_virtual_root_freq,
4343                                                     clock << auxdiv);
4344                 divsel = (desired_divisor / iclk_pi_range) - 2;
4345                 phaseinc = desired_divisor % iclk_pi_range;
4346
4347                 /*
4348                  * Near 20MHz is a corner case which is
4349                  * out of range for the 7-bit divisor
4350                  */
4351                 if (divsel <= 0x7f)
4352                         break;
4353         }
4354
4355         /* This should not happen with any sane values */
4356         WARN_ON(SBI_SSCDIVINTPHASE_DIVSEL(divsel) &
4357                 ~SBI_SSCDIVINTPHASE_DIVSEL_MASK);
4358         WARN_ON(SBI_SSCDIVINTPHASE_DIR(phasedir) &
4359                 ~SBI_SSCDIVINTPHASE_INCVAL_MASK);
4360
4361         DRM_DEBUG_KMS("iCLKIP clock: found settings for %dKHz refresh rate: auxdiv=%x, divsel=%x, phasedir=%x, phaseinc=%x\n",
4362                         clock,
4363                         auxdiv,
4364                         divsel,
4365                         phasedir,
4366                         phaseinc);
4367
4368         mutex_lock(&dev_priv->sb_lock);
4369
4370         /* Program SSCDIVINTPHASE6 */
4371         temp = intel_sbi_read(dev_priv, SBI_SSCDIVINTPHASE6, SBI_ICLK);
4372         temp &= ~SBI_SSCDIVINTPHASE_DIVSEL_MASK;
4373         temp |= SBI_SSCDIVINTPHASE_DIVSEL(divsel);
4374         temp &= ~SBI_SSCDIVINTPHASE_INCVAL_MASK;
4375         temp |= SBI_SSCDIVINTPHASE_INCVAL(phaseinc);
4376         temp |= SBI_SSCDIVINTPHASE_DIR(phasedir);
4377         temp |= SBI_SSCDIVINTPHASE_PROPAGATE;
4378         intel_sbi_write(dev_priv, SBI_SSCDIVINTPHASE6, temp, SBI_ICLK);
4379
4380         /* Program SSCAUXDIV */
4381         temp = intel_sbi_read(dev_priv, SBI_SSCAUXDIV6, SBI_ICLK);
4382         temp &= ~SBI_SSCAUXDIV_FINALDIV2SEL(1);
4383         temp |= SBI_SSCAUXDIV_FINALDIV2SEL(auxdiv);
4384         intel_sbi_write(dev_priv, SBI_SSCAUXDIV6, temp, SBI_ICLK);
4385
4386         /* Enable modulator and associated divider */
4387         temp = intel_sbi_read(dev_priv, SBI_SSCCTL6, SBI_ICLK);
4388         temp &= ~SBI_SSCCTL_DISABLE;
4389         intel_sbi_write(dev_priv, SBI_SSCCTL6, temp, SBI_ICLK);
4390
4391         mutex_unlock(&dev_priv->sb_lock);
4392
4393         /* Wait for initialization time */
4394         udelay(24);
4395
4396         I915_WRITE(PIXCLK_GATE, PIXCLK_GATE_UNGATE);
4397 }
4398
4399 int lpt_get_iclkip(struct drm_i915_private *dev_priv)
4400 {
4401         u32 divsel, phaseinc, auxdiv;
4402         u32 iclk_virtual_root_freq = 172800 * 1000;
4403         u32 iclk_pi_range = 64;
4404         u32 desired_divisor;
4405         u32 temp;
4406
4407         if ((I915_READ(PIXCLK_GATE) & PIXCLK_GATE_UNGATE) == 0)
4408                 return 0;
4409
4410         mutex_lock(&dev_priv->sb_lock);
4411
4412         temp = intel_sbi_read(dev_priv, SBI_SSCCTL6, SBI_ICLK);
4413         if (temp & SBI_SSCCTL_DISABLE) {
4414                 mutex_unlock(&dev_priv->sb_lock);
4415                 return 0;
4416         }
4417
4418         temp = intel_sbi_read(dev_priv, SBI_SSCDIVINTPHASE6, SBI_ICLK);
4419         divsel = (temp & SBI_SSCDIVINTPHASE_DIVSEL_MASK) >>
4420                 SBI_SSCDIVINTPHASE_DIVSEL_SHIFT;
4421         phaseinc = (temp & SBI_SSCDIVINTPHASE_INCVAL_MASK) >>
4422                 SBI_SSCDIVINTPHASE_INCVAL_SHIFT;
4423
4424         temp = intel_sbi_read(dev_priv, SBI_SSCAUXDIV6, SBI_ICLK);
4425         auxdiv = (temp & SBI_SSCAUXDIV_FINALDIV2SEL_MASK) >>
4426                 SBI_SSCAUXDIV_FINALDIV2SEL_SHIFT;
4427
4428         mutex_unlock(&dev_priv->sb_lock);
4429
4430         desired_divisor = (divsel + 2) * iclk_pi_range + phaseinc;
4431
4432         return DIV_ROUND_CLOSEST(iclk_virtual_root_freq,
4433                                  desired_divisor << auxdiv);
4434 }
4435
4436 static void ironlake_pch_transcoder_set_timings(struct intel_crtc *crtc,
4437                                                 enum pipe pch_transcoder)
4438 {
4439         struct drm_device *dev = crtc->base.dev;
4440         struct drm_i915_private *dev_priv = to_i915(dev);
4441         enum transcoder cpu_transcoder = crtc->config->cpu_transcoder;
4442
4443         I915_WRITE(PCH_TRANS_HTOTAL(pch_transcoder),
4444                    I915_READ(HTOTAL(cpu_transcoder)));
4445         I915_WRITE(PCH_TRANS_HBLANK(pch_transcoder),
4446                    I915_READ(HBLANK(cpu_transcoder)));
4447         I915_WRITE(PCH_TRANS_HSYNC(pch_transcoder),
4448                    I915_READ(HSYNC(cpu_transcoder)));
4449
4450         I915_WRITE(PCH_TRANS_VTOTAL(pch_transcoder),
4451                    I915_READ(VTOTAL(cpu_transcoder)));
4452         I915_WRITE(PCH_TRANS_VBLANK(pch_transcoder),
4453                    I915_READ(VBLANK(cpu_transcoder)));
4454         I915_WRITE(PCH_TRANS_VSYNC(pch_transcoder),
4455                    I915_READ(VSYNC(cpu_transcoder)));
4456         I915_WRITE(PCH_TRANS_VSYNCSHIFT(pch_transcoder),
4457                    I915_READ(VSYNCSHIFT(cpu_transcoder)));
4458 }
4459
4460 static void cpt_set_fdi_bc_bifurcation(struct drm_device *dev, bool enable)
4461 {
4462         struct drm_i915_private *dev_priv = to_i915(dev);
4463         uint32_t temp;
4464
4465         temp = I915_READ(SOUTH_CHICKEN1);
4466         if (!!(temp & FDI_BC_BIFURCATION_SELECT) == enable)
4467                 return;
4468
4469         WARN_ON(I915_READ(FDI_RX_CTL(PIPE_B)) & FDI_RX_ENABLE);
4470         WARN_ON(I915_READ(FDI_RX_CTL(PIPE_C)) & FDI_RX_ENABLE);
4471
4472         temp &= ~FDI_BC_BIFURCATION_SELECT;
4473         if (enable)
4474                 temp |= FDI_BC_BIFURCATION_SELECT;
4475
4476         DRM_DEBUG_KMS("%sabling fdi C rx\n", enable ? "en" : "dis");
4477         I915_WRITE(SOUTH_CHICKEN1, temp);
4478         POSTING_READ(SOUTH_CHICKEN1);
4479 }
4480
4481 static void ivybridge_update_fdi_bc_bifurcation(struct intel_crtc *intel_crtc)
4482 {
4483         struct drm_device *dev = intel_crtc->base.dev;
4484
4485         switch (intel_crtc->pipe) {
4486         case PIPE_A:
4487                 break;
4488         case PIPE_B:
4489                 if (intel_crtc->config->fdi_lanes > 2)
4490                         cpt_set_fdi_bc_bifurcation(dev, false);
4491                 else
4492                         cpt_set_fdi_bc_bifurcation(dev, true);
4493
4494                 break;
4495         case PIPE_C:
4496                 cpt_set_fdi_bc_bifurcation(dev, true);
4497
4498                 break;
4499         default:
4500                 BUG();
4501         }
4502 }
4503
4504 /* Return which DP Port should be selected for Transcoder DP control */
4505 static enum port
4506 intel_trans_dp_port_sel(struct drm_crtc *crtc)
4507 {
4508         struct drm_device *dev = crtc->dev;
4509         struct intel_encoder *encoder;
4510
4511         for_each_encoder_on_crtc(dev, crtc, encoder) {
4512                 if (encoder->type == INTEL_OUTPUT_DP ||
4513                     encoder->type == INTEL_OUTPUT_EDP)
4514                         return enc_to_dig_port(&encoder->base)->port;
4515         }
4516
4517         return -1;
4518 }
4519
4520 /*
4521  * Enable PCH resources required for PCH ports:
4522  *   - PCH PLLs
4523  *   - FDI training & RX/TX
4524  *   - update transcoder timings
4525  *   - DP transcoding bits
4526  *   - transcoder
4527  */
4528 static void ironlake_pch_enable(struct drm_crtc *crtc)
4529 {
4530         struct drm_device *dev = crtc->dev;
4531         struct drm_i915_private *dev_priv = to_i915(dev);
4532         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4533         int pipe = intel_crtc->pipe;
4534         u32 temp;
4535
4536         assert_pch_transcoder_disabled(dev_priv, pipe);
4537
4538         if (IS_IVYBRIDGE(dev_priv))
4539                 ivybridge_update_fdi_bc_bifurcation(intel_crtc);
4540
4541         /* Write the TU size bits before fdi link training, so that error
4542          * detection works. */
4543         I915_WRITE(FDI_RX_TUSIZE1(pipe),
4544                    I915_READ(PIPE_DATA_M1(pipe)) & TU_SIZE_MASK);
4545
4546         /* For PCH output, training FDI link */
4547         dev_priv->display.fdi_link_train(crtc);
4548
4549         /* We need to program the right clock selection before writing the pixel
4550          * mutliplier into the DPLL. */
4551         if (HAS_PCH_CPT(dev_priv)) {
4552                 u32 sel;
4553
4554                 temp = I915_READ(PCH_DPLL_SEL);
4555                 temp |= TRANS_DPLL_ENABLE(pipe);
4556                 sel = TRANS_DPLLB_SEL(pipe);
4557                 if (intel_crtc->config->shared_dpll ==
4558                     intel_get_shared_dpll_by_id(dev_priv, DPLL_ID_PCH_PLL_B))
4559                         temp |= sel;
4560                 else
4561                         temp &= ~sel;
4562                 I915_WRITE(PCH_DPLL_SEL, temp);
4563         }
4564
4565         /* XXX: pch pll's can be enabled any time before we enable the PCH
4566          * transcoder, and we actually should do this to not upset any PCH
4567          * transcoder that already use the clock when we share it.
4568          *
4569          * Note that enable_shared_dpll tries to do the right thing, but
4570          * get_shared_dpll unconditionally resets the pll - we need that to have
4571          * the right LVDS enable sequence. */
4572         intel_enable_shared_dpll(intel_crtc);
4573
4574         /* set transcoder timing, panel must allow it */
4575         assert_panel_unlocked(dev_priv, pipe);
4576         ironlake_pch_transcoder_set_timings(intel_crtc, pipe);
4577
4578         intel_fdi_normal_train(crtc);
4579
4580         /* For PCH DP, enable TRANS_DP_CTL */
4581         if (HAS_PCH_CPT(dev_priv) &&
4582             intel_crtc_has_dp_encoder(intel_crtc->config)) {
4583                 const struct drm_display_mode *adjusted_mode =
4584                         &intel_crtc->config->base.adjusted_mode;
4585                 u32 bpc = (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) >> 5;
4586                 i915_reg_t reg = TRANS_DP_CTL(pipe);
4587                 temp = I915_READ(reg);
4588                 temp &= ~(TRANS_DP_PORT_SEL_MASK |
4589                           TRANS_DP_SYNC_MASK |
4590                           TRANS_DP_BPC_MASK);
4591                 temp |= TRANS_DP_OUTPUT_ENABLE;
4592                 temp |= bpc << 9; /* same format but at 11:9 */
4593
4594                 if (adjusted_mode->flags & DRM_MODE_FLAG_PHSYNC)
4595                         temp |= TRANS_DP_HSYNC_ACTIVE_HIGH;
4596                 if (adjusted_mode->flags & DRM_MODE_FLAG_PVSYNC)
4597                         temp |= TRANS_DP_VSYNC_ACTIVE_HIGH;
4598
4599                 switch (intel_trans_dp_port_sel(crtc)) {
4600                 case PORT_B:
4601                         temp |= TRANS_DP_PORT_SEL_B;
4602                         break;
4603                 case PORT_C:
4604                         temp |= TRANS_DP_PORT_SEL_C;
4605                         break;
4606                 case PORT_D:
4607                         temp |= TRANS_DP_PORT_SEL_D;
4608                         break;
4609                 default:
4610                         BUG();
4611                 }
4612
4613                 I915_WRITE(reg, temp);
4614         }
4615
4616         ironlake_enable_pch_transcoder(dev_priv, pipe);
4617 }
4618
4619 static void lpt_pch_enable(struct drm_crtc *crtc)
4620 {
4621         struct drm_device *dev = crtc->dev;
4622         struct drm_i915_private *dev_priv = to_i915(dev);
4623         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4624         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
4625
4626         assert_pch_transcoder_disabled(dev_priv, TRANSCODER_A);
4627
4628         lpt_program_iclkip(crtc);
4629
4630         /* Set transcoder timing. */
4631         ironlake_pch_transcoder_set_timings(intel_crtc, PIPE_A);
4632
4633         lpt_enable_pch_transcoder(dev_priv, cpu_transcoder);
4634 }
4635
4636 static void cpt_verify_modeset(struct drm_device *dev, int pipe)
4637 {
4638         struct drm_i915_private *dev_priv = to_i915(dev);
4639         i915_reg_t dslreg = PIPEDSL(pipe);
4640         u32 temp;
4641
4642         temp = I915_READ(dslreg);
4643         udelay(500);
4644         if (wait_for(I915_READ(dslreg) != temp, 5)) {
4645                 if (wait_for(I915_READ(dslreg) != temp, 5))
4646                         DRM_ERROR("mode set failed: pipe %c stuck\n", pipe_name(pipe));
4647         }
4648 }
4649
4650 static int
4651 skl_update_scaler(struct intel_crtc_state *crtc_state, bool force_detach,
4652                   unsigned scaler_user, int *scaler_id, unsigned int rotation,
4653                   int src_w, int src_h, int dst_w, int dst_h)
4654 {
4655         struct intel_crtc_scaler_state *scaler_state =
4656                 &crtc_state->scaler_state;
4657         struct intel_crtc *intel_crtc =
4658                 to_intel_crtc(crtc_state->base.crtc);
4659         int need_scaling;
4660
4661         need_scaling = drm_rotation_90_or_270(rotation) ?
4662                 (src_h != dst_w || src_w != dst_h):
4663                 (src_w != dst_w || src_h != dst_h);
4664
4665         /*
4666          * if plane is being disabled or scaler is no more required or force detach
4667          *  - free scaler binded to this plane/crtc
4668          *  - in order to do this, update crtc->scaler_usage
4669          *
4670          * Here scaler state in crtc_state is set free so that
4671          * scaler can be assigned to other user. Actual register
4672          * update to free the scaler is done in plane/panel-fit programming.
4673          * For this purpose crtc/plane_state->scaler_id isn't reset here.
4674          */
4675         if (force_detach || !need_scaling) {
4676                 if (*scaler_id >= 0) {
4677                         scaler_state->scaler_users &= ~(1 << scaler_user);
4678                         scaler_state->scalers[*scaler_id].in_use = 0;
4679
4680                         DRM_DEBUG_KMS("scaler_user index %u.%u: "
4681                                 "Staged freeing scaler id %d scaler_users = 0x%x\n",
4682                                 intel_crtc->pipe, scaler_user, *scaler_id,
4683                                 scaler_state->scaler_users);
4684                         *scaler_id = -1;
4685                 }
4686                 return 0;
4687         }
4688
4689         /* range checks */
4690         if (src_w < SKL_MIN_SRC_W || src_h < SKL_MIN_SRC_H ||
4691                 dst_w < SKL_MIN_DST_W || dst_h < SKL_MIN_DST_H ||
4692
4693                 src_w > SKL_MAX_SRC_W || src_h > SKL_MAX_SRC_H ||
4694                 dst_w > SKL_MAX_DST_W || dst_h > SKL_MAX_DST_H) {
4695                 DRM_DEBUG_KMS("scaler_user index %u.%u: src %ux%u dst %ux%u "
4696                         "size is out of scaler range\n",
4697                         intel_crtc->pipe, scaler_user, src_w, src_h, dst_w, dst_h);
4698                 return -EINVAL;
4699         }
4700
4701         /* mark this plane as a scaler user in crtc_state */
4702         scaler_state->scaler_users |= (1 << scaler_user);
4703         DRM_DEBUG_KMS("scaler_user index %u.%u: "
4704                 "staged scaling request for %ux%u->%ux%u scaler_users = 0x%x\n",
4705                 intel_crtc->pipe, scaler_user, src_w, src_h, dst_w, dst_h,
4706                 scaler_state->scaler_users);
4707
4708         return 0;
4709 }
4710
4711 /**
4712  * skl_update_scaler_crtc - Stages update to scaler state for a given crtc.
4713  *
4714  * @state: crtc's scaler state
4715  *
4716  * Return
4717  *     0 - scaler_usage updated successfully
4718  *    error - requested scaling cannot be supported or other error condition
4719  */
4720 int skl_update_scaler_crtc(struct intel_crtc_state *state)
4721 {
4722         const struct drm_display_mode *adjusted_mode = &state->base.adjusted_mode;
4723
4724         return skl_update_scaler(state, !state->base.active, SKL_CRTC_INDEX,
4725                 &state->scaler_state.scaler_id, DRM_ROTATE_0,
4726                 state->pipe_src_w, state->pipe_src_h,
4727                 adjusted_mode->crtc_hdisplay, adjusted_mode->crtc_vdisplay);
4728 }
4729
4730 /**
4731  * skl_update_scaler_plane - Stages update to scaler state for a given plane.
4732  *
4733  * @state: crtc's scaler state
4734  * @plane_state: atomic plane state to update
4735  *
4736  * Return
4737  *     0 - scaler_usage updated successfully
4738  *    error - requested scaling cannot be supported or other error condition
4739  */
4740 static int skl_update_scaler_plane(struct intel_crtc_state *crtc_state,
4741                                    struct intel_plane_state *plane_state)
4742 {
4743
4744         struct intel_plane *intel_plane =
4745                 to_intel_plane(plane_state->base.plane);
4746         struct drm_framebuffer *fb = plane_state->base.fb;
4747         int ret;
4748
4749         bool force_detach = !fb || !plane_state->base.visible;
4750
4751         ret = skl_update_scaler(crtc_state, force_detach,
4752                                 drm_plane_index(&intel_plane->base),
4753                                 &plane_state->scaler_id,
4754                                 plane_state->base.rotation,
4755                                 drm_rect_width(&plane_state->base.src) >> 16,
4756                                 drm_rect_height(&plane_state->base.src) >> 16,
4757                                 drm_rect_width(&plane_state->base.dst),
4758                                 drm_rect_height(&plane_state->base.dst));
4759
4760         if (ret || plane_state->scaler_id < 0)
4761                 return ret;
4762
4763         /* check colorkey */
4764         if (plane_state->ckey.flags != I915_SET_COLORKEY_NONE) {
4765                 DRM_DEBUG_KMS("[PLANE:%d:%s] scaling with color key not allowed",
4766                               intel_plane->base.base.id,
4767                               intel_plane->base.name);
4768                 return -EINVAL;
4769         }
4770
4771         /* Check src format */
4772         switch (fb->pixel_format) {
4773         case DRM_FORMAT_RGB565:
4774         case DRM_FORMAT_XBGR8888:
4775         case DRM_FORMAT_XRGB8888:
4776         case DRM_FORMAT_ABGR8888:
4777         case DRM_FORMAT_ARGB8888:
4778         case DRM_FORMAT_XRGB2101010:
4779         case DRM_FORMAT_XBGR2101010:
4780         case DRM_FORMAT_YUYV:
4781         case DRM_FORMAT_YVYU:
4782         case DRM_FORMAT_UYVY:
4783         case DRM_FORMAT_VYUY:
4784                 break;
4785         default:
4786                 DRM_DEBUG_KMS("[PLANE:%d:%s] FB:%d unsupported scaling format 0x%x\n",
4787                               intel_plane->base.base.id, intel_plane->base.name,
4788                               fb->base.id, fb->pixel_format);
4789                 return -EINVAL;
4790         }
4791
4792         return 0;
4793 }
4794
4795 static void skylake_scaler_disable(struct intel_crtc *crtc)
4796 {
4797         int i;
4798
4799         for (i = 0; i < crtc->num_scalers; i++)
4800                 skl_detach_scaler(crtc, i);
4801 }
4802
4803 static void skylake_pfit_enable(struct intel_crtc *crtc)
4804 {
4805         struct drm_device *dev = crtc->base.dev;
4806         struct drm_i915_private *dev_priv = to_i915(dev);
4807         int pipe = crtc->pipe;
4808         struct intel_crtc_scaler_state *scaler_state =
4809                 &crtc->config->scaler_state;
4810
4811         DRM_DEBUG_KMS("for crtc_state = %p\n", crtc->config);
4812
4813         if (crtc->config->pch_pfit.enabled) {
4814                 int id;
4815
4816                 if (WARN_ON(crtc->config->scaler_state.scaler_id < 0)) {
4817                         DRM_ERROR("Requesting pfit without getting a scaler first\n");
4818                         return;
4819                 }
4820
4821                 id = scaler_state->scaler_id;
4822                 I915_WRITE(SKL_PS_CTRL(pipe, id), PS_SCALER_EN |
4823                         PS_FILTER_MEDIUM | scaler_state->scalers[id].mode);
4824                 I915_WRITE(SKL_PS_WIN_POS(pipe, id), crtc->config->pch_pfit.pos);
4825                 I915_WRITE(SKL_PS_WIN_SZ(pipe, id), crtc->config->pch_pfit.size);
4826
4827                 DRM_DEBUG_KMS("for crtc_state = %p scaler_id = %d\n", crtc->config, id);
4828         }
4829 }
4830
4831 static void ironlake_pfit_enable(struct intel_crtc *crtc)
4832 {
4833         struct drm_device *dev = crtc->base.dev;
4834         struct drm_i915_private *dev_priv = to_i915(dev);
4835         int pipe = crtc->pipe;
4836
4837         if (crtc->config->pch_pfit.enabled) {
4838                 /* Force use of hard-coded filter coefficients
4839                  * as some pre-programmed values are broken,
4840                  * e.g. x201.
4841                  */
4842                 if (IS_IVYBRIDGE(dev_priv) || IS_HASWELL(dev_priv))
4843                         I915_WRITE(PF_CTL(pipe), PF_ENABLE | PF_FILTER_MED_3x3 |
4844                                                  PF_PIPE_SEL_IVB(pipe));
4845                 else
4846                         I915_WRITE(PF_CTL(pipe), PF_ENABLE | PF_FILTER_MED_3x3);
4847                 I915_WRITE(PF_WIN_POS(pipe), crtc->config->pch_pfit.pos);
4848                 I915_WRITE(PF_WIN_SZ(pipe), crtc->config->pch_pfit.size);
4849         }
4850 }
4851
4852 void hsw_enable_ips(struct intel_crtc *crtc)
4853 {
4854         struct drm_device *dev = crtc->base.dev;
4855         struct drm_i915_private *dev_priv = to_i915(dev);
4856
4857         if (!crtc->config->ips_enabled)
4858                 return;
4859
4860         /*
4861          * We can only enable IPS after we enable a plane and wait for a vblank
4862          * This function is called from post_plane_update, which is run after
4863          * a vblank wait.
4864          */
4865
4866         assert_plane_enabled(dev_priv, crtc->plane);
4867         if (IS_BROADWELL(dev_priv)) {
4868                 mutex_lock(&dev_priv->rps.hw_lock);
4869                 WARN_ON(sandybridge_pcode_write(dev_priv, DISPLAY_IPS_CONTROL, 0xc0000000));
4870                 mutex_unlock(&dev_priv->rps.hw_lock);
4871                 /* Quoting Art Runyan: "its not safe to expect any particular
4872                  * value in IPS_CTL bit 31 after enabling IPS through the
4873                  * mailbox." Moreover, the mailbox may return a bogus state,
4874                  * so we need to just enable it and continue on.
4875                  */
4876         } else {
4877                 I915_WRITE(IPS_CTL, IPS_ENABLE);
4878                 /* The bit only becomes 1 in the next vblank, so this wait here
4879                  * is essentially intel_wait_for_vblank. If we don't have this
4880                  * and don't wait for vblanks until the end of crtc_enable, then
4881                  * the HW state readout code will complain that the expected
4882                  * IPS_CTL value is not the one we read. */
4883                 if (intel_wait_for_register(dev_priv,
4884                                             IPS_CTL, IPS_ENABLE, IPS_ENABLE,
4885                                             50))
4886                         DRM_ERROR("Timed out waiting for IPS enable\n");
4887         }
4888 }
4889
4890 void hsw_disable_ips(struct intel_crtc *crtc)
4891 {
4892         struct drm_device *dev = crtc->base.dev;
4893         struct drm_i915_private *dev_priv = to_i915(dev);
4894
4895         if (!crtc->config->ips_enabled)
4896                 return;
4897
4898         assert_plane_enabled(dev_priv, crtc->plane);
4899         if (IS_BROADWELL(dev_priv)) {
4900                 mutex_lock(&dev_priv->rps.hw_lock);
4901                 WARN_ON(sandybridge_pcode_write(dev_priv, DISPLAY_IPS_CONTROL, 0));
4902                 mutex_unlock(&dev_priv->rps.hw_lock);
4903                 /* wait for pcode to finish disabling IPS, which may take up to 42ms */
4904                 if (intel_wait_for_register(dev_priv,
4905                                             IPS_CTL, IPS_ENABLE, 0,
4906                                             42))
4907                         DRM_ERROR("Timed out waiting for IPS disable\n");
4908         } else {
4909                 I915_WRITE(IPS_CTL, 0);
4910                 POSTING_READ(IPS_CTL);
4911         }
4912
4913         /* We need to wait for a vblank before we can disable the plane. */
4914         intel_wait_for_vblank(dev_priv, crtc->pipe);
4915 }
4916
4917 static void intel_crtc_dpms_overlay_disable(struct intel_crtc *intel_crtc)
4918 {
4919         if (intel_crtc->overlay) {
4920                 struct drm_device *dev = intel_crtc->base.dev;
4921                 struct drm_i915_private *dev_priv = to_i915(dev);
4922
4923                 mutex_lock(&dev->struct_mutex);
4924                 dev_priv->mm.interruptible = false;
4925                 (void) intel_overlay_switch_off(intel_crtc->overlay);
4926                 dev_priv->mm.interruptible = true;
4927                 mutex_unlock(&dev->struct_mutex);
4928         }
4929
4930         /* Let userspace switch the overlay on again. In most cases userspace
4931          * has to recompute where to put it anyway.
4932          */
4933 }
4934
4935 /**
4936  * intel_post_enable_primary - Perform operations after enabling primary plane
4937  * @crtc: the CRTC whose primary plane was just enabled
4938  *
4939  * Performs potentially sleeping operations that must be done after the primary
4940  * plane is enabled, such as updating FBC and IPS.  Note that this may be
4941  * called due to an explicit primary plane update, or due to an implicit
4942  * re-enable that is caused when a sprite plane is updated to no longer
4943  * completely hide the primary plane.
4944  */
4945 static void
4946 intel_post_enable_primary(struct drm_crtc *crtc)
4947 {
4948         struct drm_device *dev = crtc->dev;
4949         struct drm_i915_private *dev_priv = to_i915(dev);
4950         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4951         int pipe = intel_crtc->pipe;
4952
4953         /*
4954          * FIXME IPS should be fine as long as one plane is
4955          * enabled, but in practice it seems to have problems
4956          * when going from primary only to sprite only and vice
4957          * versa.
4958          */
4959         hsw_enable_ips(intel_crtc);
4960
4961         /*
4962          * Gen2 reports pipe underruns whenever all planes are disabled.
4963          * So don't enable underrun reporting before at least some planes
4964          * are enabled.
4965          * FIXME: Need to fix the logic to work when we turn off all planes
4966          * but leave the pipe running.
4967          */
4968         if (IS_GEN2(dev_priv))
4969                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
4970
4971         /* Underruns don't always raise interrupts, so check manually. */
4972         intel_check_cpu_fifo_underruns(dev_priv);
4973         intel_check_pch_fifo_underruns(dev_priv);
4974 }
4975
4976 /* FIXME move all this to pre_plane_update() with proper state tracking */
4977 static void
4978 intel_pre_disable_primary(struct drm_crtc *crtc)
4979 {
4980         struct drm_device *dev = crtc->dev;
4981         struct drm_i915_private *dev_priv = to_i915(dev);
4982         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4983         int pipe = intel_crtc->pipe;
4984
4985         /*
4986          * Gen2 reports pipe underruns whenever all planes are disabled.
4987          * So diasble underrun reporting before all the planes get disabled.
4988          * FIXME: Need to fix the logic to work when we turn off all planes
4989          * but leave the pipe running.
4990          */
4991         if (IS_GEN2(dev_priv))
4992                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
4993
4994         /*
4995          * FIXME IPS should be fine as long as one plane is
4996          * enabled, but in practice it seems to have problems
4997          * when going from primary only to sprite only and vice
4998          * versa.
4999          */
5000         hsw_disable_ips(intel_crtc);
5001 }
5002
5003 /* FIXME get rid of this and use pre_plane_update */
5004 static void
5005 intel_pre_disable_primary_noatomic(struct drm_crtc *crtc)
5006 {
5007         struct drm_device *dev = crtc->dev;
5008         struct drm_i915_private *dev_priv = to_i915(dev);
5009         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5010         int pipe = intel_crtc->pipe;
5011
5012         intel_pre_disable_primary(crtc);
5013
5014         /*
5015          * Vblank time updates from the shadow to live plane control register
5016          * are blocked if the memory self-refresh mode is active at that
5017          * moment. So to make sure the plane gets truly disabled, disable
5018          * first the self-refresh mode. The self-refresh enable bit in turn
5019          * will be checked/applied by the HW only at the next frame start
5020          * event which is after the vblank start event, so we need to have a
5021          * wait-for-vblank between disabling the plane and the pipe.
5022          */
5023         if (HAS_GMCH_DISPLAY(dev_priv)) {
5024                 intel_set_memory_cxsr(dev_priv, false);
5025                 dev_priv->wm.vlv.cxsr = false;
5026                 intel_wait_for_vblank(dev_priv, pipe);
5027         }
5028 }
5029
5030 static void intel_post_plane_update(struct intel_crtc_state *old_crtc_state)
5031 {
5032         struct intel_crtc *crtc = to_intel_crtc(old_crtc_state->base.crtc);
5033         struct drm_atomic_state *old_state = old_crtc_state->base.state;
5034         struct intel_crtc_state *pipe_config =
5035                 to_intel_crtc_state(crtc->base.state);
5036         struct drm_plane *primary = crtc->base.primary;
5037         struct drm_plane_state *old_pri_state =
5038                 drm_atomic_get_existing_plane_state(old_state, primary);
5039
5040         intel_frontbuffer_flip(to_i915(crtc->base.dev), pipe_config->fb_bits);
5041
5042         crtc->wm.cxsr_allowed = true;
5043
5044         if (pipe_config->update_wm_post && pipe_config->base.active)
5045                 intel_update_watermarks(crtc);
5046
5047         if (old_pri_state) {
5048                 struct intel_plane_state *primary_state =
5049                         to_intel_plane_state(primary->state);
5050                 struct intel_plane_state *old_primary_state =
5051                         to_intel_plane_state(old_pri_state);
5052
5053                 intel_fbc_post_update(crtc);
5054
5055                 if (primary_state->base.visible &&
5056                     (needs_modeset(&pipe_config->base) ||
5057                      !old_primary_state->base.visible))
5058                         intel_post_enable_primary(&crtc->base);
5059         }
5060 }
5061
5062 static void intel_pre_plane_update(struct intel_crtc_state *old_crtc_state)
5063 {
5064         struct intel_crtc *crtc = to_intel_crtc(old_crtc_state->base.crtc);
5065         struct drm_device *dev = crtc->base.dev;
5066         struct drm_i915_private *dev_priv = to_i915(dev);
5067         struct intel_crtc_state *pipe_config =
5068                 to_intel_crtc_state(crtc->base.state);
5069         struct drm_atomic_state *old_state = old_crtc_state->base.state;
5070         struct drm_plane *primary = crtc->base.primary;
5071         struct drm_plane_state *old_pri_state =
5072                 drm_atomic_get_existing_plane_state(old_state, primary);
5073         bool modeset = needs_modeset(&pipe_config->base);
5074         struct intel_atomic_state *old_intel_state =
5075                 to_intel_atomic_state(old_state);
5076
5077         if (old_pri_state) {
5078                 struct intel_plane_state *primary_state =
5079                         to_intel_plane_state(primary->state);
5080                 struct intel_plane_state *old_primary_state =
5081                         to_intel_plane_state(old_pri_state);
5082
5083                 intel_fbc_pre_update(crtc, pipe_config, primary_state);
5084
5085                 if (old_primary_state->base.visible &&
5086                     (modeset || !primary_state->base.visible))
5087                         intel_pre_disable_primary(&crtc->base);
5088         }
5089
5090         if (pipe_config->disable_cxsr && HAS_GMCH_DISPLAY(dev_priv)) {
5091                 crtc->wm.cxsr_allowed = false;
5092
5093                 /*
5094                  * Vblank time updates from the shadow to live plane control register
5095                  * are blocked if the memory self-refresh mode is active at that
5096                  * moment. So to make sure the plane gets truly disabled, disable
5097                  * first the self-refresh mode. The self-refresh enable bit in turn
5098                  * will be checked/applied by the HW only at the next frame start
5099                  * event which is after the vblank start event, so we need to have a
5100                  * wait-for-vblank between disabling the plane and the pipe.
5101                  */
5102                 if (old_crtc_state->base.active) {
5103                         intel_set_memory_cxsr(dev_priv, false);
5104                         dev_priv->wm.vlv.cxsr = false;
5105                         intel_wait_for_vblank(dev_priv, crtc->pipe);
5106                 }
5107         }
5108
5109         /*
5110          * IVB workaround: must disable low power watermarks for at least
5111          * one frame before enabling scaling.  LP watermarks can be re-enabled
5112          * when scaling is disabled.
5113          *
5114          * WaCxSRDisabledForSpriteScaling:ivb
5115          */
5116         if (pipe_config->disable_lp_wm) {
5117                 ilk_disable_lp_wm(dev);
5118                 intel_wait_for_vblank(dev_priv, crtc->pipe);
5119         }
5120
5121         /*
5122          * If we're doing a modeset, we're done.  No need to do any pre-vblank
5123          * watermark programming here.
5124          */
5125         if (needs_modeset(&pipe_config->base))
5126                 return;
5127
5128         /*
5129          * For platforms that support atomic watermarks, program the
5130          * 'intermediate' watermarks immediately.  On pre-gen9 platforms, these
5131          * will be the intermediate values that are safe for both pre- and
5132          * post- vblank; when vblank happens, the 'active' values will be set
5133          * to the final 'target' values and we'll do this again to get the
5134          * optimal watermarks.  For gen9+ platforms, the values we program here
5135          * will be the final target values which will get automatically latched
5136          * at vblank time; no further programming will be necessary.
5137          *
5138          * If a platform hasn't been transitioned to atomic watermarks yet,
5139          * we'll continue to update watermarks the old way, if flags tell
5140          * us to.
5141          */
5142         if (dev_priv->display.initial_watermarks != NULL)
5143                 dev_priv->display.initial_watermarks(old_intel_state,
5144                                                      pipe_config);
5145         else if (pipe_config->update_wm_pre)
5146                 intel_update_watermarks(crtc);
5147 }
5148
5149 static void intel_crtc_disable_planes(struct drm_crtc *crtc, unsigned plane_mask)
5150 {
5151         struct drm_device *dev = crtc->dev;
5152         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5153         struct drm_plane *p;
5154         int pipe = intel_crtc->pipe;
5155
5156         intel_crtc_dpms_overlay_disable(intel_crtc);
5157
5158         drm_for_each_plane_mask(p, dev, plane_mask)
5159                 to_intel_plane(p)->disable_plane(p, crtc);
5160
5161         /*
5162          * FIXME: Once we grow proper nuclear flip support out of this we need
5163          * to compute the mask of flip planes precisely. For the time being
5164          * consider this a flip to a NULL plane.
5165          */
5166         intel_frontbuffer_flip(to_i915(dev), INTEL_FRONTBUFFER_ALL_MASK(pipe));
5167 }
5168
5169 static void intel_encoders_pre_pll_enable(struct drm_crtc *crtc,
5170                                           struct intel_crtc_state *crtc_state,
5171                                           struct drm_atomic_state *old_state)
5172 {
5173         struct drm_connector_state *old_conn_state;
5174         struct drm_connector *conn;
5175         int i;
5176
5177         for_each_connector_in_state(old_state, conn, old_conn_state, i) {
5178                 struct drm_connector_state *conn_state = conn->state;
5179                 struct intel_encoder *encoder =
5180                         to_intel_encoder(conn_state->best_encoder);
5181
5182                 if (conn_state->crtc != crtc)
5183                         continue;
5184
5185                 if (encoder->pre_pll_enable)
5186                         encoder->pre_pll_enable(encoder, crtc_state, conn_state);
5187         }
5188 }
5189
5190 static void intel_encoders_pre_enable(struct drm_crtc *crtc,
5191                                       struct intel_crtc_state *crtc_state,
5192                                       struct drm_atomic_state *old_state)
5193 {
5194         struct drm_connector_state *old_conn_state;
5195         struct drm_connector *conn;
5196         int i;
5197
5198         for_each_connector_in_state(old_state, conn, old_conn_state, i) {
5199                 struct drm_connector_state *conn_state = conn->state;
5200                 struct intel_encoder *encoder =
5201                         to_intel_encoder(conn_state->best_encoder);
5202
5203                 if (conn_state->crtc != crtc)
5204                         continue;
5205
5206                 if (encoder->pre_enable)
5207                         encoder->pre_enable(encoder, crtc_state, conn_state);
5208         }
5209 }
5210
5211 static void intel_encoders_enable(struct drm_crtc *crtc,
5212                                   struct intel_crtc_state *crtc_state,
5213                                   struct drm_atomic_state *old_state)
5214 {
5215         struct drm_connector_state *old_conn_state;
5216         struct drm_connector *conn;
5217         int i;
5218
5219         for_each_connector_in_state(old_state, conn, old_conn_state, i) {
5220                 struct drm_connector_state *conn_state = conn->state;
5221                 struct intel_encoder *encoder =
5222                         to_intel_encoder(conn_state->best_encoder);
5223
5224                 if (conn_state->crtc != crtc)
5225                         continue;
5226
5227                 encoder->enable(encoder, crtc_state, conn_state);
5228                 intel_opregion_notify_encoder(encoder, true);
5229         }
5230 }
5231
5232 static void intel_encoders_disable(struct drm_crtc *crtc,
5233                                    struct intel_crtc_state *old_crtc_state,
5234                                    struct drm_atomic_state *old_state)
5235 {
5236         struct drm_connector_state *old_conn_state;
5237         struct drm_connector *conn;
5238         int i;
5239
5240         for_each_connector_in_state(old_state, conn, old_conn_state, i) {
5241                 struct intel_encoder *encoder =
5242                         to_intel_encoder(old_conn_state->best_encoder);
5243
5244                 if (old_conn_state->crtc != crtc)
5245                         continue;
5246
5247                 intel_opregion_notify_encoder(encoder, false);
5248                 encoder->disable(encoder, old_crtc_state, old_conn_state);
5249         }
5250 }
5251
5252 static void intel_encoders_post_disable(struct drm_crtc *crtc,
5253                                         struct intel_crtc_state *old_crtc_state,
5254                                         struct drm_atomic_state *old_state)
5255 {
5256         struct drm_connector_state *old_conn_state;
5257         struct drm_connector *conn;
5258         int i;
5259
5260         for_each_connector_in_state(old_state, conn, old_conn_state, i) {
5261                 struct intel_encoder *encoder =
5262                         to_intel_encoder(old_conn_state->best_encoder);
5263
5264                 if (old_conn_state->crtc != crtc)
5265                         continue;
5266
5267                 if (encoder->post_disable)
5268                         encoder->post_disable(encoder, old_crtc_state, old_conn_state);
5269         }
5270 }
5271
5272 static void intel_encoders_post_pll_disable(struct drm_crtc *crtc,
5273                                             struct intel_crtc_state *old_crtc_state,
5274                                             struct drm_atomic_state *old_state)
5275 {
5276         struct drm_connector_state *old_conn_state;
5277         struct drm_connector *conn;
5278         int i;
5279
5280         for_each_connector_in_state(old_state, conn, old_conn_state, i) {
5281                 struct intel_encoder *encoder =
5282                         to_intel_encoder(old_conn_state->best_encoder);
5283
5284                 if (old_conn_state->crtc != crtc)
5285                         continue;
5286
5287                 if (encoder->post_pll_disable)
5288                         encoder->post_pll_disable(encoder, old_crtc_state, old_conn_state);
5289         }
5290 }
5291
5292 static void ironlake_crtc_enable(struct intel_crtc_state *pipe_config,
5293                                  struct drm_atomic_state *old_state)
5294 {
5295         struct drm_crtc *crtc = pipe_config->base.crtc;
5296         struct drm_device *dev = crtc->dev;
5297         struct drm_i915_private *dev_priv = to_i915(dev);
5298         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5299         int pipe = intel_crtc->pipe;
5300         struct intel_atomic_state *old_intel_state =
5301                 to_intel_atomic_state(old_state);
5302
5303         if (WARN_ON(intel_crtc->active))
5304                 return;
5305
5306         /*
5307          * Sometimes spurious CPU pipe underruns happen during FDI
5308          * training, at least with VGA+HDMI cloning. Suppress them.
5309          *
5310          * On ILK we get an occasional spurious CPU pipe underruns
5311          * between eDP port A enable and vdd enable. Also PCH port
5312          * enable seems to result in the occasional CPU pipe underrun.
5313          *
5314          * Spurious PCH underruns also occur during PCH enabling.
5315          */
5316         if (intel_crtc->config->has_pch_encoder || IS_GEN5(dev_priv))
5317                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
5318         if (intel_crtc->config->has_pch_encoder)
5319                 intel_set_pch_fifo_underrun_reporting(dev_priv, pipe, false);
5320
5321         if (intel_crtc->config->has_pch_encoder)
5322                 intel_prepare_shared_dpll(intel_crtc);
5323
5324         if (intel_crtc_has_dp_encoder(intel_crtc->config))
5325                 intel_dp_set_m_n(intel_crtc, M1_N1);
5326
5327         intel_set_pipe_timings(intel_crtc);
5328         intel_set_pipe_src_size(intel_crtc);
5329
5330         if (intel_crtc->config->has_pch_encoder) {
5331                 intel_cpu_transcoder_set_m_n(intel_crtc,
5332                                      &intel_crtc->config->fdi_m_n, NULL);
5333         }
5334
5335         ironlake_set_pipeconf(crtc);
5336
5337         intel_crtc->active = true;
5338
5339         intel_encoders_pre_enable(crtc, pipe_config, old_state);
5340
5341         if (intel_crtc->config->has_pch_encoder) {
5342                 /* Note: FDI PLL enabling _must_ be done before we enable the
5343                  * cpu pipes, hence this is separate from all the other fdi/pch
5344                  * enabling. */
5345                 ironlake_fdi_pll_enable(intel_crtc);
5346         } else {
5347                 assert_fdi_tx_disabled(dev_priv, pipe);
5348                 assert_fdi_rx_disabled(dev_priv, pipe);
5349         }
5350
5351         ironlake_pfit_enable(intel_crtc);
5352
5353         /*
5354          * On ILK+ LUT must be loaded before the pipe is running but with
5355          * clocks enabled
5356          */
5357         intel_color_load_luts(&pipe_config->base);
5358
5359         if (dev_priv->display.initial_watermarks != NULL)
5360                 dev_priv->display.initial_watermarks(old_intel_state, intel_crtc->config);
5361         intel_enable_pipe(intel_crtc);
5362
5363         if (intel_crtc->config->has_pch_encoder)
5364                 ironlake_pch_enable(crtc);
5365
5366         assert_vblank_disabled(crtc);
5367         drm_crtc_vblank_on(crtc);
5368
5369         intel_encoders_enable(crtc, pipe_config, old_state);
5370
5371         if (HAS_PCH_CPT(dev_priv))
5372                 cpt_verify_modeset(dev, intel_crtc->pipe);
5373
5374         /* Must wait for vblank to avoid spurious PCH FIFO underruns */
5375         if (intel_crtc->config->has_pch_encoder)
5376                 intel_wait_for_vblank(dev_priv, pipe);
5377         intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
5378         intel_set_pch_fifo_underrun_reporting(dev_priv, pipe, true);
5379 }
5380
5381 /* IPS only exists on ULT machines and is tied to pipe A. */
5382 static bool hsw_crtc_supports_ips(struct intel_crtc *crtc)
5383 {
5384         return HAS_IPS(to_i915(crtc->base.dev)) && crtc->pipe == PIPE_A;
5385 }
5386
5387 static void haswell_crtc_enable(struct intel_crtc_state *pipe_config,
5388                                 struct drm_atomic_state *old_state)
5389 {
5390         struct drm_crtc *crtc = pipe_config->base.crtc;
5391         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
5392         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5393         int pipe = intel_crtc->pipe, hsw_workaround_pipe;
5394         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
5395         struct intel_atomic_state *old_intel_state =
5396                 to_intel_atomic_state(old_state);
5397
5398         if (WARN_ON(intel_crtc->active))
5399                 return;
5400
5401         if (intel_crtc->config->has_pch_encoder)
5402                 intel_set_pch_fifo_underrun_reporting(dev_priv, TRANSCODER_A,
5403                                                       false);
5404
5405         intel_encoders_pre_pll_enable(crtc, pipe_config, old_state);
5406
5407         if (intel_crtc->config->shared_dpll)
5408                 intel_enable_shared_dpll(intel_crtc);
5409
5410         if (intel_crtc_has_dp_encoder(intel_crtc->config))
5411                 intel_dp_set_m_n(intel_crtc, M1_N1);
5412
5413         if (!transcoder_is_dsi(cpu_transcoder))
5414                 intel_set_pipe_timings(intel_crtc);
5415
5416         intel_set_pipe_src_size(intel_crtc);
5417
5418         if (cpu_transcoder != TRANSCODER_EDP &&
5419             !transcoder_is_dsi(cpu_transcoder)) {
5420                 I915_WRITE(PIPE_MULT(cpu_transcoder),
5421                            intel_crtc->config->pixel_multiplier - 1);
5422         }
5423
5424         if (intel_crtc->config->has_pch_encoder) {
5425                 intel_cpu_transcoder_set_m_n(intel_crtc,
5426                                      &intel_crtc->config->fdi_m_n, NULL);
5427         }
5428
5429         if (!transcoder_is_dsi(cpu_transcoder))
5430                 haswell_set_pipeconf(crtc);
5431
5432         haswell_set_pipemisc(crtc);
5433
5434         intel_color_set_csc(&pipe_config->base);
5435
5436         intel_crtc->active = true;
5437
5438         if (intel_crtc->config->has_pch_encoder)
5439                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
5440         else
5441                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
5442
5443         intel_encoders_pre_enable(crtc, pipe_config, old_state);
5444
5445         if (intel_crtc->config->has_pch_encoder)
5446                 dev_priv->display.fdi_link_train(crtc);
5447
5448         if (!transcoder_is_dsi(cpu_transcoder))
5449                 intel_ddi_enable_pipe_clock(intel_crtc);
5450
5451         if (INTEL_GEN(dev_priv) >= 9)
5452                 skylake_pfit_enable(intel_crtc);
5453         else
5454                 ironlake_pfit_enable(intel_crtc);
5455
5456         /*
5457          * On ILK+ LUT must be loaded before the pipe is running but with
5458          * clocks enabled
5459          */
5460         intel_color_load_luts(&pipe_config->base);
5461
5462         intel_ddi_set_pipe_settings(crtc);
5463         if (!transcoder_is_dsi(cpu_transcoder))
5464                 intel_ddi_enable_transcoder_func(crtc);
5465
5466         if (dev_priv->display.initial_watermarks != NULL)
5467                 dev_priv->display.initial_watermarks(old_intel_state,
5468                                                      pipe_config);
5469         else
5470                 intel_update_watermarks(intel_crtc);
5471
5472         /* XXX: Do the pipe assertions at the right place for BXT DSI. */
5473         if (!transcoder_is_dsi(cpu_transcoder))
5474                 intel_enable_pipe(intel_crtc);
5475
5476         if (intel_crtc->config->has_pch_encoder)
5477                 lpt_pch_enable(crtc);
5478
5479         if (intel_crtc_has_type(intel_crtc->config, INTEL_OUTPUT_DP_MST))
5480                 intel_ddi_set_vc_payload_alloc(crtc, true);
5481
5482         assert_vblank_disabled(crtc);
5483         drm_crtc_vblank_on(crtc);
5484
5485         intel_encoders_enable(crtc, pipe_config, old_state);
5486
5487         if (intel_crtc->config->has_pch_encoder) {
5488                 intel_wait_for_vblank(dev_priv, pipe);
5489                 intel_wait_for_vblank(dev_priv, pipe);
5490                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
5491                 intel_set_pch_fifo_underrun_reporting(dev_priv, TRANSCODER_A,
5492                                                       true);
5493         }
5494
5495         /* If we change the relative order between pipe/planes enabling, we need
5496          * to change the workaround. */
5497         hsw_workaround_pipe = pipe_config->hsw_workaround_pipe;
5498         if (IS_HASWELL(dev_priv) && hsw_workaround_pipe != INVALID_PIPE) {
5499                 intel_wait_for_vblank(dev_priv, hsw_workaround_pipe);
5500                 intel_wait_for_vblank(dev_priv, hsw_workaround_pipe);
5501         }
5502 }
5503
5504 static void ironlake_pfit_disable(struct intel_crtc *crtc, bool force)
5505 {
5506         struct drm_device *dev = crtc->base.dev;
5507         struct drm_i915_private *dev_priv = to_i915(dev);
5508         int pipe = crtc->pipe;
5509
5510         /* To avoid upsetting the power well on haswell only disable the pfit if
5511          * it's in use. The hw state code will make sure we get this right. */
5512         if (force || crtc->config->pch_pfit.enabled) {
5513                 I915_WRITE(PF_CTL(pipe), 0);
5514                 I915_WRITE(PF_WIN_POS(pipe), 0);
5515                 I915_WRITE(PF_WIN_SZ(pipe), 0);
5516         }
5517 }
5518
5519 static void ironlake_crtc_disable(struct intel_crtc_state *old_crtc_state,
5520                                   struct drm_atomic_state *old_state)
5521 {
5522         struct drm_crtc *crtc = old_crtc_state->base.crtc;
5523         struct drm_device *dev = crtc->dev;
5524         struct drm_i915_private *dev_priv = to_i915(dev);
5525         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5526         int pipe = intel_crtc->pipe;
5527
5528         /*
5529          * Sometimes spurious CPU pipe underruns happen when the
5530          * pipe is already disabled, but FDI RX/TX is still enabled.
5531          * Happens at least with VGA+HDMI cloning. Suppress them.
5532          */
5533         if (intel_crtc->config->has_pch_encoder) {
5534                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
5535                 intel_set_pch_fifo_underrun_reporting(dev_priv, pipe, false);
5536         }
5537
5538         intel_encoders_disable(crtc, old_crtc_state, old_state);
5539
5540         drm_crtc_vblank_off(crtc);
5541         assert_vblank_disabled(crtc);
5542
5543         intel_disable_pipe(intel_crtc);
5544
5545         ironlake_pfit_disable(intel_crtc, false);
5546
5547         if (intel_crtc->config->has_pch_encoder)
5548                 ironlake_fdi_disable(crtc);
5549
5550         intel_encoders_post_disable(crtc, old_crtc_state, old_state);
5551
5552         if (intel_crtc->config->has_pch_encoder) {
5553                 ironlake_disable_pch_transcoder(dev_priv, pipe);
5554
5555                 if (HAS_PCH_CPT(dev_priv)) {
5556                         i915_reg_t reg;
5557                         u32 temp;
5558
5559                         /* disable TRANS_DP_CTL */
5560                         reg = TRANS_DP_CTL(pipe);
5561                         temp = I915_READ(reg);
5562                         temp &= ~(TRANS_DP_OUTPUT_ENABLE |
5563                                   TRANS_DP_PORT_SEL_MASK);
5564                         temp |= TRANS_DP_PORT_SEL_NONE;
5565                         I915_WRITE(reg, temp);
5566
5567                         /* disable DPLL_SEL */
5568                         temp = I915_READ(PCH_DPLL_SEL);
5569                         temp &= ~(TRANS_DPLL_ENABLE(pipe) | TRANS_DPLLB_SEL(pipe));
5570                         I915_WRITE(PCH_DPLL_SEL, temp);
5571                 }
5572
5573                 ironlake_fdi_pll_disable(intel_crtc);
5574         }
5575
5576         intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
5577         intel_set_pch_fifo_underrun_reporting(dev_priv, pipe, true);
5578 }
5579
5580 static void haswell_crtc_disable(struct intel_crtc_state *old_crtc_state,
5581                                  struct drm_atomic_state *old_state)
5582 {
5583         struct drm_crtc *crtc = old_crtc_state->base.crtc;
5584         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
5585         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5586         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
5587
5588         if (intel_crtc->config->has_pch_encoder)
5589                 intel_set_pch_fifo_underrun_reporting(dev_priv, TRANSCODER_A,
5590                                                       false);
5591
5592         intel_encoders_disable(crtc, old_crtc_state, old_state);
5593
5594         drm_crtc_vblank_off(crtc);
5595         assert_vblank_disabled(crtc);
5596
5597         /* XXX: Do the pipe assertions at the right place for BXT DSI. */
5598         if (!transcoder_is_dsi(cpu_transcoder))
5599                 intel_disable_pipe(intel_crtc);
5600
5601         if (intel_crtc_has_type(intel_crtc->config, INTEL_OUTPUT_DP_MST))
5602                 intel_ddi_set_vc_payload_alloc(crtc, false);
5603
5604         if (!transcoder_is_dsi(cpu_transcoder))
5605                 intel_ddi_disable_transcoder_func(dev_priv, cpu_transcoder);
5606
5607         if (INTEL_GEN(dev_priv) >= 9)
5608                 skylake_scaler_disable(intel_crtc);
5609         else
5610                 ironlake_pfit_disable(intel_crtc, false);
5611
5612         if (!transcoder_is_dsi(cpu_transcoder))
5613                 intel_ddi_disable_pipe_clock(intel_crtc);
5614
5615         intel_encoders_post_disable(crtc, old_crtc_state, old_state);
5616
5617         if (old_crtc_state->has_pch_encoder)
5618                 intel_set_pch_fifo_underrun_reporting(dev_priv, TRANSCODER_A,
5619                                                       true);
5620 }
5621
5622 static void i9xx_pfit_enable(struct intel_crtc *crtc)
5623 {
5624         struct drm_device *dev = crtc->base.dev;
5625         struct drm_i915_private *dev_priv = to_i915(dev);
5626         struct intel_crtc_state *pipe_config = crtc->config;
5627
5628         if (!pipe_config->gmch_pfit.control)
5629                 return;
5630
5631         /*
5632          * The panel fitter should only be adjusted whilst the pipe is disabled,
5633          * according to register description and PRM.
5634          */
5635         WARN_ON(I915_READ(PFIT_CONTROL) & PFIT_ENABLE);
5636         assert_pipe_disabled(dev_priv, crtc->pipe);
5637
5638         I915_WRITE(PFIT_PGM_RATIOS, pipe_config->gmch_pfit.pgm_ratios);
5639         I915_WRITE(PFIT_CONTROL, pipe_config->gmch_pfit.control);
5640
5641         /* Border color in case we don't scale up to the full screen. Black by
5642          * default, change to something else for debugging. */
5643         I915_WRITE(BCLRPAT(crtc->pipe), 0);
5644 }
5645
5646 static enum intel_display_power_domain port_to_power_domain(enum port port)
5647 {
5648         switch (port) {
5649         case PORT_A:
5650                 return POWER_DOMAIN_PORT_DDI_A_LANES;
5651         case PORT_B:
5652                 return POWER_DOMAIN_PORT_DDI_B_LANES;
5653         case PORT_C:
5654                 return POWER_DOMAIN_PORT_DDI_C_LANES;
5655         case PORT_D:
5656                 return POWER_DOMAIN_PORT_DDI_D_LANES;
5657         case PORT_E:
5658                 return POWER_DOMAIN_PORT_DDI_E_LANES;
5659         default:
5660                 MISSING_CASE(port);
5661                 return POWER_DOMAIN_PORT_OTHER;
5662         }
5663 }
5664
5665 static enum intel_display_power_domain port_to_aux_power_domain(enum port port)
5666 {
5667         switch (port) {
5668         case PORT_A:
5669                 return POWER_DOMAIN_AUX_A;
5670         case PORT_B:
5671                 return POWER_DOMAIN_AUX_B;
5672         case PORT_C:
5673                 return POWER_DOMAIN_AUX_C;
5674         case PORT_D:
5675                 return POWER_DOMAIN_AUX_D;
5676         case PORT_E:
5677                 /* FIXME: Check VBT for actual wiring of PORT E */
5678                 return POWER_DOMAIN_AUX_D;
5679         default:
5680                 MISSING_CASE(port);
5681                 return POWER_DOMAIN_AUX_A;
5682         }
5683 }
5684
5685 enum intel_display_power_domain
5686 intel_display_port_power_domain(struct intel_encoder *intel_encoder)
5687 {
5688         struct drm_i915_private *dev_priv = to_i915(intel_encoder->base.dev);
5689         struct intel_digital_port *intel_dig_port;
5690
5691         switch (intel_encoder->type) {
5692         case INTEL_OUTPUT_UNKNOWN:
5693                 /* Only DDI platforms should ever use this output type */
5694                 WARN_ON_ONCE(!HAS_DDI(dev_priv));
5695         case INTEL_OUTPUT_DP:
5696         case INTEL_OUTPUT_HDMI:
5697         case INTEL_OUTPUT_EDP:
5698                 intel_dig_port = enc_to_dig_port(&intel_encoder->base);
5699                 return port_to_power_domain(intel_dig_port->port);
5700         case INTEL_OUTPUT_DP_MST:
5701                 intel_dig_port = enc_to_mst(&intel_encoder->base)->primary;
5702                 return port_to_power_domain(intel_dig_port->port);
5703         case INTEL_OUTPUT_ANALOG:
5704                 return POWER_DOMAIN_PORT_CRT;
5705         case INTEL_OUTPUT_DSI:
5706                 return POWER_DOMAIN_PORT_DSI;
5707         default:
5708                 return POWER_DOMAIN_PORT_OTHER;
5709         }
5710 }
5711
5712 enum intel_display_power_domain
5713 intel_display_port_aux_power_domain(struct intel_encoder *intel_encoder)
5714 {
5715         struct drm_i915_private *dev_priv = to_i915(intel_encoder->base.dev);
5716         struct intel_digital_port *intel_dig_port;
5717
5718         switch (intel_encoder->type) {
5719         case INTEL_OUTPUT_UNKNOWN:
5720         case INTEL_OUTPUT_HDMI:
5721                 /*
5722                  * Only DDI platforms should ever use these output types.
5723                  * We can get here after the HDMI detect code has already set
5724                  * the type of the shared encoder. Since we can't be sure
5725                  * what's the status of the given connectors, play safe and
5726                  * run the DP detection too.
5727                  */
5728                 WARN_ON_ONCE(!HAS_DDI(dev_priv));
5729         case INTEL_OUTPUT_DP:
5730         case INTEL_OUTPUT_EDP:
5731                 intel_dig_port = enc_to_dig_port(&intel_encoder->base);
5732                 return port_to_aux_power_domain(intel_dig_port->port);
5733         case INTEL_OUTPUT_DP_MST:
5734                 intel_dig_port = enc_to_mst(&intel_encoder->base)->primary;
5735                 return port_to_aux_power_domain(intel_dig_port->port);
5736         default:
5737                 MISSING_CASE(intel_encoder->type);
5738                 return POWER_DOMAIN_AUX_A;
5739         }
5740 }
5741
5742 static unsigned long get_crtc_power_domains(struct drm_crtc *crtc,
5743                                             struct intel_crtc_state *crtc_state)
5744 {
5745         struct drm_device *dev = crtc->dev;
5746         struct drm_encoder *encoder;
5747         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5748         enum pipe pipe = intel_crtc->pipe;
5749         unsigned long mask;
5750         enum transcoder transcoder = crtc_state->cpu_transcoder;
5751
5752         if (!crtc_state->base.active)
5753                 return 0;
5754
5755         mask = BIT(POWER_DOMAIN_PIPE(pipe));
5756         mask |= BIT(POWER_DOMAIN_TRANSCODER(transcoder));
5757         if (crtc_state->pch_pfit.enabled ||
5758             crtc_state->pch_pfit.force_thru)
5759                 mask |= BIT(POWER_DOMAIN_PIPE_PANEL_FITTER(pipe));
5760
5761         drm_for_each_encoder_mask(encoder, dev, crtc_state->base.encoder_mask) {
5762                 struct intel_encoder *intel_encoder = to_intel_encoder(encoder);
5763
5764                 mask |= BIT(intel_display_port_power_domain(intel_encoder));
5765         }
5766
5767         if (crtc_state->shared_dpll)
5768                 mask |= BIT(POWER_DOMAIN_PLLS);
5769
5770         return mask;
5771 }
5772
5773 static unsigned long
5774 modeset_get_crtc_power_domains(struct drm_crtc *crtc,
5775                                struct intel_crtc_state *crtc_state)
5776 {
5777         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
5778         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5779         enum intel_display_power_domain domain;
5780         unsigned long domains, new_domains, old_domains;
5781
5782         old_domains = intel_crtc->enabled_power_domains;
5783         intel_crtc->enabled_power_domains = new_domains =
5784                 get_crtc_power_domains(crtc, crtc_state);
5785
5786         domains = new_domains & ~old_domains;
5787
5788         for_each_power_domain(domain, domains)
5789                 intel_display_power_get(dev_priv, domain);
5790
5791         return old_domains & ~new_domains;
5792 }
5793
5794 static void modeset_put_power_domains(struct drm_i915_private *dev_priv,
5795                                       unsigned long domains)
5796 {
5797         enum intel_display_power_domain domain;
5798
5799         for_each_power_domain(domain, domains)
5800                 intel_display_power_put(dev_priv, domain);
5801 }
5802
5803 static int intel_compute_max_dotclk(struct drm_i915_private *dev_priv)
5804 {
5805         int max_cdclk_freq = dev_priv->max_cdclk_freq;
5806
5807         if (INTEL_INFO(dev_priv)->gen >= 9 ||
5808             IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv))
5809                 return max_cdclk_freq;
5810         else if (IS_CHERRYVIEW(dev_priv))
5811                 return max_cdclk_freq*95/100;
5812         else if (INTEL_INFO(dev_priv)->gen < 4)
5813                 return 2*max_cdclk_freq*90/100;
5814         else
5815                 return max_cdclk_freq*90/100;
5816 }
5817
5818 static int skl_calc_cdclk(int max_pixclk, int vco);
5819
5820 static void intel_update_max_cdclk(struct drm_i915_private *dev_priv)
5821 {
5822         if (IS_SKYLAKE(dev_priv) || IS_KABYLAKE(dev_priv)) {
5823                 u32 limit = I915_READ(SKL_DFSM) & SKL_DFSM_CDCLK_LIMIT_MASK;
5824                 int max_cdclk, vco;
5825
5826                 vco = dev_priv->skl_preferred_vco_freq;
5827                 WARN_ON(vco != 8100000 && vco != 8640000);
5828
5829                 /*
5830                  * Use the lower (vco 8640) cdclk values as a
5831                  * first guess. skl_calc_cdclk() will correct it
5832                  * if the preferred vco is 8100 instead.
5833                  */
5834                 if (limit == SKL_DFSM_CDCLK_LIMIT_675)
5835                         max_cdclk = 617143;
5836                 else if (limit == SKL_DFSM_CDCLK_LIMIT_540)
5837                         max_cdclk = 540000;
5838                 else if (limit == SKL_DFSM_CDCLK_LIMIT_450)
5839                         max_cdclk = 432000;
5840                 else
5841                         max_cdclk = 308571;
5842
5843                 dev_priv->max_cdclk_freq = skl_calc_cdclk(max_cdclk, vco);
5844         } else if (IS_BROXTON(dev_priv)) {
5845                 dev_priv->max_cdclk_freq = 624000;
5846         } else if (IS_BROADWELL(dev_priv))  {
5847                 /*
5848                  * FIXME with extra cooling we can allow
5849                  * 540 MHz for ULX and 675 Mhz for ULT.
5850                  * How can we know if extra cooling is
5851                  * available? PCI ID, VTB, something else?
5852                  */
5853                 if (I915_READ(FUSE_STRAP) & HSW_CDCLK_LIMIT)
5854                         dev_priv->max_cdclk_freq = 450000;
5855                 else if (IS_BDW_ULX(dev_priv))
5856                         dev_priv->max_cdclk_freq = 450000;
5857                 else if (IS_BDW_ULT(dev_priv))
5858                         dev_priv->max_cdclk_freq = 540000;
5859                 else
5860                         dev_priv->max_cdclk_freq = 675000;
5861         } else if (IS_CHERRYVIEW(dev_priv)) {
5862                 dev_priv->max_cdclk_freq = 320000;
5863         } else if (IS_VALLEYVIEW(dev_priv)) {
5864                 dev_priv->max_cdclk_freq = 400000;
5865         } else {
5866                 /* otherwise assume cdclk is fixed */
5867                 dev_priv->max_cdclk_freq = dev_priv->cdclk_freq;
5868         }
5869
5870         dev_priv->max_dotclk_freq = intel_compute_max_dotclk(dev_priv);
5871
5872         DRM_DEBUG_DRIVER("Max CD clock rate: %d kHz\n",
5873                          dev_priv->max_cdclk_freq);
5874
5875         DRM_DEBUG_DRIVER("Max dotclock rate: %d kHz\n",
5876                          dev_priv->max_dotclk_freq);
5877 }
5878
5879 static void intel_update_cdclk(struct drm_i915_private *dev_priv)
5880 {
5881         dev_priv->cdclk_freq = dev_priv->display.get_display_clock_speed(dev_priv);
5882
5883         if (INTEL_GEN(dev_priv) >= 9)
5884                 DRM_DEBUG_DRIVER("Current CD clock rate: %d kHz, VCO: %d kHz, ref: %d kHz\n",
5885                                  dev_priv->cdclk_freq, dev_priv->cdclk_pll.vco,
5886                                  dev_priv->cdclk_pll.ref);
5887         else
5888                 DRM_DEBUG_DRIVER("Current CD clock rate: %d kHz\n",
5889                                  dev_priv->cdclk_freq);
5890
5891         /*
5892          * 9:0 CMBUS [sic] CDCLK frequency (cdfreq):
5893          * Programmng [sic] note: bit[9:2] should be programmed to the number
5894          * of cdclk that generates 4MHz reference clock freq which is used to
5895          * generate GMBus clock. This will vary with the cdclk freq.
5896          */
5897         if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
5898                 I915_WRITE(GMBUSFREQ_VLV, DIV_ROUND_UP(dev_priv->cdclk_freq, 1000));
5899 }
5900
5901 /* convert from kHz to .1 fixpoint MHz with -1MHz offset */
5902 static int skl_cdclk_decimal(int cdclk)
5903 {
5904         return DIV_ROUND_CLOSEST(cdclk - 1000, 500);
5905 }
5906
5907 static int bxt_de_pll_vco(struct drm_i915_private *dev_priv, int cdclk)
5908 {
5909         int ratio;
5910
5911         if (cdclk == dev_priv->cdclk_pll.ref)
5912                 return 0;
5913
5914         switch (cdclk) {
5915         default:
5916                 MISSING_CASE(cdclk);
5917         case 144000:
5918         case 288000:
5919         case 384000:
5920         case 576000:
5921                 ratio = 60;
5922                 break;
5923         case 624000:
5924                 ratio = 65;
5925                 break;
5926         }
5927
5928         return dev_priv->cdclk_pll.ref * ratio;
5929 }
5930
5931 static void bxt_de_pll_disable(struct drm_i915_private *dev_priv)
5932 {
5933         I915_WRITE(BXT_DE_PLL_ENABLE, 0);
5934
5935         /* Timeout 200us */
5936         if (intel_wait_for_register(dev_priv,
5937                                     BXT_DE_PLL_ENABLE, BXT_DE_PLL_LOCK, 0,
5938                                     1))
5939                 DRM_ERROR("timeout waiting for DE PLL unlock\n");
5940
5941         dev_priv->cdclk_pll.vco = 0;
5942 }
5943
5944 static void bxt_de_pll_enable(struct drm_i915_private *dev_priv, int vco)
5945 {
5946         int ratio = DIV_ROUND_CLOSEST(vco, dev_priv->cdclk_pll.ref);
5947         u32 val;
5948
5949         val = I915_READ(BXT_DE_PLL_CTL);
5950         val &= ~BXT_DE_PLL_RATIO_MASK;
5951         val |= BXT_DE_PLL_RATIO(ratio);
5952         I915_WRITE(BXT_DE_PLL_CTL, val);
5953
5954         I915_WRITE(BXT_DE_PLL_ENABLE, BXT_DE_PLL_PLL_ENABLE);
5955
5956         /* Timeout 200us */
5957         if (intel_wait_for_register(dev_priv,
5958                                     BXT_DE_PLL_ENABLE,
5959                                     BXT_DE_PLL_LOCK,
5960                                     BXT_DE_PLL_LOCK,
5961                                     1))
5962                 DRM_ERROR("timeout waiting for DE PLL lock\n");
5963
5964         dev_priv->cdclk_pll.vco = vco;
5965 }
5966
5967 static void bxt_set_cdclk(struct drm_i915_private *dev_priv, int cdclk)
5968 {
5969         u32 val, divider;
5970         int vco, ret;
5971
5972         vco = bxt_de_pll_vco(dev_priv, cdclk);
5973
5974         DRM_DEBUG_DRIVER("Changing CDCLK to %d kHz (VCO %d kHz)\n", cdclk, vco);
5975
5976         /* cdclk = vco / 2 / div{1,1.5,2,4} */
5977         switch (DIV_ROUND_CLOSEST(vco, cdclk)) {
5978         case 8:
5979                 divider = BXT_CDCLK_CD2X_DIV_SEL_4;
5980                 break;
5981         case 4:
5982                 divider = BXT_CDCLK_CD2X_DIV_SEL_2;
5983                 break;
5984         case 3:
5985                 divider = BXT_CDCLK_CD2X_DIV_SEL_1_5;
5986                 break;
5987         case 2:
5988                 divider = BXT_CDCLK_CD2X_DIV_SEL_1;
5989                 break;
5990         default:
5991                 WARN_ON(cdclk != dev_priv->cdclk_pll.ref);
5992                 WARN_ON(vco != 0);
5993
5994                 divider = BXT_CDCLK_CD2X_DIV_SEL_1;
5995                 break;
5996         }
5997
5998         /* Inform power controller of upcoming frequency change */
5999         mutex_lock(&dev_priv->rps.hw_lock);
6000         ret = sandybridge_pcode_write(dev_priv, HSW_PCODE_DE_WRITE_FREQ_REQ,
6001                                       0x80000000);
6002         mutex_unlock(&dev_priv->rps.hw_lock);
6003
6004         if (ret) {
6005                 DRM_ERROR("PCode CDCLK freq change notify failed (err %d, freq %d)\n",
6006                           ret, cdclk);
6007                 return;
6008         }
6009
6010         if (dev_priv->cdclk_pll.vco != 0 &&
6011             dev_priv->cdclk_pll.vco != vco)
6012                 bxt_de_pll_disable(dev_priv);
6013
6014         if (dev_priv->cdclk_pll.vco != vco)
6015                 bxt_de_pll_enable(dev_priv, vco);
6016
6017         val = divider | skl_cdclk_decimal(cdclk);
6018         /*
6019          * FIXME if only the cd2x divider needs changing, it could be done
6020          * without shutting off the pipe (if only one pipe is active).
6021          */
6022         val |= BXT_CDCLK_CD2X_PIPE_NONE;
6023         /*
6024          * Disable SSA Precharge when CD clock frequency < 500 MHz,
6025          * enable otherwise.
6026          */
6027         if (cdclk >= 500000)
6028                 val |= BXT_CDCLK_SSA_PRECHARGE_ENABLE;
6029         I915_WRITE(CDCLK_CTL, val);
6030
6031         mutex_lock(&dev_priv->rps.hw_lock);
6032         ret = sandybridge_pcode_write(dev_priv, HSW_PCODE_DE_WRITE_FREQ_REQ,
6033                                       DIV_ROUND_UP(cdclk, 25000));
6034         mutex_unlock(&dev_priv->rps.hw_lock);
6035
6036         if (ret) {
6037                 DRM_ERROR("PCode CDCLK freq set failed, (err %d, freq %d)\n",
6038                           ret, cdclk);
6039                 return;
6040         }
6041
6042         intel_update_cdclk(dev_priv);
6043 }
6044
6045 static void bxt_sanitize_cdclk(struct drm_i915_private *dev_priv)
6046 {
6047         u32 cdctl, expected;
6048
6049         intel_update_cdclk(dev_priv);
6050
6051         if (dev_priv->cdclk_pll.vco == 0 ||
6052             dev_priv->cdclk_freq == dev_priv->cdclk_pll.ref)
6053                 goto sanitize;
6054
6055         /* DPLL okay; verify the cdclock
6056          *
6057          * Some BIOS versions leave an incorrect decimal frequency value and
6058          * set reserved MBZ bits in CDCLK_CTL at least during exiting from S4,
6059          * so sanitize this register.
6060          */
6061         cdctl = I915_READ(CDCLK_CTL);
6062         /*
6063          * Let's ignore the pipe field, since BIOS could have configured the
6064          * dividers both synching to an active pipe, or asynchronously
6065          * (PIPE_NONE).
6066          */
6067         cdctl &= ~BXT_CDCLK_CD2X_PIPE_NONE;
6068
6069         expected = (cdctl & BXT_CDCLK_CD2X_DIV_SEL_MASK) |
6070                    skl_cdclk_decimal(dev_priv->cdclk_freq);
6071         /*
6072          * Disable SSA Precharge when CD clock frequency < 500 MHz,
6073          * enable otherwise.
6074          */
6075         if (dev_priv->cdclk_freq >= 500000)
6076                 expected |= BXT_CDCLK_SSA_PRECHARGE_ENABLE;
6077
6078         if (cdctl == expected)
6079                 /* All well; nothing to sanitize */
6080                 return;
6081
6082 sanitize:
6083         DRM_DEBUG_KMS("Sanitizing cdclk programmed by pre-os\n");
6084
6085         /* force cdclk programming */
6086         dev_priv->cdclk_freq = 0;
6087
6088         /* force full PLL disable + enable */
6089         dev_priv->cdclk_pll.vco = -1;
6090 }
6091
6092 void bxt_init_cdclk(struct drm_i915_private *dev_priv)
6093 {
6094         bxt_sanitize_cdclk(dev_priv);
6095
6096         if (dev_priv->cdclk_freq != 0 && dev_priv->cdclk_pll.vco != 0)
6097                 return;
6098
6099         /*
6100          * FIXME:
6101          * - The initial CDCLK needs to be read from VBT.
6102          *   Need to make this change after VBT has changes for BXT.
6103          */
6104         bxt_set_cdclk(dev_priv, bxt_calc_cdclk(0));
6105 }
6106
6107 void bxt_uninit_cdclk(struct drm_i915_private *dev_priv)
6108 {
6109         bxt_set_cdclk(dev_priv, dev_priv->cdclk_pll.ref);
6110 }
6111
6112 static int skl_calc_cdclk(int max_pixclk, int vco)
6113 {
6114         if (vco == 8640000) {
6115                 if (max_pixclk > 540000)
6116                         return 617143;
6117                 else if (max_pixclk > 432000)
6118                         return 540000;
6119                 else if (max_pixclk > 308571)
6120                         return 432000;
6121                 else
6122                         return 308571;
6123         } else {
6124                 if (max_pixclk > 540000)
6125                         return 675000;
6126                 else if (max_pixclk > 450000)
6127                         return 540000;
6128                 else if (max_pixclk > 337500)
6129                         return 450000;
6130                 else
6131                         return 337500;
6132         }
6133 }
6134
6135 static void
6136 skl_dpll0_update(struct drm_i915_private *dev_priv)
6137 {
6138         u32 val;
6139
6140         dev_priv->cdclk_pll.ref = 24000;
6141         dev_priv->cdclk_pll.vco = 0;
6142
6143         val = I915_READ(LCPLL1_CTL);
6144         if ((val & LCPLL_PLL_ENABLE) == 0)
6145                 return;
6146
6147         if (WARN_ON((val & LCPLL_PLL_LOCK) == 0))
6148                 return;
6149
6150         val = I915_READ(DPLL_CTRL1);
6151
6152         if (WARN_ON((val & (DPLL_CTRL1_HDMI_MODE(SKL_DPLL0) |
6153                             DPLL_CTRL1_SSC(SKL_DPLL0) |
6154                             DPLL_CTRL1_OVERRIDE(SKL_DPLL0))) !=
6155                     DPLL_CTRL1_OVERRIDE(SKL_DPLL0)))
6156                 return;
6157
6158         switch (val & DPLL_CTRL1_LINK_RATE_MASK(SKL_DPLL0)) {
6159         case DPLL_CTRL1_LINK_RATE(DPLL_CTRL1_LINK_RATE_810, SKL_DPLL0):
6160         case DPLL_CTRL1_LINK_RATE(DPLL_CTRL1_LINK_RATE_1350, SKL_DPLL0):
6161         case DPLL_CTRL1_LINK_RATE(DPLL_CTRL1_LINK_RATE_1620, SKL_DPLL0):
6162         case DPLL_CTRL1_LINK_RATE(DPLL_CTRL1_LINK_RATE_2700, SKL_DPLL0):
6163                 dev_priv->cdclk_pll.vco = 8100000;
6164                 break;
6165         case DPLL_CTRL1_LINK_RATE(DPLL_CTRL1_LINK_RATE_1080, SKL_DPLL0):
6166         case DPLL_CTRL1_LINK_RATE(DPLL_CTRL1_LINK_RATE_2160, SKL_DPLL0):
6167                 dev_priv->cdclk_pll.vco = 8640000;
6168                 break;
6169         default:
6170                 MISSING_CASE(val & DPLL_CTRL1_LINK_RATE_MASK(SKL_DPLL0));
6171                 break;
6172         }
6173 }
6174
6175 void skl_set_preferred_cdclk_vco(struct drm_i915_private *dev_priv, int vco)
6176 {
6177         bool changed = dev_priv->skl_preferred_vco_freq != vco;
6178
6179         dev_priv->skl_preferred_vco_freq = vco;
6180
6181         if (changed)
6182                 intel_update_max_cdclk(dev_priv);
6183 }
6184
6185 static void
6186 skl_dpll0_enable(struct drm_i915_private *dev_priv, int vco)
6187 {
6188         int min_cdclk = skl_calc_cdclk(0, vco);
6189         u32 val;
6190
6191         WARN_ON(vco != 8100000 && vco != 8640000);
6192
6193         /* select the minimum CDCLK before enabling DPLL 0 */
6194         val = CDCLK_FREQ_337_308 | skl_cdclk_decimal(min_cdclk);
6195         I915_WRITE(CDCLK_CTL, val);
6196         POSTING_READ(CDCLK_CTL);
6197
6198         /*
6199          * We always enable DPLL0 with the lowest link rate possible, but still
6200          * taking into account the VCO required to operate the eDP panel at the
6201          * desired frequency. The usual DP link rates operate with a VCO of
6202          * 8100 while the eDP 1.4 alternate link rates need a VCO of 8640.
6203          * The modeset code is responsible for the selection of the exact link
6204          * rate later on, with the constraint of choosing a frequency that
6205          * works with vco.
6206          */
6207         val = I915_READ(DPLL_CTRL1);
6208
6209         val &= ~(DPLL_CTRL1_HDMI_MODE(SKL_DPLL0) | DPLL_CTRL1_SSC(SKL_DPLL0) |
6210                  DPLL_CTRL1_LINK_RATE_MASK(SKL_DPLL0));
6211         val |= DPLL_CTRL1_OVERRIDE(SKL_DPLL0);
6212         if (vco == 8640000)
6213                 val |= DPLL_CTRL1_LINK_RATE(DPLL_CTRL1_LINK_RATE_1080,
6214                                             SKL_DPLL0);
6215         else
6216                 val |= DPLL_CTRL1_LINK_RATE(DPLL_CTRL1_LINK_RATE_810,
6217                                             SKL_DPLL0);
6218
6219         I915_WRITE(DPLL_CTRL1, val);
6220         POSTING_READ(DPLL_CTRL1);
6221
6222         I915_WRITE(LCPLL1_CTL, I915_READ(LCPLL1_CTL) | LCPLL_PLL_ENABLE);
6223
6224         if (intel_wait_for_register(dev_priv,
6225                                     LCPLL1_CTL, LCPLL_PLL_LOCK, LCPLL_PLL_LOCK,
6226                                     5))
6227                 DRM_ERROR("DPLL0 not locked\n");
6228
6229         dev_priv->cdclk_pll.vco = vco;
6230
6231         /* We'll want to keep using the current vco from now on. */
6232         skl_set_preferred_cdclk_vco(dev_priv, vco);
6233 }
6234
6235 static void
6236 skl_dpll0_disable(struct drm_i915_private *dev_priv)
6237 {
6238         I915_WRITE(LCPLL1_CTL, I915_READ(LCPLL1_CTL) & ~LCPLL_PLL_ENABLE);
6239         if (intel_wait_for_register(dev_priv,
6240                                    LCPLL1_CTL, LCPLL_PLL_LOCK, 0,
6241                                    1))
6242                 DRM_ERROR("Couldn't disable DPLL0\n");
6243
6244         dev_priv->cdclk_pll.vco = 0;
6245 }
6246
6247 static void skl_set_cdclk(struct drm_i915_private *dev_priv, int cdclk, int vco)
6248 {
6249         u32 freq_select, pcu_ack;
6250         int ret;
6251
6252         WARN_ON((cdclk == 24000) != (vco == 0));
6253
6254         DRM_DEBUG_DRIVER("Changing CDCLK to %d kHz (VCO %d kHz)\n", cdclk, vco);
6255
6256         mutex_lock(&dev_priv->rps.hw_lock);
6257         ret = skl_pcode_request(dev_priv, SKL_PCODE_CDCLK_CONTROL,
6258                                 SKL_CDCLK_PREPARE_FOR_CHANGE,
6259                                 SKL_CDCLK_READY_FOR_CHANGE,
6260                                 SKL_CDCLK_READY_FOR_CHANGE, 3);
6261         mutex_unlock(&dev_priv->rps.hw_lock);
6262         if (ret) {
6263                 DRM_ERROR("Failed to inform PCU about cdclk change (%d)\n",
6264                           ret);
6265                 return;
6266         }
6267
6268         /* set CDCLK_CTL */
6269         switch (cdclk) {
6270         case 450000:
6271         case 432000:
6272                 freq_select = CDCLK_FREQ_450_432;
6273                 pcu_ack = 1;
6274                 break;
6275         case 540000:
6276                 freq_select = CDCLK_FREQ_540;
6277                 pcu_ack = 2;
6278                 break;
6279         case 308571:
6280         case 337500:
6281         default:
6282                 freq_select = CDCLK_FREQ_337_308;
6283                 pcu_ack = 0;
6284                 break;
6285         case 617143:
6286         case 675000:
6287                 freq_select = CDCLK_FREQ_675_617;
6288                 pcu_ack = 3;
6289                 break;
6290         }
6291
6292         if (dev_priv->cdclk_pll.vco != 0 &&
6293             dev_priv->cdclk_pll.vco != vco)
6294                 skl_dpll0_disable(dev_priv);
6295
6296         if (dev_priv->cdclk_pll.vco != vco)
6297                 skl_dpll0_enable(dev_priv, vco);
6298
6299         I915_WRITE(CDCLK_CTL, freq_select | skl_cdclk_decimal(cdclk));
6300         POSTING_READ(CDCLK_CTL);
6301
6302         /* inform PCU of the change */
6303         mutex_lock(&dev_priv->rps.hw_lock);
6304         sandybridge_pcode_write(dev_priv, SKL_PCODE_CDCLK_CONTROL, pcu_ack);
6305         mutex_unlock(&dev_priv->rps.hw_lock);
6306
6307         intel_update_cdclk(dev_priv);
6308 }
6309
6310 static void skl_sanitize_cdclk(struct drm_i915_private *dev_priv);
6311
6312 void skl_uninit_cdclk(struct drm_i915_private *dev_priv)
6313 {
6314         skl_set_cdclk(dev_priv, dev_priv->cdclk_pll.ref, 0);
6315 }
6316
6317 void skl_init_cdclk(struct drm_i915_private *dev_priv)
6318 {
6319         int cdclk, vco;
6320
6321         skl_sanitize_cdclk(dev_priv);
6322
6323         if (dev_priv->cdclk_freq != 0 && dev_priv->cdclk_pll.vco != 0) {
6324                 /*
6325                  * Use the current vco as our initial
6326                  * guess as to what the preferred vco is.
6327                  */
6328                 if (dev_priv->skl_preferred_vco_freq == 0)
6329                         skl_set_preferred_cdclk_vco(dev_priv,
6330                                                     dev_priv->cdclk_pll.vco);
6331                 return;
6332         }
6333
6334         vco = dev_priv->skl_preferred_vco_freq;
6335         if (vco == 0)
6336                 vco = 8100000;
6337         cdclk = skl_calc_cdclk(0, vco);
6338
6339         skl_set_cdclk(dev_priv, cdclk, vco);
6340 }
6341
6342 static void skl_sanitize_cdclk(struct drm_i915_private *dev_priv)
6343 {
6344         uint32_t cdctl, expected;
6345
6346         /*
6347          * check if the pre-os intialized the display
6348          * There is SWF18 scratchpad register defined which is set by the
6349          * pre-os which can be used by the OS drivers to check the status
6350          */
6351         if ((I915_READ(SWF_ILK(0x18)) & 0x00FFFFFF) == 0)
6352                 goto sanitize;
6353
6354         intel_update_cdclk(dev_priv);
6355         /* Is PLL enabled and locked ? */
6356         if (dev_priv->cdclk_pll.vco == 0 ||
6357             dev_priv->cdclk_freq == dev_priv->cdclk_pll.ref)
6358                 goto sanitize;
6359
6360         /* DPLL okay; verify the cdclock
6361          *
6362          * Noticed in some instances that the freq selection is correct but
6363          * decimal part is programmed wrong from BIOS where pre-os does not
6364          * enable display. Verify the same as well.
6365          */
6366         cdctl = I915_READ(CDCLK_CTL);
6367         expected = (cdctl & CDCLK_FREQ_SEL_MASK) |
6368                 skl_cdclk_decimal(dev_priv->cdclk_freq);
6369         if (cdctl == expected)
6370                 /* All well; nothing to sanitize */
6371                 return;
6372
6373 sanitize:
6374         DRM_DEBUG_KMS("Sanitizing cdclk programmed by pre-os\n");
6375
6376         /* force cdclk programming */
6377         dev_priv->cdclk_freq = 0;
6378         /* force full PLL disable + enable */
6379         dev_priv->cdclk_pll.vco = -1;
6380 }
6381
6382 /* Adjust CDclk dividers to allow high res or save power if possible */
6383 static void valleyview_set_cdclk(struct drm_device *dev, int cdclk)
6384 {
6385         struct drm_i915_private *dev_priv = to_i915(dev);
6386         u32 val, cmd;
6387
6388         WARN_ON(dev_priv->display.get_display_clock_speed(dev_priv)
6389                                         != dev_priv->cdclk_freq);
6390
6391         if (cdclk >= 320000) /* jump to highest voltage for 400MHz too */
6392                 cmd = 2;
6393         else if (cdclk == 266667)
6394                 cmd = 1;
6395         else
6396                 cmd = 0;
6397
6398         mutex_lock(&dev_priv->rps.hw_lock);
6399         val = vlv_punit_read(dev_priv, PUNIT_REG_DSPFREQ);
6400         val &= ~DSPFREQGUAR_MASK;
6401         val |= (cmd << DSPFREQGUAR_SHIFT);
6402         vlv_punit_write(dev_priv, PUNIT_REG_DSPFREQ, val);
6403         if (wait_for((vlv_punit_read(dev_priv, PUNIT_REG_DSPFREQ) &
6404                       DSPFREQSTAT_MASK) == (cmd << DSPFREQSTAT_SHIFT),
6405                      50)) {
6406                 DRM_ERROR("timed out waiting for CDclk change\n");
6407         }
6408         mutex_unlock(&dev_priv->rps.hw_lock);
6409
6410         mutex_lock(&dev_priv->sb_lock);
6411
6412         if (cdclk == 400000) {
6413                 u32 divider;
6414
6415                 divider = DIV_ROUND_CLOSEST(dev_priv->hpll_freq << 1, cdclk) - 1;
6416
6417                 /* adjust cdclk divider */
6418                 val = vlv_cck_read(dev_priv, CCK_DISPLAY_CLOCK_CONTROL);
6419                 val &= ~CCK_FREQUENCY_VALUES;
6420                 val |= divider;
6421                 vlv_cck_write(dev_priv, CCK_DISPLAY_CLOCK_CONTROL, val);
6422
6423                 if (wait_for((vlv_cck_read(dev_priv, CCK_DISPLAY_CLOCK_CONTROL) &
6424                               CCK_FREQUENCY_STATUS) == (divider << CCK_FREQUENCY_STATUS_SHIFT),
6425                              50))
6426                         DRM_ERROR("timed out waiting for CDclk change\n");
6427         }
6428
6429         /* adjust self-refresh exit latency value */
6430         val = vlv_bunit_read(dev_priv, BUNIT_REG_BISOC);
6431         val &= ~0x7f;
6432
6433         /*
6434          * For high bandwidth configs, we set a higher latency in the bunit
6435          * so that the core display fetch happens in time to avoid underruns.
6436          */
6437         if (cdclk == 400000)
6438                 val |= 4500 / 250; /* 4.5 usec */
6439         else
6440                 val |= 3000 / 250; /* 3.0 usec */
6441         vlv_bunit_write(dev_priv, BUNIT_REG_BISOC, val);
6442
6443         mutex_unlock(&dev_priv->sb_lock);
6444
6445         intel_update_cdclk(dev_priv);
6446 }
6447
6448 static void cherryview_set_cdclk(struct drm_device *dev, int cdclk)
6449 {
6450         struct drm_i915_private *dev_priv = to_i915(dev);
6451         u32 val, cmd;
6452
6453         WARN_ON(dev_priv->display.get_display_clock_speed(dev_priv)
6454                                                 != dev_priv->cdclk_freq);
6455
6456         switch (cdclk) {
6457         case 333333:
6458         case 320000:
6459         case 266667:
6460         case 200000:
6461                 break;
6462         default:
6463                 MISSING_CASE(cdclk);
6464                 return;
6465         }
6466
6467         /*
6468          * Specs are full of misinformation, but testing on actual
6469          * hardware has shown that we just need to write the desired
6470          * CCK divider into the Punit register.
6471          */
6472         cmd = DIV_ROUND_CLOSEST(dev_priv->hpll_freq << 1, cdclk) - 1;
6473
6474         mutex_lock(&dev_priv->rps.hw_lock);
6475         val = vlv_punit_read(dev_priv, PUNIT_REG_DSPFREQ);
6476         val &= ~DSPFREQGUAR_MASK_CHV;
6477         val |= (cmd << DSPFREQGUAR_SHIFT_CHV);
6478         vlv_punit_write(dev_priv, PUNIT_REG_DSPFREQ, val);
6479         if (wait_for((vlv_punit_read(dev_priv, PUNIT_REG_DSPFREQ) &
6480                       DSPFREQSTAT_MASK_CHV) == (cmd << DSPFREQSTAT_SHIFT_CHV),
6481                      50)) {
6482                 DRM_ERROR("timed out waiting for CDclk change\n");
6483         }
6484         mutex_unlock(&dev_priv->rps.hw_lock);
6485
6486         intel_update_cdclk(dev_priv);
6487 }
6488
6489 static int valleyview_calc_cdclk(struct drm_i915_private *dev_priv,
6490                                  int max_pixclk)
6491 {
6492         int freq_320 = (dev_priv->hpll_freq <<  1) % 320000 != 0 ? 333333 : 320000;
6493         int limit = IS_CHERRYVIEW(dev_priv) ? 95 : 90;
6494
6495         /*
6496          * Really only a few cases to deal with, as only 4 CDclks are supported:
6497          *   200MHz
6498          *   267MHz
6499          *   320/333MHz (depends on HPLL freq)
6500          *   400MHz (VLV only)
6501          * So we check to see whether we're above 90% (VLV) or 95% (CHV)
6502          * of the lower bin and adjust if needed.
6503          *
6504          * We seem to get an unstable or solid color picture at 200MHz.
6505          * Not sure what's wrong. For now use 200MHz only when all pipes
6506          * are off.
6507          */
6508         if (!IS_CHERRYVIEW(dev_priv) &&
6509             max_pixclk > freq_320*limit/100)
6510                 return 400000;
6511         else if (max_pixclk > 266667*limit/100)
6512                 return freq_320;
6513         else if (max_pixclk > 0)
6514                 return 266667;
6515         else
6516                 return 200000;
6517 }
6518
6519 static int bxt_calc_cdclk(int max_pixclk)
6520 {
6521         if (max_pixclk > 576000)
6522                 return 624000;
6523         else if (max_pixclk > 384000)
6524                 return 576000;
6525         else if (max_pixclk > 288000)
6526                 return 384000;
6527         else if (max_pixclk > 144000)
6528                 return 288000;
6529         else
6530                 return 144000;
6531 }
6532
6533 /* Compute the max pixel clock for new configuration. */
6534 static int intel_mode_max_pixclk(struct drm_device *dev,
6535                                  struct drm_atomic_state *state)
6536 {
6537         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
6538         struct drm_i915_private *dev_priv = to_i915(dev);
6539         struct drm_crtc *crtc;
6540         struct drm_crtc_state *crtc_state;
6541         unsigned max_pixclk = 0, i;
6542         enum pipe pipe;
6543
6544         memcpy(intel_state->min_pixclk, dev_priv->min_pixclk,
6545                sizeof(intel_state->min_pixclk));
6546
6547         for_each_crtc_in_state(state, crtc, crtc_state, i) {
6548                 int pixclk = 0;
6549
6550                 if (crtc_state->enable)
6551                         pixclk = crtc_state->adjusted_mode.crtc_clock;
6552
6553                 intel_state->min_pixclk[i] = pixclk;
6554         }
6555
6556         for_each_pipe(dev_priv, pipe)
6557                 max_pixclk = max(intel_state->min_pixclk[pipe], max_pixclk);
6558
6559         return max_pixclk;
6560 }
6561
6562 static int valleyview_modeset_calc_cdclk(struct drm_atomic_state *state)
6563 {
6564         struct drm_device *dev = state->dev;
6565         struct drm_i915_private *dev_priv = to_i915(dev);
6566         int max_pixclk = intel_mode_max_pixclk(dev, state);
6567         struct intel_atomic_state *intel_state =
6568                 to_intel_atomic_state(state);
6569
6570         intel_state->cdclk = intel_state->dev_cdclk =
6571                 valleyview_calc_cdclk(dev_priv, max_pixclk);
6572
6573         if (!intel_state->active_crtcs)
6574                 intel_state->dev_cdclk = valleyview_calc_cdclk(dev_priv, 0);
6575
6576         return 0;
6577 }
6578
6579 static int bxt_modeset_calc_cdclk(struct drm_atomic_state *state)
6580 {
6581         int max_pixclk = ilk_max_pixel_rate(state);
6582         struct intel_atomic_state *intel_state =
6583                 to_intel_atomic_state(state);
6584
6585         intel_state->cdclk = intel_state->dev_cdclk =
6586                 bxt_calc_cdclk(max_pixclk);
6587
6588         if (!intel_state->active_crtcs)
6589                 intel_state->dev_cdclk = bxt_calc_cdclk(0);
6590
6591         return 0;
6592 }
6593
6594 static void vlv_program_pfi_credits(struct drm_i915_private *dev_priv)
6595 {
6596         unsigned int credits, default_credits;
6597
6598         if (IS_CHERRYVIEW(dev_priv))
6599                 default_credits = PFI_CREDIT(12);
6600         else
6601                 default_credits = PFI_CREDIT(8);
6602
6603         if (dev_priv->cdclk_freq >= dev_priv->czclk_freq) {
6604                 /* CHV suggested value is 31 or 63 */
6605                 if (IS_CHERRYVIEW(dev_priv))
6606                         credits = PFI_CREDIT_63;
6607                 else
6608                         credits = PFI_CREDIT(15);
6609         } else {
6610                 credits = default_credits;
6611         }
6612
6613         /*
6614          * WA - write default credits before re-programming
6615          * FIXME: should we also set the resend bit here?
6616          */
6617         I915_WRITE(GCI_CONTROL, VGA_FAST_MODE_DISABLE |
6618                    default_credits);
6619
6620         I915_WRITE(GCI_CONTROL, VGA_FAST_MODE_DISABLE |
6621                    credits | PFI_CREDIT_RESEND);
6622
6623         /*
6624          * FIXME is this guaranteed to clear
6625          * immediately or should we poll for it?
6626          */
6627         WARN_ON(I915_READ(GCI_CONTROL) & PFI_CREDIT_RESEND);
6628 }
6629
6630 static void valleyview_modeset_commit_cdclk(struct drm_atomic_state *old_state)
6631 {
6632         struct drm_device *dev = old_state->dev;
6633         struct drm_i915_private *dev_priv = to_i915(dev);
6634         struct intel_atomic_state *old_intel_state =
6635                 to_intel_atomic_state(old_state);
6636         unsigned req_cdclk = old_intel_state->dev_cdclk;
6637
6638         /*
6639          * FIXME: We can end up here with all power domains off, yet
6640          * with a CDCLK frequency other than the minimum. To account
6641          * for this take the PIPE-A power domain, which covers the HW
6642          * blocks needed for the following programming. This can be
6643          * removed once it's guaranteed that we get here either with
6644          * the minimum CDCLK set, or the required power domains
6645          * enabled.
6646          */
6647         intel_display_power_get(dev_priv, POWER_DOMAIN_PIPE_A);
6648
6649         if (IS_CHERRYVIEW(dev_priv))
6650                 cherryview_set_cdclk(dev, req_cdclk);
6651         else
6652                 valleyview_set_cdclk(dev, req_cdclk);
6653
6654         vlv_program_pfi_credits(dev_priv);
6655
6656         intel_display_power_put(dev_priv, POWER_DOMAIN_PIPE_A);
6657 }
6658
6659 static void valleyview_crtc_enable(struct intel_crtc_state *pipe_config,
6660                                    struct drm_atomic_state *old_state)
6661 {
6662         struct drm_crtc *crtc = pipe_config->base.crtc;
6663         struct drm_device *dev = crtc->dev;
6664         struct drm_i915_private *dev_priv = to_i915(dev);
6665         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
6666         int pipe = intel_crtc->pipe;
6667
6668         if (WARN_ON(intel_crtc->active))
6669                 return;
6670
6671         if (intel_crtc_has_dp_encoder(intel_crtc->config))
6672                 intel_dp_set_m_n(intel_crtc, M1_N1);
6673
6674         intel_set_pipe_timings(intel_crtc);
6675         intel_set_pipe_src_size(intel_crtc);
6676
6677         if (IS_CHERRYVIEW(dev_priv) && pipe == PIPE_B) {
6678                 struct drm_i915_private *dev_priv = to_i915(dev);
6679
6680                 I915_WRITE(CHV_BLEND(pipe), CHV_BLEND_LEGACY);
6681                 I915_WRITE(CHV_CANVAS(pipe), 0);
6682         }
6683
6684         i9xx_set_pipeconf(intel_crtc);
6685
6686         intel_crtc->active = true;
6687
6688         intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
6689
6690         intel_encoders_pre_pll_enable(crtc, pipe_config, old_state);
6691
6692         if (IS_CHERRYVIEW(dev_priv)) {
6693                 chv_prepare_pll(intel_crtc, intel_crtc->config);
6694                 chv_enable_pll(intel_crtc, intel_crtc->config);
6695         } else {
6696                 vlv_prepare_pll(intel_crtc, intel_crtc->config);
6697                 vlv_enable_pll(intel_crtc, intel_crtc->config);
6698         }
6699
6700         intel_encoders_pre_enable(crtc, pipe_config, old_state);
6701
6702         i9xx_pfit_enable(intel_crtc);
6703
6704         intel_color_load_luts(&pipe_config->base);
6705
6706         intel_update_watermarks(intel_crtc);
6707         intel_enable_pipe(intel_crtc);
6708
6709         assert_vblank_disabled(crtc);
6710         drm_crtc_vblank_on(crtc);
6711
6712         intel_encoders_enable(crtc, pipe_config, old_state);
6713 }
6714
6715 static void i9xx_set_pll_dividers(struct intel_crtc *crtc)
6716 {
6717         struct drm_device *dev = crtc->base.dev;
6718         struct drm_i915_private *dev_priv = to_i915(dev);
6719
6720         I915_WRITE(FP0(crtc->pipe), crtc->config->dpll_hw_state.fp0);
6721         I915_WRITE(FP1(crtc->pipe), crtc->config->dpll_hw_state.fp1);
6722 }
6723
6724 static void i9xx_crtc_enable(struct intel_crtc_state *pipe_config,
6725                              struct drm_atomic_state *old_state)
6726 {
6727         struct drm_crtc *crtc = pipe_config->base.crtc;
6728         struct drm_device *dev = crtc->dev;
6729         struct drm_i915_private *dev_priv = to_i915(dev);
6730         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
6731         enum pipe pipe = intel_crtc->pipe;
6732
6733         if (WARN_ON(intel_crtc->active))
6734                 return;
6735
6736         i9xx_set_pll_dividers(intel_crtc);
6737
6738         if (intel_crtc_has_dp_encoder(intel_crtc->config))
6739                 intel_dp_set_m_n(intel_crtc, M1_N1);
6740
6741         intel_set_pipe_timings(intel_crtc);
6742         intel_set_pipe_src_size(intel_crtc);
6743
6744         i9xx_set_pipeconf(intel_crtc);
6745
6746         intel_crtc->active = true;
6747
6748         if (!IS_GEN2(dev_priv))
6749                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
6750
6751         intel_encoders_pre_enable(crtc, pipe_config, old_state);
6752
6753         i9xx_enable_pll(intel_crtc);
6754
6755         i9xx_pfit_enable(intel_crtc);
6756
6757         intel_color_load_luts(&pipe_config->base);
6758
6759         intel_update_watermarks(intel_crtc);
6760         intel_enable_pipe(intel_crtc);
6761
6762         assert_vblank_disabled(crtc);
6763         drm_crtc_vblank_on(crtc);
6764
6765         intel_encoders_enable(crtc, pipe_config, old_state);
6766 }
6767
6768 static void i9xx_pfit_disable(struct intel_crtc *crtc)
6769 {
6770         struct drm_device *dev = crtc->base.dev;
6771         struct drm_i915_private *dev_priv = to_i915(dev);
6772
6773         if (!crtc->config->gmch_pfit.control)
6774                 return;
6775
6776         assert_pipe_disabled(dev_priv, crtc->pipe);
6777
6778         DRM_DEBUG_DRIVER("disabling pfit, current: 0x%08x\n",
6779                          I915_READ(PFIT_CONTROL));
6780         I915_WRITE(PFIT_CONTROL, 0);
6781 }
6782
6783 static void i9xx_crtc_disable(struct intel_crtc_state *old_crtc_state,
6784                               struct drm_atomic_state *old_state)
6785 {
6786         struct drm_crtc *crtc = old_crtc_state->base.crtc;
6787         struct drm_device *dev = crtc->dev;
6788         struct drm_i915_private *dev_priv = to_i915(dev);
6789         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
6790         int pipe = intel_crtc->pipe;
6791
6792         /*
6793          * On gen2 planes are double buffered but the pipe isn't, so we must
6794          * wait for planes to fully turn off before disabling the pipe.
6795          */
6796         if (IS_GEN2(dev_priv))
6797                 intel_wait_for_vblank(dev_priv, pipe);
6798
6799         intel_encoders_disable(crtc, old_crtc_state, old_state);
6800
6801         drm_crtc_vblank_off(crtc);
6802         assert_vblank_disabled(crtc);
6803
6804         intel_disable_pipe(intel_crtc);
6805
6806         i9xx_pfit_disable(intel_crtc);
6807
6808         intel_encoders_post_disable(crtc, old_crtc_state, old_state);
6809
6810         if (!intel_crtc_has_type(intel_crtc->config, INTEL_OUTPUT_DSI)) {
6811                 if (IS_CHERRYVIEW(dev_priv))
6812                         chv_disable_pll(dev_priv, pipe);
6813                 else if (IS_VALLEYVIEW(dev_priv))
6814                         vlv_disable_pll(dev_priv, pipe);
6815                 else
6816                         i9xx_disable_pll(intel_crtc);
6817         }
6818
6819         intel_encoders_post_pll_disable(crtc, old_crtc_state, old_state);
6820
6821         if (!IS_GEN2(dev_priv))
6822                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
6823 }
6824
6825 static void intel_crtc_disable_noatomic(struct drm_crtc *crtc)
6826 {
6827         struct intel_encoder *encoder;
6828         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
6829         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
6830         enum intel_display_power_domain domain;
6831         unsigned long domains;
6832         struct drm_atomic_state *state;
6833         struct intel_crtc_state *crtc_state;
6834         int ret;
6835
6836         if (!intel_crtc->active)
6837                 return;
6838
6839         if (to_intel_plane_state(crtc->primary->state)->base.visible) {
6840                 WARN_ON(intel_crtc->flip_work);
6841
6842                 intel_pre_disable_primary_noatomic(crtc);
6843
6844                 intel_crtc_disable_planes(crtc, 1 << drm_plane_index(crtc->primary));
6845                 to_intel_plane_state(crtc->primary->state)->base.visible = false;
6846         }
6847
6848         state = drm_atomic_state_alloc(crtc->dev);
6849         state->acquire_ctx = crtc->dev->mode_config.acquire_ctx;
6850
6851         /* Everything's already locked, -EDEADLK can't happen. */
6852         crtc_state = intel_atomic_get_crtc_state(state, intel_crtc);
6853         ret = drm_atomic_add_affected_connectors(state, crtc);
6854
6855         WARN_ON(IS_ERR(crtc_state) || ret);
6856
6857         dev_priv->display.crtc_disable(crtc_state, state);
6858
6859         drm_atomic_state_put(state);
6860
6861         DRM_DEBUG_KMS("[CRTC:%d:%s] hw state adjusted, was enabled, now disabled\n",
6862                       crtc->base.id, crtc->name);
6863
6864         WARN_ON(drm_atomic_set_mode_for_crtc(crtc->state, NULL) < 0);
6865         crtc->state->active = false;
6866         intel_crtc->active = false;
6867         crtc->enabled = false;
6868         crtc->state->connector_mask = 0;
6869         crtc->state->encoder_mask = 0;
6870
6871         for_each_encoder_on_crtc(crtc->dev, crtc, encoder)
6872                 encoder->base.crtc = NULL;
6873
6874         intel_fbc_disable(intel_crtc);
6875         intel_update_watermarks(intel_crtc);
6876         intel_disable_shared_dpll(intel_crtc);
6877
6878         domains = intel_crtc->enabled_power_domains;
6879         for_each_power_domain(domain, domains)
6880                 intel_display_power_put(dev_priv, domain);
6881         intel_crtc->enabled_power_domains = 0;
6882
6883         dev_priv->active_crtcs &= ~(1 << intel_crtc->pipe);
6884         dev_priv->min_pixclk[intel_crtc->pipe] = 0;
6885 }
6886
6887 /*
6888  * turn all crtc's off, but do not adjust state
6889  * This has to be paired with a call to intel_modeset_setup_hw_state.
6890  */
6891 int intel_display_suspend(struct drm_device *dev)
6892 {
6893         struct drm_i915_private *dev_priv = to_i915(dev);
6894         struct drm_atomic_state *state;
6895         int ret;
6896
6897         state = drm_atomic_helper_suspend(dev);
6898         ret = PTR_ERR_OR_ZERO(state);
6899         if (ret)
6900                 DRM_ERROR("Suspending crtc's failed with %i\n", ret);
6901         else
6902                 dev_priv->modeset_restore_state = state;
6903         return ret;
6904 }
6905
6906 void intel_encoder_destroy(struct drm_encoder *encoder)
6907 {
6908         struct intel_encoder *intel_encoder = to_intel_encoder(encoder);
6909
6910         drm_encoder_cleanup(encoder);
6911         kfree(intel_encoder);
6912 }
6913
6914 /* Cross check the actual hw state with our own modeset state tracking (and it's
6915  * internal consistency). */
6916 static void intel_connector_verify_state(struct intel_connector *connector)
6917 {
6918         struct drm_crtc *crtc = connector->base.state->crtc;
6919
6920         DRM_DEBUG_KMS("[CONNECTOR:%d:%s]\n",
6921                       connector->base.base.id,
6922                       connector->base.name);
6923
6924         if (connector->get_hw_state(connector)) {
6925                 struct intel_encoder *encoder = connector->encoder;
6926                 struct drm_connector_state *conn_state = connector->base.state;
6927
6928                 I915_STATE_WARN(!crtc,
6929                          "connector enabled without attached crtc\n");
6930
6931                 if (!crtc)
6932                         return;
6933
6934                 I915_STATE_WARN(!crtc->state->active,
6935                       "connector is active, but attached crtc isn't\n");
6936
6937                 if (!encoder || encoder->type == INTEL_OUTPUT_DP_MST)
6938                         return;
6939
6940                 I915_STATE_WARN(conn_state->best_encoder != &encoder->base,
6941                         "atomic encoder doesn't match attached encoder\n");
6942
6943                 I915_STATE_WARN(conn_state->crtc != encoder->base.crtc,
6944                         "attached encoder crtc differs from connector crtc\n");
6945         } else {
6946                 I915_STATE_WARN(crtc && crtc->state->active,
6947                         "attached crtc is active, but connector isn't\n");
6948                 I915_STATE_WARN(!crtc && connector->base.state->best_encoder,
6949                         "best encoder set without crtc!\n");
6950         }
6951 }
6952
6953 int intel_connector_init(struct intel_connector *connector)
6954 {
6955         drm_atomic_helper_connector_reset(&connector->base);
6956
6957         if (!connector->base.state)
6958                 return -ENOMEM;
6959
6960         return 0;
6961 }
6962
6963 struct intel_connector *intel_connector_alloc(void)
6964 {
6965         struct intel_connector *connector;
6966
6967         connector = kzalloc(sizeof *connector, GFP_KERNEL);
6968         if (!connector)
6969                 return NULL;
6970
6971         if (intel_connector_init(connector) < 0) {
6972                 kfree(connector);
6973                 return NULL;
6974         }
6975
6976         return connector;
6977 }
6978
6979 /* Simple connector->get_hw_state implementation for encoders that support only
6980  * one connector and no cloning and hence the encoder state determines the state
6981  * of the connector. */
6982 bool intel_connector_get_hw_state(struct intel_connector *connector)
6983 {
6984         enum pipe pipe = 0;
6985         struct intel_encoder *encoder = connector->encoder;
6986
6987         return encoder->get_hw_state(encoder, &pipe);
6988 }
6989
6990 static int pipe_required_fdi_lanes(struct intel_crtc_state *crtc_state)
6991 {
6992         if (crtc_state->base.enable && crtc_state->has_pch_encoder)
6993                 return crtc_state->fdi_lanes;
6994
6995         return 0;
6996 }
6997
6998 static int ironlake_check_fdi_lanes(struct drm_device *dev, enum pipe pipe,
6999                                      struct intel_crtc_state *pipe_config)
7000 {
7001         struct drm_i915_private *dev_priv = to_i915(dev);
7002         struct drm_atomic_state *state = pipe_config->base.state;
7003         struct intel_crtc *other_crtc;
7004         struct intel_crtc_state *other_crtc_state;
7005
7006         DRM_DEBUG_KMS("checking fdi config on pipe %c, lanes %i\n",
7007                       pipe_name(pipe), pipe_config->fdi_lanes);
7008         if (pipe_config->fdi_lanes > 4) {
7009                 DRM_DEBUG_KMS("invalid fdi lane config on pipe %c: %i lanes\n",
7010                               pipe_name(pipe), pipe_config->fdi_lanes);
7011                 return -EINVAL;
7012         }
7013
7014         if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv)) {
7015                 if (pipe_config->fdi_lanes > 2) {
7016                         DRM_DEBUG_KMS("only 2 lanes on haswell, required: %i lanes\n",
7017                                       pipe_config->fdi_lanes);
7018                         return -EINVAL;
7019                 } else {
7020                         return 0;
7021                 }
7022         }
7023
7024         if (INTEL_INFO(dev_priv)->num_pipes == 2)
7025                 return 0;
7026
7027         /* Ivybridge 3 pipe is really complicated */
7028         switch (pipe) {
7029         case PIPE_A:
7030                 return 0;
7031         case PIPE_B:
7032                 if (pipe_config->fdi_lanes <= 2)
7033                         return 0;
7034
7035                 other_crtc = intel_get_crtc_for_pipe(dev_priv, PIPE_C);
7036                 other_crtc_state =
7037                         intel_atomic_get_crtc_state(state, other_crtc);
7038                 if (IS_ERR(other_crtc_state))
7039                         return PTR_ERR(other_crtc_state);
7040
7041                 if (pipe_required_fdi_lanes(other_crtc_state) > 0) {
7042                         DRM_DEBUG_KMS("invalid shared fdi lane config on pipe %c: %i lanes\n",
7043                                       pipe_name(pipe), pipe_config->fdi_lanes);
7044                         return -EINVAL;
7045                 }
7046                 return 0;
7047         case PIPE_C:
7048                 if (pipe_config->fdi_lanes > 2) {
7049                         DRM_DEBUG_KMS("only 2 lanes on pipe %c: required %i lanes\n",
7050                                       pipe_name(pipe), pipe_config->fdi_lanes);
7051                         return -EINVAL;
7052                 }
7053
7054                 other_crtc = intel_get_crtc_for_pipe(dev_priv, PIPE_B);
7055                 other_crtc_state =
7056                         intel_atomic_get_crtc_state(state, other_crtc);
7057                 if (IS_ERR(other_crtc_state))
7058                         return PTR_ERR(other_crtc_state);
7059
7060                 if (pipe_required_fdi_lanes(other_crtc_state) > 2) {
7061                         DRM_DEBUG_KMS("fdi link B uses too many lanes to enable link C\n");
7062                         return -EINVAL;
7063                 }
7064                 return 0;
7065         default:
7066                 BUG();
7067         }
7068 }
7069
7070 #define RETRY 1
7071 static int ironlake_fdi_compute_config(struct intel_crtc *intel_crtc,
7072                                        struct intel_crtc_state *pipe_config)
7073 {
7074         struct drm_device *dev = intel_crtc->base.dev;
7075         const struct drm_display_mode *adjusted_mode = &pipe_config->base.adjusted_mode;
7076         int lane, link_bw, fdi_dotclock, ret;
7077         bool needs_recompute = false;
7078
7079 retry:
7080         /* FDI is a binary signal running at ~2.7GHz, encoding
7081          * each output octet as 10 bits. The actual frequency
7082          * is stored as a divider into a 100MHz clock, and the
7083          * mode pixel clock is stored in units of 1KHz.
7084          * Hence the bw of each lane in terms of the mode signal
7085          * is:
7086          */
7087         link_bw = intel_fdi_link_freq(to_i915(dev), pipe_config);
7088
7089         fdi_dotclock = adjusted_mode->crtc_clock;
7090
7091         lane = ironlake_get_lanes_required(fdi_dotclock, link_bw,
7092                                            pipe_config->pipe_bpp);
7093
7094         pipe_config->fdi_lanes = lane;
7095
7096         intel_link_compute_m_n(pipe_config->pipe_bpp, lane, fdi_dotclock,
7097                                link_bw, &pipe_config->fdi_m_n);
7098
7099         ret = ironlake_check_fdi_lanes(dev, intel_crtc->pipe, pipe_config);
7100         if (ret == -EINVAL && pipe_config->pipe_bpp > 6*3) {
7101                 pipe_config->pipe_bpp -= 2*3;
7102                 DRM_DEBUG_KMS("fdi link bw constraint, reducing pipe bpp to %i\n",
7103                               pipe_config->pipe_bpp);
7104                 needs_recompute = true;
7105                 pipe_config->bw_constrained = true;
7106
7107                 goto retry;
7108         }
7109
7110         if (needs_recompute)
7111                 return RETRY;
7112
7113         return ret;
7114 }
7115
7116 static bool pipe_config_supports_ips(struct drm_i915_private *dev_priv,
7117                                      struct intel_crtc_state *pipe_config)
7118 {
7119         if (pipe_config->pipe_bpp > 24)
7120                 return false;
7121
7122         /* HSW can handle pixel rate up to cdclk? */
7123         if (IS_HASWELL(dev_priv))
7124                 return true;
7125
7126         /*
7127          * We compare against max which means we must take
7128          * the increased cdclk requirement into account when
7129          * calculating the new cdclk.
7130          *
7131          * Should measure whether using a lower cdclk w/o IPS
7132          */
7133         return ilk_pipe_pixel_rate(pipe_config) <=
7134                 dev_priv->max_cdclk_freq * 95 / 100;
7135 }
7136
7137 static void hsw_compute_ips_config(struct intel_crtc *crtc,
7138                                    struct intel_crtc_state *pipe_config)
7139 {
7140         struct drm_device *dev = crtc->base.dev;
7141         struct drm_i915_private *dev_priv = to_i915(dev);
7142
7143         pipe_config->ips_enabled = i915.enable_ips &&
7144                 hsw_crtc_supports_ips(crtc) &&
7145                 pipe_config_supports_ips(dev_priv, pipe_config);
7146 }
7147
7148 static bool intel_crtc_supports_double_wide(const struct intel_crtc *crtc)
7149 {
7150         const struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
7151
7152         /* GDG double wide on either pipe, otherwise pipe A only */
7153         return INTEL_INFO(dev_priv)->gen < 4 &&
7154                 (crtc->pipe == PIPE_A || IS_I915G(dev_priv));
7155 }
7156
7157 static int intel_crtc_compute_config(struct intel_crtc *crtc,
7158                                      struct intel_crtc_state *pipe_config)
7159 {
7160         struct drm_device *dev = crtc->base.dev;
7161         struct drm_i915_private *dev_priv = to_i915(dev);
7162         const struct drm_display_mode *adjusted_mode = &pipe_config->base.adjusted_mode;
7163         int clock_limit = dev_priv->max_dotclk_freq;
7164
7165         if (INTEL_GEN(dev_priv) < 4) {
7166                 clock_limit = dev_priv->max_cdclk_freq * 9 / 10;
7167
7168                 /*
7169                  * Enable double wide mode when the dot clock
7170                  * is > 90% of the (display) core speed.
7171                  */
7172                 if (intel_crtc_supports_double_wide(crtc) &&
7173                     adjusted_mode->crtc_clock > clock_limit) {
7174                         clock_limit = dev_priv->max_dotclk_freq;
7175                         pipe_config->double_wide = true;
7176                 }
7177         }
7178
7179         if (adjusted_mode->crtc_clock > clock_limit) {
7180                 DRM_DEBUG_KMS("requested pixel clock (%d kHz) too high (max: %d kHz, double wide: %s)\n",
7181                               adjusted_mode->crtc_clock, clock_limit,
7182                               yesno(pipe_config->double_wide));
7183                 return -EINVAL;
7184         }
7185
7186         /*
7187          * Pipe horizontal size must be even in:
7188          * - DVO ganged mode
7189          * - LVDS dual channel mode
7190          * - Double wide pipe
7191          */
7192         if ((intel_crtc_has_type(pipe_config, INTEL_OUTPUT_LVDS) &&
7193              intel_is_dual_link_lvds(dev)) || pipe_config->double_wide)
7194                 pipe_config->pipe_src_w &= ~1;
7195
7196         /* Cantiga+ cannot handle modes with a hsync front porch of 0.
7197          * WaPruneModeWithIncorrectHsyncOffset:ctg,elk,ilk,snb,ivb,vlv,hsw.
7198          */
7199         if ((INTEL_GEN(dev_priv) > 4 || IS_G4X(dev_priv)) &&
7200                 adjusted_mode->crtc_hsync_start == adjusted_mode->crtc_hdisplay)
7201                 return -EINVAL;
7202
7203         if (HAS_IPS(dev_priv))
7204                 hsw_compute_ips_config(crtc, pipe_config);
7205
7206         if (pipe_config->has_pch_encoder)
7207                 return ironlake_fdi_compute_config(crtc, pipe_config);
7208
7209         return 0;
7210 }
7211
7212 static int skylake_get_display_clock_speed(struct drm_i915_private *dev_priv)
7213 {
7214         u32 cdctl;
7215
7216         skl_dpll0_update(dev_priv);
7217
7218         if (dev_priv->cdclk_pll.vco == 0)
7219                 return dev_priv->cdclk_pll.ref;
7220
7221         cdctl = I915_READ(CDCLK_CTL);
7222
7223         if (dev_priv->cdclk_pll.vco == 8640000) {
7224                 switch (cdctl & CDCLK_FREQ_SEL_MASK) {
7225                 case CDCLK_FREQ_450_432:
7226                         return 432000;
7227                 case CDCLK_FREQ_337_308:
7228                         return 308571;
7229                 case CDCLK_FREQ_540:
7230                         return 540000;
7231                 case CDCLK_FREQ_675_617:
7232                         return 617143;
7233                 default:
7234                         MISSING_CASE(cdctl & CDCLK_FREQ_SEL_MASK);
7235                 }
7236         } else {
7237                 switch (cdctl & CDCLK_FREQ_SEL_MASK) {
7238                 case CDCLK_FREQ_450_432:
7239                         return 450000;
7240                 case CDCLK_FREQ_337_308:
7241                         return 337500;
7242                 case CDCLK_FREQ_540:
7243                         return 540000;
7244                 case CDCLK_FREQ_675_617:
7245                         return 675000;
7246                 default:
7247                         MISSING_CASE(cdctl & CDCLK_FREQ_SEL_MASK);
7248                 }
7249         }
7250
7251         return dev_priv->cdclk_pll.ref;
7252 }
7253
7254 static void bxt_de_pll_update(struct drm_i915_private *dev_priv)
7255 {
7256         u32 val;
7257
7258         dev_priv->cdclk_pll.ref = 19200;
7259         dev_priv->cdclk_pll.vco = 0;
7260
7261         val = I915_READ(BXT_DE_PLL_ENABLE);
7262         if ((val & BXT_DE_PLL_PLL_ENABLE) == 0)
7263                 return;
7264
7265         if (WARN_ON((val & BXT_DE_PLL_LOCK) == 0))
7266                 return;
7267
7268         val = I915_READ(BXT_DE_PLL_CTL);
7269         dev_priv->cdclk_pll.vco = (val & BXT_DE_PLL_RATIO_MASK) *
7270                 dev_priv->cdclk_pll.ref;
7271 }
7272
7273 static int broxton_get_display_clock_speed(struct drm_i915_private *dev_priv)
7274 {
7275         u32 divider;
7276         int div, vco;
7277
7278         bxt_de_pll_update(dev_priv);
7279
7280         vco = dev_priv->cdclk_pll.vco;
7281         if (vco == 0)
7282                 return dev_priv->cdclk_pll.ref;
7283
7284         divider = I915_READ(CDCLK_CTL) & BXT_CDCLK_CD2X_DIV_SEL_MASK;
7285
7286         switch (divider) {
7287         case BXT_CDCLK_CD2X_DIV_SEL_1:
7288                 div = 2;
7289                 break;
7290         case BXT_CDCLK_CD2X_DIV_SEL_1_5:
7291                 div = 3;
7292                 break;
7293         case BXT_CDCLK_CD2X_DIV_SEL_2:
7294                 div = 4;
7295                 break;
7296         case BXT_CDCLK_CD2X_DIV_SEL_4:
7297                 div = 8;
7298                 break;
7299         default:
7300                 MISSING_CASE(divider);
7301                 return dev_priv->cdclk_pll.ref;
7302         }
7303
7304         return DIV_ROUND_CLOSEST(vco, div);
7305 }
7306
7307 static int broadwell_get_display_clock_speed(struct drm_i915_private *dev_priv)
7308 {
7309         uint32_t lcpll = I915_READ(LCPLL_CTL);
7310         uint32_t freq = lcpll & LCPLL_CLK_FREQ_MASK;
7311
7312         if (lcpll & LCPLL_CD_SOURCE_FCLK)
7313                 return 800000;
7314         else if (I915_READ(FUSE_STRAP) & HSW_CDCLK_LIMIT)
7315                 return 450000;
7316         else if (freq == LCPLL_CLK_FREQ_450)
7317                 return 450000;
7318         else if (freq == LCPLL_CLK_FREQ_54O_BDW)
7319                 return 540000;
7320         else if (freq == LCPLL_CLK_FREQ_337_5_BDW)
7321                 return 337500;
7322         else
7323                 return 675000;
7324 }
7325
7326 static int haswell_get_display_clock_speed(struct drm_i915_private *dev_priv)
7327 {
7328         uint32_t lcpll = I915_READ(LCPLL_CTL);
7329         uint32_t freq = lcpll & LCPLL_CLK_FREQ_MASK;
7330
7331         if (lcpll & LCPLL_CD_SOURCE_FCLK)
7332                 return 800000;
7333         else if (I915_READ(FUSE_STRAP) & HSW_CDCLK_LIMIT)
7334                 return 450000;
7335         else if (freq == LCPLL_CLK_FREQ_450)
7336                 return 450000;
7337         else if (IS_HSW_ULT(dev_priv))
7338                 return 337500;
7339         else
7340                 return 540000;
7341 }
7342
7343 static int valleyview_get_display_clock_speed(struct drm_i915_private *dev_priv)
7344 {
7345         return vlv_get_cck_clock_hpll(dev_priv, "cdclk",
7346                                       CCK_DISPLAY_CLOCK_CONTROL);
7347 }
7348
7349 static int ilk_get_display_clock_speed(struct drm_i915_private *dev_priv)
7350 {
7351         return 450000;
7352 }
7353
7354 static int i945_get_display_clock_speed(struct drm_i915_private *dev_priv)
7355 {
7356         return 400000;
7357 }
7358
7359 static int i915_get_display_clock_speed(struct drm_i915_private *dev_priv)
7360 {
7361         return 333333;
7362 }
7363
7364 static int i9xx_misc_get_display_clock_speed(struct drm_i915_private *dev_priv)
7365 {
7366         return 200000;
7367 }
7368
7369 static int pnv_get_display_clock_speed(struct drm_i915_private *dev_priv)
7370 {
7371         struct pci_dev *pdev = dev_priv->drm.pdev;
7372         u16 gcfgc = 0;
7373
7374         pci_read_config_word(pdev, GCFGC, &gcfgc);
7375
7376         switch (gcfgc & GC_DISPLAY_CLOCK_MASK) {
7377         case GC_DISPLAY_CLOCK_267_MHZ_PNV:
7378                 return 266667;
7379         case GC_DISPLAY_CLOCK_333_MHZ_PNV:
7380                 return 333333;
7381         case GC_DISPLAY_CLOCK_444_MHZ_PNV:
7382                 return 444444;
7383         case GC_DISPLAY_CLOCK_200_MHZ_PNV:
7384                 return 200000;
7385         default:
7386                 DRM_ERROR("Unknown pnv display core clock 0x%04x\n", gcfgc);
7387         case GC_DISPLAY_CLOCK_133_MHZ_PNV:
7388                 return 133333;
7389         case GC_DISPLAY_CLOCK_167_MHZ_PNV:
7390                 return 166667;
7391         }
7392 }
7393
7394 static int i915gm_get_display_clock_speed(struct drm_i915_private *dev_priv)
7395 {
7396         struct pci_dev *pdev = dev_priv->drm.pdev;
7397         u16 gcfgc = 0;
7398
7399         pci_read_config_word(pdev, GCFGC, &gcfgc);
7400
7401         if (gcfgc & GC_LOW_FREQUENCY_ENABLE)
7402                 return 133333;
7403         else {
7404                 switch (gcfgc & GC_DISPLAY_CLOCK_MASK) {
7405                 case GC_DISPLAY_CLOCK_333_MHZ:
7406                         return 333333;
7407                 default:
7408                 case GC_DISPLAY_CLOCK_190_200_MHZ:
7409                         return 190000;
7410                 }
7411         }
7412 }
7413
7414 static int i865_get_display_clock_speed(struct drm_i915_private *dev_priv)
7415 {
7416         return 266667;
7417 }
7418
7419 static int i85x_get_display_clock_speed(struct drm_i915_private *dev_priv)
7420 {
7421         struct pci_dev *pdev = dev_priv->drm.pdev;
7422         u16 hpllcc = 0;
7423
7424         /*
7425          * 852GM/852GMV only supports 133 MHz and the HPLLCC
7426          * encoding is different :(
7427          * FIXME is this the right way to detect 852GM/852GMV?
7428          */
7429         if (pdev->revision == 0x1)
7430                 return 133333;
7431
7432         pci_bus_read_config_word(pdev->bus,
7433                                  PCI_DEVFN(0, 3), HPLLCC, &hpllcc);
7434
7435         /* Assume that the hardware is in the high speed state.  This
7436          * should be the default.
7437          */
7438         switch (hpllcc & GC_CLOCK_CONTROL_MASK) {
7439         case GC_CLOCK_133_200:
7440         case GC_CLOCK_133_200_2:
7441         case GC_CLOCK_100_200:
7442                 return 200000;
7443         case GC_CLOCK_166_250:
7444                 return 250000;
7445         case GC_CLOCK_100_133:
7446                 return 133333;
7447         case GC_CLOCK_133_266:
7448         case GC_CLOCK_133_266_2:
7449         case GC_CLOCK_166_266:
7450                 return 266667;
7451         }
7452
7453         /* Shouldn't happen */
7454         return 0;
7455 }
7456
7457 static int i830_get_display_clock_speed(struct drm_i915_private *dev_priv)
7458 {
7459         return 133333;
7460 }
7461
7462 static unsigned int intel_hpll_vco(struct drm_i915_private *dev_priv)
7463 {
7464         static const unsigned int blb_vco[8] = {
7465                 [0] = 3200000,
7466                 [1] = 4000000,
7467                 [2] = 5333333,
7468                 [3] = 4800000,
7469                 [4] = 6400000,
7470         };
7471         static const unsigned int pnv_vco[8] = {
7472                 [0] = 3200000,
7473                 [1] = 4000000,
7474                 [2] = 5333333,
7475                 [3] = 4800000,
7476                 [4] = 2666667,
7477         };
7478         static const unsigned int cl_vco[8] = {
7479                 [0] = 3200000,
7480                 [1] = 4000000,
7481                 [2] = 5333333,
7482                 [3] = 6400000,
7483                 [4] = 3333333,
7484                 [5] = 3566667,
7485                 [6] = 4266667,
7486         };
7487         static const unsigned int elk_vco[8] = {
7488                 [0] = 3200000,
7489                 [1] = 4000000,
7490                 [2] = 5333333,
7491                 [3] = 4800000,
7492         };
7493         static const unsigned int ctg_vco[8] = {
7494                 [0] = 3200000,
7495                 [1] = 4000000,
7496                 [2] = 5333333,
7497                 [3] = 6400000,
7498                 [4] = 2666667,
7499                 [5] = 4266667,
7500         };
7501         const unsigned int *vco_table;
7502         unsigned int vco;
7503         uint8_t tmp = 0;
7504
7505         /* FIXME other chipsets? */
7506         if (IS_GM45(dev_priv))
7507                 vco_table = ctg_vco;
7508         else if (IS_G4X(dev_priv))
7509                 vco_table = elk_vco;
7510         else if (IS_CRESTLINE(dev_priv))
7511                 vco_table = cl_vco;
7512         else if (IS_PINEVIEW(dev_priv))
7513                 vco_table = pnv_vco;
7514         else if (IS_G33(dev_priv))
7515                 vco_table = blb_vco;
7516         else
7517                 return 0;
7518
7519         tmp = I915_READ(IS_MOBILE(dev_priv) ? HPLLVCO_MOBILE : HPLLVCO);
7520
7521         vco = vco_table[tmp & 0x7];
7522         if (vco == 0)
7523                 DRM_ERROR("Bad HPLL VCO (HPLLVCO=0x%02x)\n", tmp);
7524         else
7525                 DRM_DEBUG_KMS("HPLL VCO %u kHz\n", vco);
7526
7527         return vco;
7528 }
7529
7530 static int gm45_get_display_clock_speed(struct drm_i915_private *dev_priv)
7531 {
7532         struct pci_dev *pdev = dev_priv->drm.pdev;
7533         unsigned int cdclk_sel, vco = intel_hpll_vco(dev_priv);
7534         uint16_t tmp = 0;
7535
7536         pci_read_config_word(pdev, GCFGC, &tmp);
7537
7538         cdclk_sel = (tmp >> 12) & 0x1;
7539
7540         switch (vco) {
7541         case 2666667:
7542         case 4000000:
7543         case 5333333:
7544                 return cdclk_sel ? 333333 : 222222;
7545         case 3200000:
7546                 return cdclk_sel ? 320000 : 228571;
7547         default:
7548                 DRM_ERROR("Unable to determine CDCLK. HPLL VCO=%u, CFGC=0x%04x\n", vco, tmp);
7549                 return 222222;
7550         }
7551 }
7552
7553 static int i965gm_get_display_clock_speed(struct drm_i915_private *dev_priv)
7554 {
7555         struct pci_dev *pdev = dev_priv->drm.pdev;
7556         static const uint8_t div_3200[] = { 16, 10,  8 };
7557         static const uint8_t div_4000[] = { 20, 12, 10 };
7558         static const uint8_t div_5333[] = { 24, 16, 14 };
7559         const uint8_t *div_table;
7560         unsigned int cdclk_sel, vco = intel_hpll_vco(dev_priv);
7561         uint16_t tmp = 0;
7562
7563         pci_read_config_word(pdev, GCFGC, &tmp);
7564
7565         cdclk_sel = ((tmp >> 8) & 0x1f) - 1;
7566
7567         if (cdclk_sel >= ARRAY_SIZE(div_3200))
7568                 goto fail;
7569
7570         switch (vco) {
7571         case 3200000:
7572                 div_table = div_3200;
7573                 break;
7574         case 4000000:
7575                 div_table = div_4000;
7576                 break;
7577         case 5333333:
7578                 div_table = div_5333;
7579                 break;
7580         default:
7581                 goto fail;
7582         }
7583
7584         return DIV_ROUND_CLOSEST(vco, div_table[cdclk_sel]);
7585
7586 fail:
7587         DRM_ERROR("Unable to determine CDCLK. HPLL VCO=%u kHz, CFGC=0x%04x\n", vco, tmp);
7588         return 200000;
7589 }
7590
7591 static int g33_get_display_clock_speed(struct drm_i915_private *dev_priv)
7592 {
7593         struct pci_dev *pdev = dev_priv->drm.pdev;
7594         static const uint8_t div_3200[] = { 12, 10,  8,  7, 5, 16 };
7595         static const uint8_t div_4000[] = { 14, 12, 10,  8, 6, 20 };
7596         static const uint8_t div_4800[] = { 20, 14, 12, 10, 8, 24 };
7597         static const uint8_t div_5333[] = { 20, 16, 12, 12, 8, 28 };
7598         const uint8_t *div_table;
7599         unsigned int cdclk_sel, vco = intel_hpll_vco(dev_priv);
7600         uint16_t tmp = 0;
7601
7602         pci_read_config_word(pdev, GCFGC, &tmp);
7603
7604         cdclk_sel = (tmp >> 4) & 0x7;
7605
7606         if (cdclk_sel >= ARRAY_SIZE(div_3200))
7607                 goto fail;
7608
7609         switch (vco) {
7610         case 3200000:
7611                 div_table = div_3200;
7612                 break;
7613         case 4000000:
7614                 div_table = div_4000;
7615                 break;
7616         case 4800000:
7617                 div_table = div_4800;
7618                 break;
7619         case 5333333:
7620                 div_table = div_5333;
7621                 break;
7622         default:
7623                 goto fail;
7624         }
7625
7626         return DIV_ROUND_CLOSEST(vco, div_table[cdclk_sel]);
7627
7628 fail:
7629         DRM_ERROR("Unable to determine CDCLK. HPLL VCO=%u kHz, CFGC=0x%08x\n", vco, tmp);
7630         return 190476;
7631 }
7632
7633 static void
7634 intel_reduce_m_n_ratio(uint32_t *num, uint32_t *den)
7635 {
7636         while (*num > DATA_LINK_M_N_MASK ||
7637                *den > DATA_LINK_M_N_MASK) {
7638                 *num >>= 1;
7639                 *den >>= 1;
7640         }
7641 }
7642
7643 static void compute_m_n(unsigned int m, unsigned int n,
7644                         uint32_t *ret_m, uint32_t *ret_n)
7645 {
7646         *ret_n = min_t(unsigned int, roundup_pow_of_two(n), DATA_LINK_N_MAX);
7647         *ret_m = div_u64((uint64_t) m * *ret_n, n);
7648         intel_reduce_m_n_ratio(ret_m, ret_n);
7649 }
7650
7651 void
7652 intel_link_compute_m_n(int bits_per_pixel, int nlanes,
7653                        int pixel_clock, int link_clock,
7654                        struct intel_link_m_n *m_n)
7655 {
7656         m_n->tu = 64;
7657
7658         compute_m_n(bits_per_pixel * pixel_clock,
7659                     link_clock * nlanes * 8,
7660                     &m_n->gmch_m, &m_n->gmch_n);
7661
7662         compute_m_n(pixel_clock, link_clock,
7663                     &m_n->link_m, &m_n->link_n);
7664 }
7665
7666 static inline bool intel_panel_use_ssc(struct drm_i915_private *dev_priv)
7667 {
7668         if (i915.panel_use_ssc >= 0)
7669                 return i915.panel_use_ssc != 0;
7670         return dev_priv->vbt.lvds_use_ssc
7671                 && !(dev_priv->quirks & QUIRK_LVDS_SSC_DISABLE);
7672 }
7673
7674 static uint32_t pnv_dpll_compute_fp(struct dpll *dpll)
7675 {
7676         return (1 << dpll->n) << 16 | dpll->m2;
7677 }
7678
7679 static uint32_t i9xx_dpll_compute_fp(struct dpll *dpll)
7680 {
7681         return dpll->n << 16 | dpll->m1 << 8 | dpll->m2;
7682 }
7683
7684 static void i9xx_update_pll_dividers(struct intel_crtc *crtc,
7685                                      struct intel_crtc_state *crtc_state,
7686                                      struct dpll *reduced_clock)
7687 {
7688         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
7689         u32 fp, fp2 = 0;
7690
7691         if (IS_PINEVIEW(dev_priv)) {
7692                 fp = pnv_dpll_compute_fp(&crtc_state->dpll);
7693                 if (reduced_clock)
7694                         fp2 = pnv_dpll_compute_fp(reduced_clock);
7695         } else {
7696                 fp = i9xx_dpll_compute_fp(&crtc_state->dpll);
7697                 if (reduced_clock)
7698                         fp2 = i9xx_dpll_compute_fp(reduced_clock);
7699         }
7700
7701         crtc_state->dpll_hw_state.fp0 = fp;
7702
7703         crtc->lowfreq_avail = false;
7704         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS) &&
7705             reduced_clock) {
7706                 crtc_state->dpll_hw_state.fp1 = fp2;
7707                 crtc->lowfreq_avail = true;
7708         } else {
7709                 crtc_state->dpll_hw_state.fp1 = fp;
7710         }
7711 }
7712
7713 static void vlv_pllb_recal_opamp(struct drm_i915_private *dev_priv, enum pipe
7714                 pipe)
7715 {
7716         u32 reg_val;
7717
7718         /*
7719          * PLLB opamp always calibrates to max value of 0x3f, force enable it
7720          * and set it to a reasonable value instead.
7721          */
7722         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW9(1));
7723         reg_val &= 0xffffff00;
7724         reg_val |= 0x00000030;
7725         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW9(1), reg_val);
7726
7727         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_REF_DW13);
7728         reg_val &= 0x8cffffff;
7729         reg_val = 0x8c000000;
7730         vlv_dpio_write(dev_priv, pipe, VLV_REF_DW13, reg_val);
7731
7732         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW9(1));
7733         reg_val &= 0xffffff00;
7734         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW9(1), reg_val);
7735
7736         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_REF_DW13);
7737         reg_val &= 0x00ffffff;
7738         reg_val |= 0xb0000000;
7739         vlv_dpio_write(dev_priv, pipe, VLV_REF_DW13, reg_val);
7740 }
7741
7742 static void intel_pch_transcoder_set_m_n(struct intel_crtc *crtc,
7743                                          struct intel_link_m_n *m_n)
7744 {
7745         struct drm_device *dev = crtc->base.dev;
7746         struct drm_i915_private *dev_priv = to_i915(dev);
7747         int pipe = crtc->pipe;
7748
7749         I915_WRITE(PCH_TRANS_DATA_M1(pipe), TU_SIZE(m_n->tu) | m_n->gmch_m);
7750         I915_WRITE(PCH_TRANS_DATA_N1(pipe), m_n->gmch_n);
7751         I915_WRITE(PCH_TRANS_LINK_M1(pipe), m_n->link_m);
7752         I915_WRITE(PCH_TRANS_LINK_N1(pipe), m_n->link_n);
7753 }
7754
7755 static void intel_cpu_transcoder_set_m_n(struct intel_crtc *crtc,
7756                                          struct intel_link_m_n *m_n,
7757                                          struct intel_link_m_n *m2_n2)
7758 {
7759         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
7760         int pipe = crtc->pipe;
7761         enum transcoder transcoder = crtc->config->cpu_transcoder;
7762
7763         if (INTEL_GEN(dev_priv) >= 5) {
7764                 I915_WRITE(PIPE_DATA_M1(transcoder), TU_SIZE(m_n->tu) | m_n->gmch_m);
7765                 I915_WRITE(PIPE_DATA_N1(transcoder), m_n->gmch_n);
7766                 I915_WRITE(PIPE_LINK_M1(transcoder), m_n->link_m);
7767                 I915_WRITE(PIPE_LINK_N1(transcoder), m_n->link_n);
7768                 /* M2_N2 registers to be set only for gen < 8 (M2_N2 available
7769                  * for gen < 8) and if DRRS is supported (to make sure the
7770                  * registers are not unnecessarily accessed).
7771                  */
7772                 if (m2_n2 && (IS_CHERRYVIEW(dev_priv) ||
7773                     INTEL_GEN(dev_priv) < 8) && crtc->config->has_drrs) {
7774                         I915_WRITE(PIPE_DATA_M2(transcoder),
7775                                         TU_SIZE(m2_n2->tu) | m2_n2->gmch_m);
7776                         I915_WRITE(PIPE_DATA_N2(transcoder), m2_n2->gmch_n);
7777                         I915_WRITE(PIPE_LINK_M2(transcoder), m2_n2->link_m);
7778                         I915_WRITE(PIPE_LINK_N2(transcoder), m2_n2->link_n);
7779                 }
7780         } else {
7781                 I915_WRITE(PIPE_DATA_M_G4X(pipe), TU_SIZE(m_n->tu) | m_n->gmch_m);
7782                 I915_WRITE(PIPE_DATA_N_G4X(pipe), m_n->gmch_n);
7783                 I915_WRITE(PIPE_LINK_M_G4X(pipe), m_n->link_m);
7784                 I915_WRITE(PIPE_LINK_N_G4X(pipe), m_n->link_n);
7785         }
7786 }
7787
7788 void intel_dp_set_m_n(struct intel_crtc *crtc, enum link_m_n_set m_n)
7789 {
7790         struct intel_link_m_n *dp_m_n, *dp_m2_n2 = NULL;
7791
7792         if (m_n == M1_N1) {
7793                 dp_m_n = &crtc->config->dp_m_n;
7794                 dp_m2_n2 = &crtc->config->dp_m2_n2;
7795         } else if (m_n == M2_N2) {
7796
7797                 /*
7798                  * M2_N2 registers are not supported. Hence m2_n2 divider value
7799                  * needs to be programmed into M1_N1.
7800                  */
7801                 dp_m_n = &crtc->config->dp_m2_n2;
7802         } else {
7803                 DRM_ERROR("Unsupported divider value\n");
7804                 return;
7805         }
7806
7807         if (crtc->config->has_pch_encoder)
7808                 intel_pch_transcoder_set_m_n(crtc, &crtc->config->dp_m_n);
7809         else
7810                 intel_cpu_transcoder_set_m_n(crtc, dp_m_n, dp_m2_n2);
7811 }
7812
7813 static void vlv_compute_dpll(struct intel_crtc *crtc,
7814                              struct intel_crtc_state *pipe_config)
7815 {
7816         pipe_config->dpll_hw_state.dpll = DPLL_INTEGRATED_REF_CLK_VLV |
7817                 DPLL_REF_CLK_ENABLE_VLV | DPLL_VGA_MODE_DIS;
7818         if (crtc->pipe != PIPE_A)
7819                 pipe_config->dpll_hw_state.dpll |= DPLL_INTEGRATED_CRI_CLK_VLV;
7820
7821         /* DPLL not used with DSI, but still need the rest set up */
7822         if (!intel_crtc_has_type(pipe_config, INTEL_OUTPUT_DSI))
7823                 pipe_config->dpll_hw_state.dpll |= DPLL_VCO_ENABLE |
7824                         DPLL_EXT_BUFFER_ENABLE_VLV;
7825
7826         pipe_config->dpll_hw_state.dpll_md =
7827                 (pipe_config->pixel_multiplier - 1) << DPLL_MD_UDI_MULTIPLIER_SHIFT;
7828 }
7829
7830 static void chv_compute_dpll(struct intel_crtc *crtc,
7831                              struct intel_crtc_state *pipe_config)
7832 {
7833         pipe_config->dpll_hw_state.dpll = DPLL_SSC_REF_CLK_CHV |
7834                 DPLL_REF_CLK_ENABLE_VLV | DPLL_VGA_MODE_DIS;
7835         if (crtc->pipe != PIPE_A)
7836                 pipe_config->dpll_hw_state.dpll |= DPLL_INTEGRATED_CRI_CLK_VLV;
7837
7838         /* DPLL not used with DSI, but still need the rest set up */
7839         if (!intel_crtc_has_type(pipe_config, INTEL_OUTPUT_DSI))
7840                 pipe_config->dpll_hw_state.dpll |= DPLL_VCO_ENABLE;
7841
7842         pipe_config->dpll_hw_state.dpll_md =
7843                 (pipe_config->pixel_multiplier - 1) << DPLL_MD_UDI_MULTIPLIER_SHIFT;
7844 }
7845
7846 static void vlv_prepare_pll(struct intel_crtc *crtc,
7847                             const struct intel_crtc_state *pipe_config)
7848 {
7849         struct drm_device *dev = crtc->base.dev;
7850         struct drm_i915_private *dev_priv = to_i915(dev);
7851         enum pipe pipe = crtc->pipe;
7852         u32 mdiv;
7853         u32 bestn, bestm1, bestm2, bestp1, bestp2;
7854         u32 coreclk, reg_val;
7855
7856         /* Enable Refclk */
7857         I915_WRITE(DPLL(pipe),
7858                    pipe_config->dpll_hw_state.dpll &
7859                    ~(DPLL_VCO_ENABLE | DPLL_EXT_BUFFER_ENABLE_VLV));
7860
7861         /* No need to actually set up the DPLL with DSI */
7862         if ((pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE) == 0)
7863                 return;
7864
7865         mutex_lock(&dev_priv->sb_lock);
7866
7867         bestn = pipe_config->dpll.n;
7868         bestm1 = pipe_config->dpll.m1;
7869         bestm2 = pipe_config->dpll.m2;
7870         bestp1 = pipe_config->dpll.p1;
7871         bestp2 = pipe_config->dpll.p2;
7872
7873         /* See eDP HDMI DPIO driver vbios notes doc */
7874
7875         /* PLL B needs special handling */
7876         if (pipe == PIPE_B)
7877                 vlv_pllb_recal_opamp(dev_priv, pipe);
7878
7879         /* Set up Tx target for periodic Rcomp update */
7880         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW9_BCAST, 0x0100000f);
7881
7882         /* Disable target IRef on PLL */
7883         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW8(pipe));
7884         reg_val &= 0x00ffffff;
7885         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW8(pipe), reg_val);
7886
7887         /* Disable fast lock */
7888         vlv_dpio_write(dev_priv, pipe, VLV_CMN_DW0, 0x610);
7889
7890         /* Set idtafcrecal before PLL is enabled */
7891         mdiv = ((bestm1 << DPIO_M1DIV_SHIFT) | (bestm2 & DPIO_M2DIV_MASK));
7892         mdiv |= ((bestp1 << DPIO_P1_SHIFT) | (bestp2 << DPIO_P2_SHIFT));
7893         mdiv |= ((bestn << DPIO_N_SHIFT));
7894         mdiv |= (1 << DPIO_K_SHIFT);
7895
7896         /*
7897          * Post divider depends on pixel clock rate, DAC vs digital (and LVDS,
7898          * but we don't support that).
7899          * Note: don't use the DAC post divider as it seems unstable.
7900          */
7901         mdiv |= (DPIO_POST_DIV_HDMIDP << DPIO_POST_DIV_SHIFT);
7902         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW3(pipe), mdiv);
7903
7904         mdiv |= DPIO_ENABLE_CALIBRATION;
7905         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW3(pipe), mdiv);
7906
7907         /* Set HBR and RBR LPF coefficients */
7908         if (pipe_config->port_clock == 162000 ||
7909             intel_crtc_has_type(crtc->config, INTEL_OUTPUT_ANALOG) ||
7910             intel_crtc_has_type(crtc->config, INTEL_OUTPUT_HDMI))
7911                 vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW10(pipe),
7912                                  0x009f0003);
7913         else
7914                 vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW10(pipe),
7915                                  0x00d0000f);
7916
7917         if (intel_crtc_has_dp_encoder(pipe_config)) {
7918                 /* Use SSC source */
7919                 if (pipe == PIPE_A)
7920                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
7921                                          0x0df40000);
7922                 else
7923                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
7924                                          0x0df70000);
7925         } else { /* HDMI or VGA */
7926                 /* Use bend source */
7927                 if (pipe == PIPE_A)
7928                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
7929                                          0x0df70000);
7930                 else
7931                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
7932                                          0x0df40000);
7933         }
7934
7935         coreclk = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW7(pipe));
7936         coreclk = (coreclk & 0x0000ff00) | 0x01c00000;
7937         if (intel_crtc_has_dp_encoder(crtc->config))
7938                 coreclk |= 0x01000000;
7939         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW7(pipe), coreclk);
7940
7941         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW11(pipe), 0x87871000);
7942         mutex_unlock(&dev_priv->sb_lock);
7943 }
7944
7945 static void chv_prepare_pll(struct intel_crtc *crtc,
7946                             const struct intel_crtc_state *pipe_config)
7947 {
7948         struct drm_device *dev = crtc->base.dev;
7949         struct drm_i915_private *dev_priv = to_i915(dev);
7950         enum pipe pipe = crtc->pipe;
7951         enum dpio_channel port = vlv_pipe_to_channel(pipe);
7952         u32 loopfilter, tribuf_calcntr;
7953         u32 bestn, bestm1, bestm2, bestp1, bestp2, bestm2_frac;
7954         u32 dpio_val;
7955         int vco;
7956
7957         /* Enable Refclk and SSC */
7958         I915_WRITE(DPLL(pipe),
7959                    pipe_config->dpll_hw_state.dpll & ~DPLL_VCO_ENABLE);
7960
7961         /* No need to actually set up the DPLL with DSI */
7962         if ((pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE) == 0)
7963                 return;
7964
7965         bestn = pipe_config->dpll.n;
7966         bestm2_frac = pipe_config->dpll.m2 & 0x3fffff;
7967         bestm1 = pipe_config->dpll.m1;
7968         bestm2 = pipe_config->dpll.m2 >> 22;
7969         bestp1 = pipe_config->dpll.p1;
7970         bestp2 = pipe_config->dpll.p2;
7971         vco = pipe_config->dpll.vco;
7972         dpio_val = 0;
7973         loopfilter = 0;
7974
7975         mutex_lock(&dev_priv->sb_lock);
7976
7977         /* p1 and p2 divider */
7978         vlv_dpio_write(dev_priv, pipe, CHV_CMN_DW13(port),
7979                         5 << DPIO_CHV_S1_DIV_SHIFT |
7980                         bestp1 << DPIO_CHV_P1_DIV_SHIFT |
7981                         bestp2 << DPIO_CHV_P2_DIV_SHIFT |
7982                         1 << DPIO_CHV_K_DIV_SHIFT);
7983
7984         /* Feedback post-divider - m2 */
7985         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW0(port), bestm2);
7986
7987         /* Feedback refclk divider - n and m1 */
7988         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW1(port),
7989                         DPIO_CHV_M1_DIV_BY_2 |
7990                         1 << DPIO_CHV_N_DIV_SHIFT);
7991
7992         /* M2 fraction division */
7993         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW2(port), bestm2_frac);
7994
7995         /* M2 fraction division enable */
7996         dpio_val = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW3(port));
7997         dpio_val &= ~(DPIO_CHV_FEEDFWD_GAIN_MASK | DPIO_CHV_FRAC_DIV_EN);
7998         dpio_val |= (2 << DPIO_CHV_FEEDFWD_GAIN_SHIFT);
7999         if (bestm2_frac)
8000                 dpio_val |= DPIO_CHV_FRAC_DIV_EN;
8001         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW3(port), dpio_val);
8002
8003         /* Program digital lock detect threshold */
8004         dpio_val = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW9(port));
8005         dpio_val &= ~(DPIO_CHV_INT_LOCK_THRESHOLD_MASK |
8006                                         DPIO_CHV_INT_LOCK_THRESHOLD_SEL_COARSE);
8007         dpio_val |= (0x5 << DPIO_CHV_INT_LOCK_THRESHOLD_SHIFT);
8008         if (!bestm2_frac)
8009                 dpio_val |= DPIO_CHV_INT_LOCK_THRESHOLD_SEL_COARSE;
8010         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW9(port), dpio_val);
8011
8012         /* Loop filter */
8013         if (vco == 5400000) {
8014                 loopfilter |= (0x3 << DPIO_CHV_PROP_COEFF_SHIFT);
8015                 loopfilter |= (0x8 << DPIO_CHV_INT_COEFF_SHIFT);
8016                 loopfilter |= (0x1 << DPIO_CHV_GAIN_CTRL_SHIFT);
8017                 tribuf_calcntr = 0x9;
8018         } else if (vco <= 6200000) {
8019                 loopfilter |= (0x5 << DPIO_CHV_PROP_COEFF_SHIFT);
8020                 loopfilter |= (0xB << DPIO_CHV_INT_COEFF_SHIFT);
8021                 loopfilter |= (0x3 << DPIO_CHV_GAIN_CTRL_SHIFT);
8022                 tribuf_calcntr = 0x9;
8023         } else if (vco <= 6480000) {
8024                 loopfilter |= (0x4 << DPIO_CHV_PROP_COEFF_SHIFT);
8025                 loopfilter |= (0x9 << DPIO_CHV_INT_COEFF_SHIFT);
8026                 loopfilter |= (0x3 << DPIO_CHV_GAIN_CTRL_SHIFT);
8027                 tribuf_calcntr = 0x8;
8028         } else {
8029                 /* Not supported. Apply the same limits as in the max case */
8030                 loopfilter |= (0x4 << DPIO_CHV_PROP_COEFF_SHIFT);
8031                 loopfilter |= (0x9 << DPIO_CHV_INT_COEFF_SHIFT);
8032                 loopfilter |= (0x3 << DPIO_CHV_GAIN_CTRL_SHIFT);
8033                 tribuf_calcntr = 0;
8034         }
8035         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW6(port), loopfilter);
8036
8037         dpio_val = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW8(port));
8038         dpio_val &= ~DPIO_CHV_TDC_TARGET_CNT_MASK;
8039         dpio_val |= (tribuf_calcntr << DPIO_CHV_TDC_TARGET_CNT_SHIFT);
8040         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW8(port), dpio_val);
8041
8042         /* AFC Recal */
8043         vlv_dpio_write(dev_priv, pipe, CHV_CMN_DW14(port),
8044                         vlv_dpio_read(dev_priv, pipe, CHV_CMN_DW14(port)) |
8045                         DPIO_AFC_RECAL);
8046
8047         mutex_unlock(&dev_priv->sb_lock);
8048 }
8049
8050 /**
8051  * vlv_force_pll_on - forcibly enable just the PLL
8052  * @dev_priv: i915 private structure
8053  * @pipe: pipe PLL to enable
8054  * @dpll: PLL configuration
8055  *
8056  * Enable the PLL for @pipe using the supplied @dpll config. To be used
8057  * in cases where we need the PLL enabled even when @pipe is not going to
8058  * be enabled.
8059  */
8060 int vlv_force_pll_on(struct drm_i915_private *dev_priv, enum pipe pipe,
8061                      const struct dpll *dpll)
8062 {
8063         struct intel_crtc *crtc = intel_get_crtc_for_pipe(dev_priv, pipe);
8064         struct intel_crtc_state *pipe_config;
8065
8066         pipe_config = kzalloc(sizeof(*pipe_config), GFP_KERNEL);
8067         if (!pipe_config)
8068                 return -ENOMEM;
8069
8070         pipe_config->base.crtc = &crtc->base;
8071         pipe_config->pixel_multiplier = 1;
8072         pipe_config->dpll = *dpll;
8073
8074         if (IS_CHERRYVIEW(dev_priv)) {
8075                 chv_compute_dpll(crtc, pipe_config);
8076                 chv_prepare_pll(crtc, pipe_config);
8077                 chv_enable_pll(crtc, pipe_config);
8078         } else {
8079                 vlv_compute_dpll(crtc, pipe_config);
8080                 vlv_prepare_pll(crtc, pipe_config);
8081                 vlv_enable_pll(crtc, pipe_config);
8082         }
8083
8084         kfree(pipe_config);
8085
8086         return 0;
8087 }
8088
8089 /**
8090  * vlv_force_pll_off - forcibly disable just the PLL
8091  * @dev_priv: i915 private structure
8092  * @pipe: pipe PLL to disable
8093  *
8094  * Disable the PLL for @pipe. To be used in cases where we need
8095  * the PLL enabled even when @pipe is not going to be enabled.
8096  */
8097 void vlv_force_pll_off(struct drm_i915_private *dev_priv, enum pipe pipe)
8098 {
8099         if (IS_CHERRYVIEW(dev_priv))
8100                 chv_disable_pll(dev_priv, pipe);
8101         else
8102                 vlv_disable_pll(dev_priv, pipe);
8103 }
8104
8105 static void i9xx_compute_dpll(struct intel_crtc *crtc,
8106                               struct intel_crtc_state *crtc_state,
8107                               struct dpll *reduced_clock)
8108 {
8109         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
8110         u32 dpll;
8111         struct dpll *clock = &crtc_state->dpll;
8112
8113         i9xx_update_pll_dividers(crtc, crtc_state, reduced_clock);
8114
8115         dpll = DPLL_VGA_MODE_DIS;
8116
8117         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS))
8118                 dpll |= DPLLB_MODE_LVDS;
8119         else
8120                 dpll |= DPLLB_MODE_DAC_SERIAL;
8121
8122         if (IS_I945G(dev_priv) || IS_I945GM(dev_priv) || IS_G33(dev_priv)) {
8123                 dpll |= (crtc_state->pixel_multiplier - 1)
8124                         << SDVO_MULTIPLIER_SHIFT_HIRES;
8125         }
8126
8127         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_SDVO) ||
8128             intel_crtc_has_type(crtc_state, INTEL_OUTPUT_HDMI))
8129                 dpll |= DPLL_SDVO_HIGH_SPEED;
8130
8131         if (intel_crtc_has_dp_encoder(crtc_state))
8132                 dpll |= DPLL_SDVO_HIGH_SPEED;
8133
8134         /* compute bitmask from p1 value */
8135         if (IS_PINEVIEW(dev_priv))
8136                 dpll |= (1 << (clock->p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT_PINEVIEW;
8137         else {
8138                 dpll |= (1 << (clock->p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT;
8139                 if (IS_G4X(dev_priv) && reduced_clock)
8140                         dpll |= (1 << (reduced_clock->p1 - 1)) << DPLL_FPA1_P1_POST_DIV_SHIFT;
8141         }
8142         switch (clock->p2) {
8143         case 5:
8144                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_5;
8145                 break;
8146         case 7:
8147                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_7;
8148                 break;
8149         case 10:
8150                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_10;
8151                 break;
8152         case 14:
8153                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_14;
8154                 break;
8155         }
8156         if (INTEL_GEN(dev_priv) >= 4)
8157                 dpll |= (6 << PLL_LOAD_PULSE_PHASE_SHIFT);
8158
8159         if (crtc_state->sdvo_tv_clock)
8160                 dpll |= PLL_REF_INPUT_TVCLKINBC;
8161         else if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS) &&
8162                  intel_panel_use_ssc(dev_priv))
8163                 dpll |= PLLB_REF_INPUT_SPREADSPECTRUMIN;
8164         else
8165                 dpll |= PLL_REF_INPUT_DREFCLK;
8166
8167         dpll |= DPLL_VCO_ENABLE;
8168         crtc_state->dpll_hw_state.dpll = dpll;
8169
8170         if (INTEL_GEN(dev_priv) >= 4) {
8171                 u32 dpll_md = (crtc_state->pixel_multiplier - 1)
8172                         << DPLL_MD_UDI_MULTIPLIER_SHIFT;
8173                 crtc_state->dpll_hw_state.dpll_md = dpll_md;
8174         }
8175 }
8176
8177 static void i8xx_compute_dpll(struct intel_crtc *crtc,
8178                               struct intel_crtc_state *crtc_state,
8179                               struct dpll *reduced_clock)
8180 {
8181         struct drm_device *dev = crtc->base.dev;
8182         struct drm_i915_private *dev_priv = to_i915(dev);
8183         u32 dpll;
8184         struct dpll *clock = &crtc_state->dpll;
8185
8186         i9xx_update_pll_dividers(crtc, crtc_state, reduced_clock);
8187
8188         dpll = DPLL_VGA_MODE_DIS;
8189
8190         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
8191                 dpll |= (1 << (clock->p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT;
8192         } else {
8193                 if (clock->p1 == 2)
8194                         dpll |= PLL_P1_DIVIDE_BY_TWO;
8195                 else
8196                         dpll |= (clock->p1 - 2) << DPLL_FPA01_P1_POST_DIV_SHIFT;
8197                 if (clock->p2 == 4)
8198                         dpll |= PLL_P2_DIVIDE_BY_4;
8199         }
8200
8201         if (!IS_I830(dev_priv) &&
8202             intel_crtc_has_type(crtc_state, INTEL_OUTPUT_DVO))
8203                 dpll |= DPLL_DVO_2X_MODE;
8204
8205         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS) &&
8206             intel_panel_use_ssc(dev_priv))
8207                 dpll |= PLLB_REF_INPUT_SPREADSPECTRUMIN;
8208         else
8209                 dpll |= PLL_REF_INPUT_DREFCLK;
8210
8211         dpll |= DPLL_VCO_ENABLE;
8212         crtc_state->dpll_hw_state.dpll = dpll;
8213 }
8214
8215 static void intel_set_pipe_timings(struct intel_crtc *intel_crtc)
8216 {
8217         struct drm_i915_private *dev_priv = to_i915(intel_crtc->base.dev);
8218         enum pipe pipe = intel_crtc->pipe;
8219         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
8220         const struct drm_display_mode *adjusted_mode = &intel_crtc->config->base.adjusted_mode;
8221         uint32_t crtc_vtotal, crtc_vblank_end;
8222         int vsyncshift = 0;
8223
8224         /* We need to be careful not to changed the adjusted mode, for otherwise
8225          * the hw state checker will get angry at the mismatch. */
8226         crtc_vtotal = adjusted_mode->crtc_vtotal;
8227         crtc_vblank_end = adjusted_mode->crtc_vblank_end;
8228
8229         if (adjusted_mode->flags & DRM_MODE_FLAG_INTERLACE) {
8230                 /* the chip adds 2 halflines automatically */
8231                 crtc_vtotal -= 1;
8232                 crtc_vblank_end -= 1;
8233
8234                 if (intel_crtc_has_type(intel_crtc->config, INTEL_OUTPUT_SDVO))
8235                         vsyncshift = (adjusted_mode->crtc_htotal - 1) / 2;
8236                 else
8237                         vsyncshift = adjusted_mode->crtc_hsync_start -
8238                                 adjusted_mode->crtc_htotal / 2;
8239                 if (vsyncshift < 0)
8240                         vsyncshift += adjusted_mode->crtc_htotal;
8241         }
8242
8243         if (INTEL_GEN(dev_priv) > 3)
8244                 I915_WRITE(VSYNCSHIFT(cpu_transcoder), vsyncshift);
8245
8246         I915_WRITE(HTOTAL(cpu_transcoder),
8247                    (adjusted_mode->crtc_hdisplay - 1) |
8248                    ((adjusted_mode->crtc_htotal - 1) << 16));
8249         I915_WRITE(HBLANK(cpu_transcoder),
8250                    (adjusted_mode->crtc_hblank_start - 1) |
8251                    ((adjusted_mode->crtc_hblank_end - 1) << 16));
8252         I915_WRITE(HSYNC(cpu_transcoder),
8253                    (adjusted_mode->crtc_hsync_start - 1) |
8254                    ((adjusted_mode->crtc_hsync_end - 1) << 16));
8255
8256         I915_WRITE(VTOTAL(cpu_transcoder),
8257                    (adjusted_mode->crtc_vdisplay - 1) |
8258                    ((crtc_vtotal - 1) << 16));
8259         I915_WRITE(VBLANK(cpu_transcoder),
8260                    (adjusted_mode->crtc_vblank_start - 1) |
8261                    ((crtc_vblank_end - 1) << 16));
8262         I915_WRITE(VSYNC(cpu_transcoder),
8263                    (adjusted_mode->crtc_vsync_start - 1) |
8264                    ((adjusted_mode->crtc_vsync_end - 1) << 16));
8265
8266         /* Workaround: when the EDP input selection is B, the VTOTAL_B must be
8267          * programmed with the VTOTAL_EDP value. Same for VTOTAL_C. This is
8268          * documented on the DDI_FUNC_CTL register description, EDP Input Select
8269          * bits. */
8270         if (IS_HASWELL(dev_priv) && cpu_transcoder == TRANSCODER_EDP &&
8271             (pipe == PIPE_B || pipe == PIPE_C))
8272                 I915_WRITE(VTOTAL(pipe), I915_READ(VTOTAL(cpu_transcoder)));
8273
8274 }
8275
8276 static void intel_set_pipe_src_size(struct intel_crtc *intel_crtc)
8277 {
8278         struct drm_device *dev = intel_crtc->base.dev;
8279         struct drm_i915_private *dev_priv = to_i915(dev);
8280         enum pipe pipe = intel_crtc->pipe;
8281
8282         /* pipesrc controls the size that is scaled from, which should
8283          * always be the user's requested size.
8284          */
8285         I915_WRITE(PIPESRC(pipe),
8286                    ((intel_crtc->config->pipe_src_w - 1) << 16) |
8287                    (intel_crtc->config->pipe_src_h - 1));
8288 }
8289
8290 static void intel_get_pipe_timings(struct intel_crtc *crtc,
8291                                    struct intel_crtc_state *pipe_config)
8292 {
8293         struct drm_device *dev = crtc->base.dev;
8294         struct drm_i915_private *dev_priv = to_i915(dev);
8295         enum transcoder cpu_transcoder = pipe_config->cpu_transcoder;
8296         uint32_t tmp;
8297
8298         tmp = I915_READ(HTOTAL(cpu_transcoder));
8299         pipe_config->base.adjusted_mode.crtc_hdisplay = (tmp & 0xffff) + 1;
8300         pipe_config->base.adjusted_mode.crtc_htotal = ((tmp >> 16) & 0xffff) + 1;
8301         tmp = I915_READ(HBLANK(cpu_transcoder));
8302         pipe_config->base.adjusted_mode.crtc_hblank_start = (tmp & 0xffff) + 1;
8303         pipe_config->base.adjusted_mode.crtc_hblank_end = ((tmp >> 16) & 0xffff) + 1;
8304         tmp = I915_READ(HSYNC(cpu_transcoder));
8305         pipe_config->base.adjusted_mode.crtc_hsync_start = (tmp & 0xffff) + 1;
8306         pipe_config->base.adjusted_mode.crtc_hsync_end = ((tmp >> 16) & 0xffff) + 1;
8307
8308         tmp = I915_READ(VTOTAL(cpu_transcoder));
8309         pipe_config->base.adjusted_mode.crtc_vdisplay = (tmp & 0xffff) + 1;
8310         pipe_config->base.adjusted_mode.crtc_vtotal = ((tmp >> 16) & 0xffff) + 1;
8311         tmp = I915_READ(VBLANK(cpu_transcoder));
8312         pipe_config->base.adjusted_mode.crtc_vblank_start = (tmp & 0xffff) + 1;
8313         pipe_config->base.adjusted_mode.crtc_vblank_end = ((tmp >> 16) & 0xffff) + 1;
8314         tmp = I915_READ(VSYNC(cpu_transcoder));
8315         pipe_config->base.adjusted_mode.crtc_vsync_start = (tmp & 0xffff) + 1;
8316         pipe_config->base.adjusted_mode.crtc_vsync_end = ((tmp >> 16) & 0xffff) + 1;
8317
8318         if (I915_READ(PIPECONF(cpu_transcoder)) & PIPECONF_INTERLACE_MASK) {
8319                 pipe_config->base.adjusted_mode.flags |= DRM_MODE_FLAG_INTERLACE;
8320                 pipe_config->base.adjusted_mode.crtc_vtotal += 1;
8321                 pipe_config->base.adjusted_mode.crtc_vblank_end += 1;
8322         }
8323 }
8324
8325 static void intel_get_pipe_src_size(struct intel_crtc *crtc,
8326                                     struct intel_crtc_state *pipe_config)
8327 {
8328         struct drm_device *dev = crtc->base.dev;
8329         struct drm_i915_private *dev_priv = to_i915(dev);
8330         u32 tmp;
8331
8332         tmp = I915_READ(PIPESRC(crtc->pipe));
8333         pipe_config->pipe_src_h = (tmp & 0xffff) + 1;
8334         pipe_config->pipe_src_w = ((tmp >> 16) & 0xffff) + 1;
8335
8336         pipe_config->base.mode.vdisplay = pipe_config->pipe_src_h;
8337         pipe_config->base.mode.hdisplay = pipe_config->pipe_src_w;
8338 }
8339
8340 void intel_mode_from_pipe_config(struct drm_display_mode *mode,
8341                                  struct intel_crtc_state *pipe_config)
8342 {
8343         mode->hdisplay = pipe_config->base.adjusted_mode.crtc_hdisplay;
8344         mode->htotal = pipe_config->base.adjusted_mode.crtc_htotal;
8345         mode->hsync_start = pipe_config->base.adjusted_mode.crtc_hsync_start;
8346         mode->hsync_end = pipe_config->base.adjusted_mode.crtc_hsync_end;
8347
8348         mode->vdisplay = pipe_config->base.adjusted_mode.crtc_vdisplay;
8349         mode->vtotal = pipe_config->base.adjusted_mode.crtc_vtotal;
8350         mode->vsync_start = pipe_config->base.adjusted_mode.crtc_vsync_start;
8351         mode->vsync_end = pipe_config->base.adjusted_mode.crtc_vsync_end;
8352
8353         mode->flags = pipe_config->base.adjusted_mode.flags;
8354         mode->type = DRM_MODE_TYPE_DRIVER;
8355
8356         mode->clock = pipe_config->base.adjusted_mode.crtc_clock;
8357         mode->flags |= pipe_config->base.adjusted_mode.flags;
8358
8359         mode->hsync = drm_mode_hsync(mode);
8360         mode->vrefresh = drm_mode_vrefresh(mode);
8361         drm_mode_set_name(mode);
8362 }
8363
8364 static void i9xx_set_pipeconf(struct intel_crtc *intel_crtc)
8365 {
8366         struct drm_i915_private *dev_priv = to_i915(intel_crtc->base.dev);
8367         uint32_t pipeconf;
8368
8369         pipeconf = 0;
8370
8371         if ((intel_crtc->pipe == PIPE_A && dev_priv->quirks & QUIRK_PIPEA_FORCE) ||
8372             (intel_crtc->pipe == PIPE_B && dev_priv->quirks & QUIRK_PIPEB_FORCE))
8373                 pipeconf |= I915_READ(PIPECONF(intel_crtc->pipe)) & PIPECONF_ENABLE;
8374
8375         if (intel_crtc->config->double_wide)
8376                 pipeconf |= PIPECONF_DOUBLE_WIDE;
8377
8378         /* only g4x and later have fancy bpc/dither controls */
8379         if (IS_G4X(dev_priv) || IS_VALLEYVIEW(dev_priv) ||
8380             IS_CHERRYVIEW(dev_priv)) {
8381                 /* Bspec claims that we can't use dithering for 30bpp pipes. */
8382                 if (intel_crtc->config->dither && intel_crtc->config->pipe_bpp != 30)
8383                         pipeconf |= PIPECONF_DITHER_EN |
8384                                     PIPECONF_DITHER_TYPE_SP;
8385
8386                 switch (intel_crtc->config->pipe_bpp) {
8387                 case 18:
8388                         pipeconf |= PIPECONF_6BPC;
8389                         break;
8390                 case 24:
8391                         pipeconf |= PIPECONF_8BPC;
8392                         break;
8393                 case 30:
8394                         pipeconf |= PIPECONF_10BPC;
8395                         break;
8396                 default:
8397                         /* Case prevented by intel_choose_pipe_bpp_dither. */
8398                         BUG();
8399                 }
8400         }
8401
8402         if (HAS_PIPE_CXSR(dev_priv)) {
8403                 if (intel_crtc->lowfreq_avail) {
8404                         DRM_DEBUG_KMS("enabling CxSR downclocking\n");
8405                         pipeconf |= PIPECONF_CXSR_DOWNCLOCK;
8406                 } else {
8407                         DRM_DEBUG_KMS("disabling CxSR downclocking\n");
8408                 }
8409         }
8410
8411         if (intel_crtc->config->base.adjusted_mode.flags & DRM_MODE_FLAG_INTERLACE) {
8412                 if (INTEL_GEN(dev_priv) < 4 ||
8413                     intel_crtc_has_type(intel_crtc->config, INTEL_OUTPUT_SDVO))
8414                         pipeconf |= PIPECONF_INTERLACE_W_FIELD_INDICATION;
8415                 else
8416                         pipeconf |= PIPECONF_INTERLACE_W_SYNC_SHIFT;
8417         } else
8418                 pipeconf |= PIPECONF_PROGRESSIVE;
8419
8420         if ((IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv)) &&
8421              intel_crtc->config->limited_color_range)
8422                 pipeconf |= PIPECONF_COLOR_RANGE_SELECT;
8423
8424         I915_WRITE(PIPECONF(intel_crtc->pipe), pipeconf);
8425         POSTING_READ(PIPECONF(intel_crtc->pipe));
8426 }
8427
8428 static int i8xx_crtc_compute_clock(struct intel_crtc *crtc,
8429                                    struct intel_crtc_state *crtc_state)
8430 {
8431         struct drm_device *dev = crtc->base.dev;
8432         struct drm_i915_private *dev_priv = to_i915(dev);
8433         const struct intel_limit *limit;
8434         int refclk = 48000;
8435
8436         memset(&crtc_state->dpll_hw_state, 0,
8437                sizeof(crtc_state->dpll_hw_state));
8438
8439         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
8440                 if (intel_panel_use_ssc(dev_priv)) {
8441                         refclk = dev_priv->vbt.lvds_ssc_freq;
8442                         DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n", refclk);
8443                 }
8444
8445                 limit = &intel_limits_i8xx_lvds;
8446         } else if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_DVO)) {
8447                 limit = &intel_limits_i8xx_dvo;
8448         } else {
8449                 limit = &intel_limits_i8xx_dac;
8450         }
8451
8452         if (!crtc_state->clock_set &&
8453             !i9xx_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
8454                                  refclk, NULL, &crtc_state->dpll)) {
8455                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
8456                 return -EINVAL;
8457         }
8458
8459         i8xx_compute_dpll(crtc, crtc_state, NULL);
8460
8461         return 0;
8462 }
8463
8464 static int g4x_crtc_compute_clock(struct intel_crtc *crtc,
8465                                   struct intel_crtc_state *crtc_state)
8466 {
8467         struct drm_device *dev = crtc->base.dev;
8468         struct drm_i915_private *dev_priv = to_i915(dev);
8469         const struct intel_limit *limit;
8470         int refclk = 96000;
8471
8472         memset(&crtc_state->dpll_hw_state, 0,
8473                sizeof(crtc_state->dpll_hw_state));
8474
8475         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
8476                 if (intel_panel_use_ssc(dev_priv)) {
8477                         refclk = dev_priv->vbt.lvds_ssc_freq;
8478                         DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n", refclk);
8479                 }
8480
8481                 if (intel_is_dual_link_lvds(dev))
8482                         limit = &intel_limits_g4x_dual_channel_lvds;
8483                 else
8484                         limit = &intel_limits_g4x_single_channel_lvds;
8485         } else if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_HDMI) ||
8486                    intel_crtc_has_type(crtc_state, INTEL_OUTPUT_ANALOG)) {
8487                 limit = &intel_limits_g4x_hdmi;
8488         } else if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_SDVO)) {
8489                 limit = &intel_limits_g4x_sdvo;
8490         } else {
8491                 /* The option is for other outputs */
8492                 limit = &intel_limits_i9xx_sdvo;
8493         }
8494
8495         if (!crtc_state->clock_set &&
8496             !g4x_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
8497                                 refclk, NULL, &crtc_state->dpll)) {
8498                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
8499                 return -EINVAL;
8500         }
8501
8502         i9xx_compute_dpll(crtc, crtc_state, NULL);
8503
8504         return 0;
8505 }
8506
8507 static int pnv_crtc_compute_clock(struct intel_crtc *crtc,
8508                                   struct intel_crtc_state *crtc_state)
8509 {
8510         struct drm_device *dev = crtc->base.dev;
8511         struct drm_i915_private *dev_priv = to_i915(dev);
8512         const struct intel_limit *limit;
8513         int refclk = 96000;
8514
8515         memset(&crtc_state->dpll_hw_state, 0,
8516                sizeof(crtc_state->dpll_hw_state));
8517
8518         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
8519                 if (intel_panel_use_ssc(dev_priv)) {
8520                         refclk = dev_priv->vbt.lvds_ssc_freq;
8521                         DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n", refclk);
8522                 }
8523
8524                 limit = &intel_limits_pineview_lvds;
8525         } else {
8526                 limit = &intel_limits_pineview_sdvo;
8527         }
8528
8529         if (!crtc_state->clock_set &&
8530             !pnv_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
8531                                 refclk, NULL, &crtc_state->dpll)) {
8532                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
8533                 return -EINVAL;
8534         }
8535
8536         i9xx_compute_dpll(crtc, crtc_state, NULL);
8537
8538         return 0;
8539 }
8540
8541 static int i9xx_crtc_compute_clock(struct intel_crtc *crtc,
8542                                    struct intel_crtc_state *crtc_state)
8543 {
8544         struct drm_device *dev = crtc->base.dev;
8545         struct drm_i915_private *dev_priv = to_i915(dev);
8546         const struct intel_limit *limit;
8547         int refclk = 96000;
8548
8549         memset(&crtc_state->dpll_hw_state, 0,
8550                sizeof(crtc_state->dpll_hw_state));
8551
8552         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
8553                 if (intel_panel_use_ssc(dev_priv)) {
8554                         refclk = dev_priv->vbt.lvds_ssc_freq;
8555                         DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n", refclk);
8556                 }
8557
8558                 limit = &intel_limits_i9xx_lvds;
8559         } else {
8560                 limit = &intel_limits_i9xx_sdvo;
8561         }
8562
8563         if (!crtc_state->clock_set &&
8564             !i9xx_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
8565                                  refclk, NULL, &crtc_state->dpll)) {
8566                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
8567                 return -EINVAL;
8568         }
8569
8570         i9xx_compute_dpll(crtc, crtc_state, NULL);
8571
8572         return 0;
8573 }
8574
8575 static int chv_crtc_compute_clock(struct intel_crtc *crtc,
8576                                   struct intel_crtc_state *crtc_state)
8577 {
8578         int refclk = 100000;
8579         const struct intel_limit *limit = &intel_limits_chv;
8580
8581         memset(&crtc_state->dpll_hw_state, 0,
8582                sizeof(crtc_state->dpll_hw_state));
8583
8584         if (!crtc_state->clock_set &&
8585             !chv_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
8586                                 refclk, NULL, &crtc_state->dpll)) {
8587                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
8588                 return -EINVAL;
8589         }
8590
8591         chv_compute_dpll(crtc, crtc_state);
8592
8593         return 0;
8594 }
8595
8596 static int vlv_crtc_compute_clock(struct intel_crtc *crtc,
8597                                   struct intel_crtc_state *crtc_state)
8598 {
8599         int refclk = 100000;
8600         const struct intel_limit *limit = &intel_limits_vlv;
8601
8602         memset(&crtc_state->dpll_hw_state, 0,
8603                sizeof(crtc_state->dpll_hw_state));
8604
8605         if (!crtc_state->clock_set &&
8606             !vlv_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
8607                                 refclk, NULL, &crtc_state->dpll)) {
8608                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
8609                 return -EINVAL;
8610         }
8611
8612         vlv_compute_dpll(crtc, crtc_state);
8613
8614         return 0;
8615 }
8616
8617 static void i9xx_get_pfit_config(struct intel_crtc *crtc,
8618                                  struct intel_crtc_state *pipe_config)
8619 {
8620         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
8621         uint32_t tmp;
8622
8623         if (INTEL_GEN(dev_priv) <= 3 &&
8624             (IS_I830(dev_priv) || !IS_MOBILE(dev_priv)))
8625                 return;
8626
8627         tmp = I915_READ(PFIT_CONTROL);
8628         if (!(tmp & PFIT_ENABLE))
8629                 return;
8630
8631         /* Check whether the pfit is attached to our pipe. */
8632         if (INTEL_GEN(dev_priv) < 4) {
8633                 if (crtc->pipe != PIPE_B)
8634                         return;
8635         } else {
8636                 if ((tmp & PFIT_PIPE_MASK) != (crtc->pipe << PFIT_PIPE_SHIFT))
8637                         return;
8638         }
8639
8640         pipe_config->gmch_pfit.control = tmp;
8641         pipe_config->gmch_pfit.pgm_ratios = I915_READ(PFIT_PGM_RATIOS);
8642 }
8643
8644 static void vlv_crtc_clock_get(struct intel_crtc *crtc,
8645                                struct intel_crtc_state *pipe_config)
8646 {
8647         struct drm_device *dev = crtc->base.dev;
8648         struct drm_i915_private *dev_priv = to_i915(dev);
8649         int pipe = pipe_config->cpu_transcoder;
8650         struct dpll clock;
8651         u32 mdiv;
8652         int refclk = 100000;
8653
8654         /* In case of DSI, DPLL will not be used */
8655         if ((pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE) == 0)
8656                 return;
8657
8658         mutex_lock(&dev_priv->sb_lock);
8659         mdiv = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW3(pipe));
8660         mutex_unlock(&dev_priv->sb_lock);
8661
8662         clock.m1 = (mdiv >> DPIO_M1DIV_SHIFT) & 7;
8663         clock.m2 = mdiv & DPIO_M2DIV_MASK;
8664         clock.n = (mdiv >> DPIO_N_SHIFT) & 0xf;
8665         clock.p1 = (mdiv >> DPIO_P1_SHIFT) & 7;
8666         clock.p2 = (mdiv >> DPIO_P2_SHIFT) & 0x1f;
8667
8668         pipe_config->port_clock = vlv_calc_dpll_params(refclk, &clock);
8669 }
8670
8671 static void
8672 i9xx_get_initial_plane_config(struct intel_crtc *crtc,
8673                               struct intel_initial_plane_config *plane_config)
8674 {
8675         struct drm_device *dev = crtc->base.dev;
8676         struct drm_i915_private *dev_priv = to_i915(dev);
8677         u32 val, base, offset;
8678         int pipe = crtc->pipe, plane = crtc->plane;
8679         int fourcc, pixel_format;
8680         unsigned int aligned_height;
8681         struct drm_framebuffer *fb;
8682         struct intel_framebuffer *intel_fb;
8683
8684         val = I915_READ(DSPCNTR(plane));
8685         if (!(val & DISPLAY_PLANE_ENABLE))
8686                 return;
8687
8688         intel_fb = kzalloc(sizeof(*intel_fb), GFP_KERNEL);
8689         if (!intel_fb) {
8690                 DRM_DEBUG_KMS("failed to alloc fb\n");
8691                 return;
8692         }
8693
8694         fb = &intel_fb->base;
8695
8696         if (INTEL_GEN(dev_priv) >= 4) {
8697                 if (val & DISPPLANE_TILED) {
8698                         plane_config->tiling = I915_TILING_X;
8699                         fb->modifier = I915_FORMAT_MOD_X_TILED;
8700                 }
8701         }
8702
8703         pixel_format = val & DISPPLANE_PIXFORMAT_MASK;
8704         fourcc = i9xx_format_to_fourcc(pixel_format);
8705         fb->pixel_format = fourcc;
8706         fb->bits_per_pixel = drm_format_plane_cpp(fourcc, 0) * 8;
8707
8708         if (INTEL_GEN(dev_priv) >= 4) {
8709                 if (plane_config->tiling)
8710                         offset = I915_READ(DSPTILEOFF(plane));
8711                 else
8712                         offset = I915_READ(DSPLINOFF(plane));
8713                 base = I915_READ(DSPSURF(plane)) & 0xfffff000;
8714         } else {
8715                 base = I915_READ(DSPADDR(plane));
8716         }
8717         plane_config->base = base;
8718
8719         val = I915_READ(PIPESRC(pipe));
8720         fb->width = ((val >> 16) & 0xfff) + 1;
8721         fb->height = ((val >> 0) & 0xfff) + 1;
8722
8723         val = I915_READ(DSPSTRIDE(pipe));
8724         fb->pitches[0] = val & 0xffffffc0;
8725
8726         aligned_height = intel_fb_align_height(dev, fb->height,
8727                                                fb->pixel_format,
8728                                                fb->modifier);
8729
8730         plane_config->size = fb->pitches[0] * aligned_height;
8731
8732         DRM_DEBUG_KMS("pipe/plane %c/%d with fb: size=%dx%d@%d, offset=%x, pitch %d, size 0x%x\n",
8733                       pipe_name(pipe), plane, fb->width, fb->height,
8734                       fb->bits_per_pixel, base, fb->pitches[0],
8735                       plane_config->size);
8736
8737         plane_config->fb = intel_fb;
8738 }
8739
8740 static void chv_crtc_clock_get(struct intel_crtc *crtc,
8741                                struct intel_crtc_state *pipe_config)
8742 {
8743         struct drm_device *dev = crtc->base.dev;
8744         struct drm_i915_private *dev_priv = to_i915(dev);
8745         int pipe = pipe_config->cpu_transcoder;
8746         enum dpio_channel port = vlv_pipe_to_channel(pipe);
8747         struct dpll clock;
8748         u32 cmn_dw13, pll_dw0, pll_dw1, pll_dw2, pll_dw3;
8749         int refclk = 100000;
8750
8751         /* In case of DSI, DPLL will not be used */
8752         if ((pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE) == 0)
8753                 return;
8754
8755         mutex_lock(&dev_priv->sb_lock);
8756         cmn_dw13 = vlv_dpio_read(dev_priv, pipe, CHV_CMN_DW13(port));
8757         pll_dw0 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW0(port));
8758         pll_dw1 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW1(port));
8759         pll_dw2 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW2(port));
8760         pll_dw3 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW3(port));
8761         mutex_unlock(&dev_priv->sb_lock);
8762
8763         clock.m1 = (pll_dw1 & 0x7) == DPIO_CHV_M1_DIV_BY_2 ? 2 : 0;
8764         clock.m2 = (pll_dw0 & 0xff) << 22;
8765         if (pll_dw3 & DPIO_CHV_FRAC_DIV_EN)
8766                 clock.m2 |= pll_dw2 & 0x3fffff;
8767         clock.n = (pll_dw1 >> DPIO_CHV_N_DIV_SHIFT) & 0xf;
8768         clock.p1 = (cmn_dw13 >> DPIO_CHV_P1_DIV_SHIFT) & 0x7;
8769         clock.p2 = (cmn_dw13 >> DPIO_CHV_P2_DIV_SHIFT) & 0x1f;
8770
8771         pipe_config->port_clock = chv_calc_dpll_params(refclk, &clock);
8772 }
8773
8774 static bool i9xx_get_pipe_config(struct intel_crtc *crtc,
8775                                  struct intel_crtc_state *pipe_config)
8776 {
8777         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
8778         enum intel_display_power_domain power_domain;
8779         uint32_t tmp;
8780         bool ret;
8781
8782         power_domain = POWER_DOMAIN_PIPE(crtc->pipe);
8783         if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
8784                 return false;
8785
8786         pipe_config->cpu_transcoder = (enum transcoder) crtc->pipe;
8787         pipe_config->shared_dpll = NULL;
8788
8789         ret = false;
8790
8791         tmp = I915_READ(PIPECONF(crtc->pipe));
8792         if (!(tmp & PIPECONF_ENABLE))
8793                 goto out;
8794
8795         if (IS_G4X(dev_priv) || IS_VALLEYVIEW(dev_priv) ||
8796             IS_CHERRYVIEW(dev_priv)) {
8797                 switch (tmp & PIPECONF_BPC_MASK) {
8798                 case PIPECONF_6BPC:
8799                         pipe_config->pipe_bpp = 18;
8800                         break;
8801                 case PIPECONF_8BPC:
8802                         pipe_config->pipe_bpp = 24;
8803                         break;
8804                 case PIPECONF_10BPC:
8805                         pipe_config->pipe_bpp = 30;
8806                         break;
8807                 default:
8808                         break;
8809                 }
8810         }
8811
8812         if ((IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv)) &&
8813             (tmp & PIPECONF_COLOR_RANGE_SELECT))
8814                 pipe_config->limited_color_range = true;
8815
8816         if (INTEL_GEN(dev_priv) < 4)
8817                 pipe_config->double_wide = tmp & PIPECONF_DOUBLE_WIDE;
8818
8819         intel_get_pipe_timings(crtc, pipe_config);
8820         intel_get_pipe_src_size(crtc, pipe_config);
8821
8822         i9xx_get_pfit_config(crtc, pipe_config);
8823
8824         if (INTEL_GEN(dev_priv) >= 4) {
8825                 /* No way to read it out on pipes B and C */
8826                 if (IS_CHERRYVIEW(dev_priv) && crtc->pipe != PIPE_A)
8827                         tmp = dev_priv->chv_dpll_md[crtc->pipe];
8828                 else
8829                         tmp = I915_READ(DPLL_MD(crtc->pipe));
8830                 pipe_config->pixel_multiplier =
8831                         ((tmp & DPLL_MD_UDI_MULTIPLIER_MASK)
8832                          >> DPLL_MD_UDI_MULTIPLIER_SHIFT) + 1;
8833                 pipe_config->dpll_hw_state.dpll_md = tmp;
8834         } else if (IS_I945G(dev_priv) || IS_I945GM(dev_priv) ||
8835                    IS_G33(dev_priv)) {
8836                 tmp = I915_READ(DPLL(crtc->pipe));
8837                 pipe_config->pixel_multiplier =
8838                         ((tmp & SDVO_MULTIPLIER_MASK)
8839                          >> SDVO_MULTIPLIER_SHIFT_HIRES) + 1;
8840         } else {
8841                 /* Note that on i915G/GM the pixel multiplier is in the sdvo
8842                  * port and will be fixed up in the encoder->get_config
8843                  * function. */
8844                 pipe_config->pixel_multiplier = 1;
8845         }
8846         pipe_config->dpll_hw_state.dpll = I915_READ(DPLL(crtc->pipe));
8847         if (!IS_VALLEYVIEW(dev_priv) && !IS_CHERRYVIEW(dev_priv)) {
8848                 /*
8849                  * DPLL_DVO_2X_MODE must be enabled for both DPLLs
8850                  * on 830. Filter it out here so that we don't
8851                  * report errors due to that.
8852                  */
8853                 if (IS_I830(dev_priv))
8854                         pipe_config->dpll_hw_state.dpll &= ~DPLL_DVO_2X_MODE;
8855
8856                 pipe_config->dpll_hw_state.fp0 = I915_READ(FP0(crtc->pipe));
8857                 pipe_config->dpll_hw_state.fp1 = I915_READ(FP1(crtc->pipe));
8858         } else {
8859                 /* Mask out read-only status bits. */
8860                 pipe_config->dpll_hw_state.dpll &= ~(DPLL_LOCK_VLV |
8861                                                      DPLL_PORTC_READY_MASK |
8862                                                      DPLL_PORTB_READY_MASK);
8863         }
8864
8865         if (IS_CHERRYVIEW(dev_priv))
8866                 chv_crtc_clock_get(crtc, pipe_config);
8867         else if (IS_VALLEYVIEW(dev_priv))
8868                 vlv_crtc_clock_get(crtc, pipe_config);
8869         else
8870                 i9xx_crtc_clock_get(crtc, pipe_config);
8871
8872         /*
8873          * Normally the dotclock is filled in by the encoder .get_config()
8874          * but in case the pipe is enabled w/o any ports we need a sane
8875          * default.
8876          */
8877         pipe_config->base.adjusted_mode.crtc_clock =
8878                 pipe_config->port_clock / pipe_config->pixel_multiplier;
8879
8880         ret = true;
8881
8882 out:
8883         intel_display_power_put(dev_priv, power_domain);
8884
8885         return ret;
8886 }
8887
8888 static void ironlake_init_pch_refclk(struct drm_device *dev)
8889 {
8890         struct drm_i915_private *dev_priv = to_i915(dev);
8891         struct intel_encoder *encoder;
8892         int i;
8893         u32 val, final;
8894         bool has_lvds = false;
8895         bool has_cpu_edp = false;
8896         bool has_panel = false;
8897         bool has_ck505 = false;
8898         bool can_ssc = false;
8899         bool using_ssc_source = false;
8900
8901         /* We need to take the global config into account */
8902         for_each_intel_encoder(dev, encoder) {
8903                 switch (encoder->type) {
8904                 case INTEL_OUTPUT_LVDS:
8905                         has_panel = true;
8906                         has_lvds = true;
8907                         break;
8908                 case INTEL_OUTPUT_EDP:
8909                         has_panel = true;
8910                         if (enc_to_dig_port(&encoder->base)->port == PORT_A)
8911                                 has_cpu_edp = true;
8912                         break;
8913                 default:
8914                         break;
8915                 }
8916         }
8917
8918         if (HAS_PCH_IBX(dev_priv)) {
8919                 has_ck505 = dev_priv->vbt.display_clock_mode;
8920                 can_ssc = has_ck505;
8921         } else {
8922                 has_ck505 = false;
8923                 can_ssc = true;
8924         }
8925
8926         /* Check if any DPLLs are using the SSC source */
8927         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
8928                 u32 temp = I915_READ(PCH_DPLL(i));
8929
8930                 if (!(temp & DPLL_VCO_ENABLE))
8931                         continue;
8932
8933                 if ((temp & PLL_REF_INPUT_MASK) ==
8934                     PLLB_REF_INPUT_SPREADSPECTRUMIN) {
8935                         using_ssc_source = true;
8936                         break;
8937                 }
8938         }
8939
8940         DRM_DEBUG_KMS("has_panel %d has_lvds %d has_ck505 %d using_ssc_source %d\n",
8941                       has_panel, has_lvds, has_ck505, using_ssc_source);
8942
8943         /* Ironlake: try to setup display ref clock before DPLL
8944          * enabling. This is only under driver's control after
8945          * PCH B stepping, previous chipset stepping should be
8946          * ignoring this setting.
8947          */
8948         val = I915_READ(PCH_DREF_CONTROL);
8949
8950         /* As we must carefully and slowly disable/enable each source in turn,
8951          * compute the final state we want first and check if we need to
8952          * make any changes at all.
8953          */
8954         final = val;
8955         final &= ~DREF_NONSPREAD_SOURCE_MASK;
8956         if (has_ck505)
8957                 final |= DREF_NONSPREAD_CK505_ENABLE;
8958         else
8959                 final |= DREF_NONSPREAD_SOURCE_ENABLE;
8960
8961         final &= ~DREF_SSC_SOURCE_MASK;
8962         final &= ~DREF_CPU_SOURCE_OUTPUT_MASK;
8963         final &= ~DREF_SSC1_ENABLE;
8964
8965         if (has_panel) {
8966                 final |= DREF_SSC_SOURCE_ENABLE;
8967
8968                 if (intel_panel_use_ssc(dev_priv) && can_ssc)
8969                         final |= DREF_SSC1_ENABLE;
8970
8971                 if (has_cpu_edp) {
8972                         if (intel_panel_use_ssc(dev_priv) && can_ssc)
8973                                 final |= DREF_CPU_SOURCE_OUTPUT_DOWNSPREAD;
8974                         else
8975                                 final |= DREF_CPU_SOURCE_OUTPUT_NONSPREAD;
8976                 } else
8977                         final |= DREF_CPU_SOURCE_OUTPUT_DISABLE;
8978         } else if (using_ssc_source) {
8979                 final |= DREF_SSC_SOURCE_ENABLE;
8980                 final |= DREF_SSC1_ENABLE;
8981         }
8982
8983         if (final == val)
8984                 return;
8985
8986         /* Always enable nonspread source */
8987         val &= ~DREF_NONSPREAD_SOURCE_MASK;
8988
8989         if (has_ck505)
8990                 val |= DREF_NONSPREAD_CK505_ENABLE;
8991         else
8992                 val |= DREF_NONSPREAD_SOURCE_ENABLE;
8993
8994         if (has_panel) {
8995                 val &= ~DREF_SSC_SOURCE_MASK;
8996                 val |= DREF_SSC_SOURCE_ENABLE;
8997
8998                 /* SSC must be turned on before enabling the CPU output  */
8999                 if (intel_panel_use_ssc(dev_priv) && can_ssc) {
9000                         DRM_DEBUG_KMS("Using SSC on panel\n");
9001                         val |= DREF_SSC1_ENABLE;
9002                 } else
9003                         val &= ~DREF_SSC1_ENABLE;
9004
9005                 /* Get SSC going before enabling the outputs */
9006                 I915_WRITE(PCH_DREF_CONTROL, val);
9007                 POSTING_READ(PCH_DREF_CONTROL);
9008                 udelay(200);
9009
9010                 val &= ~DREF_CPU_SOURCE_OUTPUT_MASK;
9011
9012                 /* Enable CPU source on CPU attached eDP */
9013                 if (has_cpu_edp) {
9014                         if (intel_panel_use_ssc(dev_priv) && can_ssc) {
9015                                 DRM_DEBUG_KMS("Using SSC on eDP\n");
9016                                 val |= DREF_CPU_SOURCE_OUTPUT_DOWNSPREAD;
9017                         } else
9018                                 val |= DREF_CPU_SOURCE_OUTPUT_NONSPREAD;
9019                 } else
9020                         val |= DREF_CPU_SOURCE_OUTPUT_DISABLE;
9021
9022                 I915_WRITE(PCH_DREF_CONTROL, val);
9023                 POSTING_READ(PCH_DREF_CONTROL);
9024                 udelay(200);
9025         } else {
9026                 DRM_DEBUG_KMS("Disabling CPU source output\n");
9027
9028                 val &= ~DREF_CPU_SOURCE_OUTPUT_MASK;
9029
9030                 /* Turn off CPU output */
9031                 val |= DREF_CPU_SOURCE_OUTPUT_DISABLE;
9032
9033                 I915_WRITE(PCH_DREF_CONTROL, val);
9034                 POSTING_READ(PCH_DREF_CONTROL);
9035                 udelay(200);
9036
9037                 if (!using_ssc_source) {
9038                         DRM_DEBUG_KMS("Disabling SSC source\n");
9039
9040                         /* Turn off the SSC source */
9041                         val &= ~DREF_SSC_SOURCE_MASK;
9042                         val |= DREF_SSC_SOURCE_DISABLE;
9043
9044                         /* Turn off SSC1 */
9045                         val &= ~DREF_SSC1_ENABLE;
9046
9047                         I915_WRITE(PCH_DREF_CONTROL, val);
9048                         POSTING_READ(PCH_DREF_CONTROL);
9049                         udelay(200);
9050                 }
9051         }
9052
9053         BUG_ON(val != final);
9054 }
9055
9056 static void lpt_reset_fdi_mphy(struct drm_i915_private *dev_priv)
9057 {
9058         uint32_t tmp;
9059
9060         tmp = I915_READ(SOUTH_CHICKEN2);
9061         tmp |= FDI_MPHY_IOSFSB_RESET_CTL;
9062         I915_WRITE(SOUTH_CHICKEN2, tmp);
9063
9064         if (wait_for_us(I915_READ(SOUTH_CHICKEN2) &
9065                         FDI_MPHY_IOSFSB_RESET_STATUS, 100))
9066                 DRM_ERROR("FDI mPHY reset assert timeout\n");
9067
9068         tmp = I915_READ(SOUTH_CHICKEN2);
9069         tmp &= ~FDI_MPHY_IOSFSB_RESET_CTL;
9070         I915_WRITE(SOUTH_CHICKEN2, tmp);
9071
9072         if (wait_for_us((I915_READ(SOUTH_CHICKEN2) &
9073                          FDI_MPHY_IOSFSB_RESET_STATUS) == 0, 100))
9074                 DRM_ERROR("FDI mPHY reset de-assert timeout\n");
9075 }
9076
9077 /* WaMPhyProgramming:hsw */
9078 static void lpt_program_fdi_mphy(struct drm_i915_private *dev_priv)
9079 {
9080         uint32_t tmp;
9081
9082         tmp = intel_sbi_read(dev_priv, 0x8008, SBI_MPHY);
9083         tmp &= ~(0xFF << 24);
9084         tmp |= (0x12 << 24);
9085         intel_sbi_write(dev_priv, 0x8008, tmp, SBI_MPHY);
9086
9087         tmp = intel_sbi_read(dev_priv, 0x2008, SBI_MPHY);
9088         tmp |= (1 << 11);
9089         intel_sbi_write(dev_priv, 0x2008, tmp, SBI_MPHY);
9090
9091         tmp = intel_sbi_read(dev_priv, 0x2108, SBI_MPHY);
9092         tmp |= (1 << 11);
9093         intel_sbi_write(dev_priv, 0x2108, tmp, SBI_MPHY);
9094
9095         tmp = intel_sbi_read(dev_priv, 0x206C, SBI_MPHY);
9096         tmp |= (1 << 24) | (1 << 21) | (1 << 18);
9097         intel_sbi_write(dev_priv, 0x206C, tmp, SBI_MPHY);
9098
9099         tmp = intel_sbi_read(dev_priv, 0x216C, SBI_MPHY);
9100         tmp |= (1 << 24) | (1 << 21) | (1 << 18);
9101         intel_sbi_write(dev_priv, 0x216C, tmp, SBI_MPHY);
9102
9103         tmp = intel_sbi_read(dev_priv, 0x2080, SBI_MPHY);
9104         tmp &= ~(7 << 13);
9105         tmp |= (5 << 13);
9106         intel_sbi_write(dev_priv, 0x2080, tmp, SBI_MPHY);
9107
9108         tmp = intel_sbi_read(dev_priv, 0x2180, SBI_MPHY);
9109         tmp &= ~(7 << 13);
9110         tmp |= (5 << 13);
9111         intel_sbi_write(dev_priv, 0x2180, tmp, SBI_MPHY);
9112
9113         tmp = intel_sbi_read(dev_priv, 0x208C, SBI_MPHY);
9114         tmp &= ~0xFF;
9115         tmp |= 0x1C;
9116         intel_sbi_write(dev_priv, 0x208C, tmp, SBI_MPHY);
9117
9118         tmp = intel_sbi_read(dev_priv, 0x218C, SBI_MPHY);
9119         tmp &= ~0xFF;
9120         tmp |= 0x1C;
9121         intel_sbi_write(dev_priv, 0x218C, tmp, SBI_MPHY);
9122
9123         tmp = intel_sbi_read(dev_priv, 0x2098, SBI_MPHY);
9124         tmp &= ~(0xFF << 16);
9125         tmp |= (0x1C << 16);
9126         intel_sbi_write(dev_priv, 0x2098, tmp, SBI_MPHY);
9127
9128         tmp = intel_sbi_read(dev_priv, 0x2198, SBI_MPHY);
9129         tmp &= ~(0xFF << 16);
9130         tmp |= (0x1C << 16);
9131         intel_sbi_write(dev_priv, 0x2198, tmp, SBI_MPHY);
9132
9133         tmp = intel_sbi_read(dev_priv, 0x20C4, SBI_MPHY);
9134         tmp |= (1 << 27);
9135         intel_sbi_write(dev_priv, 0x20C4, tmp, SBI_MPHY);
9136
9137         tmp = intel_sbi_read(dev_priv, 0x21C4, SBI_MPHY);
9138         tmp |= (1 << 27);
9139         intel_sbi_write(dev_priv, 0x21C4, tmp, SBI_MPHY);
9140
9141         tmp = intel_sbi_read(dev_priv, 0x20EC, SBI_MPHY);
9142         tmp &= ~(0xF << 28);
9143         tmp |= (4 << 28);
9144         intel_sbi_write(dev_priv, 0x20EC, tmp, SBI_MPHY);
9145
9146         tmp = intel_sbi_read(dev_priv, 0x21EC, SBI_MPHY);
9147         tmp &= ~(0xF << 28);
9148         tmp |= (4 << 28);
9149         intel_sbi_write(dev_priv, 0x21EC, tmp, SBI_MPHY);
9150 }
9151
9152 /* Implements 3 different sequences from BSpec chapter "Display iCLK
9153  * Programming" based on the parameters passed:
9154  * - Sequence to enable CLKOUT_DP
9155  * - Sequence to enable CLKOUT_DP without spread
9156  * - Sequence to enable CLKOUT_DP for FDI usage and configure PCH FDI I/O
9157  */
9158 static void lpt_enable_clkout_dp(struct drm_device *dev, bool with_spread,
9159                                  bool with_fdi)
9160 {
9161         struct drm_i915_private *dev_priv = to_i915(dev);
9162         uint32_t reg, tmp;
9163
9164         if (WARN(with_fdi && !with_spread, "FDI requires downspread\n"))
9165                 with_spread = true;
9166         if (WARN(HAS_PCH_LPT_LP(dev_priv) &&
9167             with_fdi, "LP PCH doesn't have FDI\n"))
9168                 with_fdi = false;
9169
9170         mutex_lock(&dev_priv->sb_lock);
9171
9172         tmp = intel_sbi_read(dev_priv, SBI_SSCCTL, SBI_ICLK);
9173         tmp &= ~SBI_SSCCTL_DISABLE;
9174         tmp |= SBI_SSCCTL_PATHALT;
9175         intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
9176
9177         udelay(24);
9178
9179         if (with_spread) {
9180                 tmp = intel_sbi_read(dev_priv, SBI_SSCCTL, SBI_ICLK);
9181                 tmp &= ~SBI_SSCCTL_PATHALT;
9182                 intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
9183
9184                 if (with_fdi) {
9185                         lpt_reset_fdi_mphy(dev_priv);
9186                         lpt_program_fdi_mphy(dev_priv);
9187                 }
9188         }
9189
9190         reg = HAS_PCH_LPT_LP(dev_priv) ? SBI_GEN0 : SBI_DBUFF0;
9191         tmp = intel_sbi_read(dev_priv, reg, SBI_ICLK);
9192         tmp |= SBI_GEN0_CFG_BUFFENABLE_DISABLE;
9193         intel_sbi_write(dev_priv, reg, tmp, SBI_ICLK);
9194
9195         mutex_unlock(&dev_priv->sb_lock);
9196 }
9197
9198 /* Sequence to disable CLKOUT_DP */
9199 static void lpt_disable_clkout_dp(struct drm_device *dev)
9200 {
9201         struct drm_i915_private *dev_priv = to_i915(dev);
9202         uint32_t reg, tmp;
9203
9204         mutex_lock(&dev_priv->sb_lock);
9205
9206         reg = HAS_PCH_LPT_LP(dev_priv) ? SBI_GEN0 : SBI_DBUFF0;
9207         tmp = intel_sbi_read(dev_priv, reg, SBI_ICLK);
9208         tmp &= ~SBI_GEN0_CFG_BUFFENABLE_DISABLE;
9209         intel_sbi_write(dev_priv, reg, tmp, SBI_ICLK);
9210
9211         tmp = intel_sbi_read(dev_priv, SBI_SSCCTL, SBI_ICLK);
9212         if (!(tmp & SBI_SSCCTL_DISABLE)) {
9213                 if (!(tmp & SBI_SSCCTL_PATHALT)) {
9214                         tmp |= SBI_SSCCTL_PATHALT;
9215                         intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
9216                         udelay(32);
9217                 }
9218                 tmp |= SBI_SSCCTL_DISABLE;
9219                 intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
9220         }
9221
9222         mutex_unlock(&dev_priv->sb_lock);
9223 }
9224
9225 #define BEND_IDX(steps) ((50 + (steps)) / 5)
9226
9227 static const uint16_t sscdivintphase[] = {
9228         [BEND_IDX( 50)] = 0x3B23,
9229         [BEND_IDX( 45)] = 0x3B23,
9230         [BEND_IDX( 40)] = 0x3C23,
9231         [BEND_IDX( 35)] = 0x3C23,
9232         [BEND_IDX( 30)] = 0x3D23,
9233         [BEND_IDX( 25)] = 0x3D23,
9234         [BEND_IDX( 20)] = 0x3E23,
9235         [BEND_IDX( 15)] = 0x3E23,
9236         [BEND_IDX( 10)] = 0x3F23,
9237         [BEND_IDX(  5)] = 0x3F23,
9238         [BEND_IDX(  0)] = 0x0025,
9239         [BEND_IDX( -5)] = 0x0025,
9240         [BEND_IDX(-10)] = 0x0125,
9241         [BEND_IDX(-15)] = 0x0125,
9242         [BEND_IDX(-20)] = 0x0225,
9243         [BEND_IDX(-25)] = 0x0225,
9244         [BEND_IDX(-30)] = 0x0325,
9245         [BEND_IDX(-35)] = 0x0325,
9246         [BEND_IDX(-40)] = 0x0425,
9247         [BEND_IDX(-45)] = 0x0425,
9248         [BEND_IDX(-50)] = 0x0525,
9249 };
9250
9251 /*
9252  * Bend CLKOUT_DP
9253  * steps -50 to 50 inclusive, in steps of 5
9254  * < 0 slow down the clock, > 0 speed up the clock, 0 == no bend (135MHz)
9255  * change in clock period = -(steps / 10) * 5.787 ps
9256  */
9257 static void lpt_bend_clkout_dp(struct drm_i915_private *dev_priv, int steps)
9258 {
9259         uint32_t tmp;
9260         int idx = BEND_IDX(steps);
9261
9262         if (WARN_ON(steps % 5 != 0))
9263                 return;
9264
9265         if (WARN_ON(idx >= ARRAY_SIZE(sscdivintphase)))
9266                 return;
9267
9268         mutex_lock(&dev_priv->sb_lock);
9269
9270         if (steps % 10 != 0)
9271                 tmp = 0xAAAAAAAB;
9272         else
9273                 tmp = 0x00000000;
9274         intel_sbi_write(dev_priv, SBI_SSCDITHPHASE, tmp, SBI_ICLK);
9275
9276         tmp = intel_sbi_read(dev_priv, SBI_SSCDIVINTPHASE, SBI_ICLK);
9277         tmp &= 0xffff0000;
9278         tmp |= sscdivintphase[idx];
9279         intel_sbi_write(dev_priv, SBI_SSCDIVINTPHASE, tmp, SBI_ICLK);
9280
9281         mutex_unlock(&dev_priv->sb_lock);
9282 }
9283
9284 #undef BEND_IDX
9285
9286 static void lpt_init_pch_refclk(struct drm_device *dev)
9287 {
9288         struct intel_encoder *encoder;
9289         bool has_vga = false;
9290
9291         for_each_intel_encoder(dev, encoder) {
9292                 switch (encoder->type) {
9293                 case INTEL_OUTPUT_ANALOG:
9294                         has_vga = true;
9295                         break;
9296                 default:
9297                         break;
9298                 }
9299         }
9300
9301         if (has_vga) {
9302                 lpt_bend_clkout_dp(to_i915(dev), 0);
9303                 lpt_enable_clkout_dp(dev, true, true);
9304         } else {
9305                 lpt_disable_clkout_dp(dev);
9306         }
9307 }
9308
9309 /*
9310  * Initialize reference clocks when the driver loads
9311  */
9312 void intel_init_pch_refclk(struct drm_device *dev)
9313 {
9314         struct drm_i915_private *dev_priv = to_i915(dev);
9315
9316         if (HAS_PCH_IBX(dev_priv) || HAS_PCH_CPT(dev_priv))
9317                 ironlake_init_pch_refclk(dev);
9318         else if (HAS_PCH_LPT(dev_priv))
9319                 lpt_init_pch_refclk(dev);
9320 }
9321
9322 static void ironlake_set_pipeconf(struct drm_crtc *crtc)
9323 {
9324         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
9325         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
9326         int pipe = intel_crtc->pipe;
9327         uint32_t val;
9328
9329         val = 0;
9330
9331         switch (intel_crtc->config->pipe_bpp) {
9332         case 18:
9333                 val |= PIPECONF_6BPC;
9334                 break;
9335         case 24:
9336                 val |= PIPECONF_8BPC;
9337                 break;
9338         case 30:
9339                 val |= PIPECONF_10BPC;
9340                 break;
9341         case 36:
9342                 val |= PIPECONF_12BPC;
9343                 break;
9344         default:
9345                 /* Case prevented by intel_choose_pipe_bpp_dither. */
9346                 BUG();
9347         }
9348
9349         if (intel_crtc->config->dither)
9350                 val |= (PIPECONF_DITHER_EN | PIPECONF_DITHER_TYPE_SP);
9351
9352         if (intel_crtc->config->base.adjusted_mode.flags & DRM_MODE_FLAG_INTERLACE)
9353                 val |= PIPECONF_INTERLACED_ILK;
9354         else
9355                 val |= PIPECONF_PROGRESSIVE;
9356
9357         if (intel_crtc->config->limited_color_range)
9358                 val |= PIPECONF_COLOR_RANGE_SELECT;
9359
9360         I915_WRITE(PIPECONF(pipe), val);
9361         POSTING_READ(PIPECONF(pipe));
9362 }
9363
9364 static void haswell_set_pipeconf(struct drm_crtc *crtc)
9365 {
9366         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
9367         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
9368         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
9369         u32 val = 0;
9370
9371         if (IS_HASWELL(dev_priv) && intel_crtc->config->dither)
9372                 val |= (PIPECONF_DITHER_EN | PIPECONF_DITHER_TYPE_SP);
9373
9374         if (intel_crtc->config->base.adjusted_mode.flags & DRM_MODE_FLAG_INTERLACE)
9375                 val |= PIPECONF_INTERLACED_ILK;
9376         else
9377                 val |= PIPECONF_PROGRESSIVE;
9378
9379         I915_WRITE(PIPECONF(cpu_transcoder), val);
9380         POSTING_READ(PIPECONF(cpu_transcoder));
9381 }
9382
9383 static void haswell_set_pipemisc(struct drm_crtc *crtc)
9384 {
9385         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
9386         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
9387
9388         if (IS_BROADWELL(dev_priv) || INTEL_INFO(dev_priv)->gen >= 9) {
9389                 u32 val = 0;
9390
9391                 switch (intel_crtc->config->pipe_bpp) {
9392                 case 18:
9393                         val |= PIPEMISC_DITHER_6_BPC;
9394                         break;
9395                 case 24:
9396                         val |= PIPEMISC_DITHER_8_BPC;
9397                         break;
9398                 case 30:
9399                         val |= PIPEMISC_DITHER_10_BPC;
9400                         break;
9401                 case 36:
9402                         val |= PIPEMISC_DITHER_12_BPC;
9403                         break;
9404                 default:
9405                         /* Case prevented by pipe_config_set_bpp. */
9406                         BUG();
9407                 }
9408
9409                 if (intel_crtc->config->dither)
9410                         val |= PIPEMISC_DITHER_ENABLE | PIPEMISC_DITHER_TYPE_SP;
9411
9412                 I915_WRITE(PIPEMISC(intel_crtc->pipe), val);
9413         }
9414 }
9415
9416 int ironlake_get_lanes_required(int target_clock, int link_bw, int bpp)
9417 {
9418         /*
9419          * Account for spread spectrum to avoid
9420          * oversubscribing the link. Max center spread
9421          * is 2.5%; use 5% for safety's sake.
9422          */
9423         u32 bps = target_clock * bpp * 21 / 20;
9424         return DIV_ROUND_UP(bps, link_bw * 8);
9425 }
9426
9427 static bool ironlake_needs_fb_cb_tune(struct dpll *dpll, int factor)
9428 {
9429         return i9xx_dpll_compute_m(dpll) < factor * dpll->n;
9430 }
9431
9432 static void ironlake_compute_dpll(struct intel_crtc *intel_crtc,
9433                                   struct intel_crtc_state *crtc_state,
9434                                   struct dpll *reduced_clock)
9435 {
9436         struct drm_crtc *crtc = &intel_crtc->base;
9437         struct drm_device *dev = crtc->dev;
9438         struct drm_i915_private *dev_priv = to_i915(dev);
9439         u32 dpll, fp, fp2;
9440         int factor;
9441
9442         /* Enable autotuning of the PLL clock (if permissible) */
9443         factor = 21;
9444         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
9445                 if ((intel_panel_use_ssc(dev_priv) &&
9446                      dev_priv->vbt.lvds_ssc_freq == 100000) ||
9447                     (HAS_PCH_IBX(dev_priv) && intel_is_dual_link_lvds(dev)))
9448                         factor = 25;
9449         } else if (crtc_state->sdvo_tv_clock)
9450                 factor = 20;
9451
9452         fp = i9xx_dpll_compute_fp(&crtc_state->dpll);
9453
9454         if (ironlake_needs_fb_cb_tune(&crtc_state->dpll, factor))
9455                 fp |= FP_CB_TUNE;
9456
9457         if (reduced_clock) {
9458                 fp2 = i9xx_dpll_compute_fp(reduced_clock);
9459
9460                 if (reduced_clock->m < factor * reduced_clock->n)
9461                         fp2 |= FP_CB_TUNE;
9462         } else {
9463                 fp2 = fp;
9464         }
9465
9466         dpll = 0;
9467
9468         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS))
9469                 dpll |= DPLLB_MODE_LVDS;
9470         else
9471                 dpll |= DPLLB_MODE_DAC_SERIAL;
9472
9473         dpll |= (crtc_state->pixel_multiplier - 1)
9474                 << PLL_REF_SDVO_HDMI_MULTIPLIER_SHIFT;
9475
9476         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_SDVO) ||
9477             intel_crtc_has_type(crtc_state, INTEL_OUTPUT_HDMI))
9478                 dpll |= DPLL_SDVO_HIGH_SPEED;
9479
9480         if (intel_crtc_has_dp_encoder(crtc_state))
9481                 dpll |= DPLL_SDVO_HIGH_SPEED;
9482
9483         /*
9484          * The high speed IO clock is only really required for
9485          * SDVO/HDMI/DP, but we also enable it for CRT to make it
9486          * possible to share the DPLL between CRT and HDMI. Enabling
9487          * the clock needlessly does no real harm, except use up a
9488          * bit of power potentially.
9489          *
9490          * We'll limit this to IVB with 3 pipes, since it has only two
9491          * DPLLs and so DPLL sharing is the only way to get three pipes
9492          * driving PCH ports at the same time. On SNB we could do this,
9493          * and potentially avoid enabling the second DPLL, but it's not
9494          * clear if it''s a win or loss power wise. No point in doing
9495          * this on ILK at all since it has a fixed DPLL<->pipe mapping.
9496          */
9497         if (INTEL_INFO(dev_priv)->num_pipes == 3 &&
9498             intel_crtc_has_type(crtc_state, INTEL_OUTPUT_ANALOG))
9499                 dpll |= DPLL_SDVO_HIGH_SPEED;
9500
9501         /* compute bitmask from p1 value */
9502         dpll |= (1 << (crtc_state->dpll.p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT;
9503         /* also FPA1 */
9504         dpll |= (1 << (crtc_state->dpll.p1 - 1)) << DPLL_FPA1_P1_POST_DIV_SHIFT;
9505
9506         switch (crtc_state->dpll.p2) {
9507         case 5:
9508                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_5;
9509                 break;
9510         case 7:
9511                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_7;
9512                 break;
9513         case 10:
9514                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_10;
9515                 break;
9516         case 14:
9517                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_14;
9518                 break;
9519         }
9520
9521         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS) &&
9522             intel_panel_use_ssc(dev_priv))
9523                 dpll |= PLLB_REF_INPUT_SPREADSPECTRUMIN;
9524         else
9525                 dpll |= PLL_REF_INPUT_DREFCLK;
9526
9527         dpll |= DPLL_VCO_ENABLE;
9528
9529         crtc_state->dpll_hw_state.dpll = dpll;
9530         crtc_state->dpll_hw_state.fp0 = fp;
9531         crtc_state->dpll_hw_state.fp1 = fp2;
9532 }
9533
9534 static int ironlake_crtc_compute_clock(struct intel_crtc *crtc,
9535                                        struct intel_crtc_state *crtc_state)
9536 {
9537         struct drm_device *dev = crtc->base.dev;
9538         struct drm_i915_private *dev_priv = to_i915(dev);
9539         struct dpll reduced_clock;
9540         bool has_reduced_clock = false;
9541         struct intel_shared_dpll *pll;
9542         const struct intel_limit *limit;
9543         int refclk = 120000;
9544
9545         memset(&crtc_state->dpll_hw_state, 0,
9546                sizeof(crtc_state->dpll_hw_state));
9547
9548         crtc->lowfreq_avail = false;
9549
9550         /* CPU eDP is the only output that doesn't need a PCH PLL of its own. */
9551         if (!crtc_state->has_pch_encoder)
9552                 return 0;
9553
9554         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
9555                 if (intel_panel_use_ssc(dev_priv)) {
9556                         DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n",
9557                                       dev_priv->vbt.lvds_ssc_freq);
9558                         refclk = dev_priv->vbt.lvds_ssc_freq;
9559                 }
9560
9561                 if (intel_is_dual_link_lvds(dev)) {
9562                         if (refclk == 100000)
9563                                 limit = &intel_limits_ironlake_dual_lvds_100m;
9564                         else
9565                                 limit = &intel_limits_ironlake_dual_lvds;
9566                 } else {
9567                         if (refclk == 100000)
9568                                 limit = &intel_limits_ironlake_single_lvds_100m;
9569                         else
9570                                 limit = &intel_limits_ironlake_single_lvds;
9571                 }
9572         } else {
9573                 limit = &intel_limits_ironlake_dac;
9574         }
9575
9576         if (!crtc_state->clock_set &&
9577             !g4x_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
9578                                 refclk, NULL, &crtc_state->dpll)) {
9579                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
9580                 return -EINVAL;
9581         }
9582
9583         ironlake_compute_dpll(crtc, crtc_state,
9584                               has_reduced_clock ? &reduced_clock : NULL);
9585
9586         pll = intel_get_shared_dpll(crtc, crtc_state, NULL);
9587         if (pll == NULL) {
9588                 DRM_DEBUG_DRIVER("failed to find PLL for pipe %c\n",
9589                                  pipe_name(crtc->pipe));
9590                 return -EINVAL;
9591         }
9592
9593         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS) &&
9594             has_reduced_clock)
9595                 crtc->lowfreq_avail = true;
9596
9597         return 0;
9598 }
9599
9600 static void intel_pch_transcoder_get_m_n(struct intel_crtc *crtc,
9601                                          struct intel_link_m_n *m_n)
9602 {
9603         struct drm_device *dev = crtc->base.dev;
9604         struct drm_i915_private *dev_priv = to_i915(dev);
9605         enum pipe pipe = crtc->pipe;
9606
9607         m_n->link_m = I915_READ(PCH_TRANS_LINK_M1(pipe));
9608         m_n->link_n = I915_READ(PCH_TRANS_LINK_N1(pipe));
9609         m_n->gmch_m = I915_READ(PCH_TRANS_DATA_M1(pipe))
9610                 & ~TU_SIZE_MASK;
9611         m_n->gmch_n = I915_READ(PCH_TRANS_DATA_N1(pipe));
9612         m_n->tu = ((I915_READ(PCH_TRANS_DATA_M1(pipe))
9613                     & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
9614 }
9615
9616 static void intel_cpu_transcoder_get_m_n(struct intel_crtc *crtc,
9617                                          enum transcoder transcoder,
9618                                          struct intel_link_m_n *m_n,
9619                                          struct intel_link_m_n *m2_n2)
9620 {
9621         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
9622         enum pipe pipe = crtc->pipe;
9623
9624         if (INTEL_GEN(dev_priv) >= 5) {
9625                 m_n->link_m = I915_READ(PIPE_LINK_M1(transcoder));
9626                 m_n->link_n = I915_READ(PIPE_LINK_N1(transcoder));
9627                 m_n->gmch_m = I915_READ(PIPE_DATA_M1(transcoder))
9628                         & ~TU_SIZE_MASK;
9629                 m_n->gmch_n = I915_READ(PIPE_DATA_N1(transcoder));
9630                 m_n->tu = ((I915_READ(PIPE_DATA_M1(transcoder))
9631                             & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
9632                 /* Read M2_N2 registers only for gen < 8 (M2_N2 available for
9633                  * gen < 8) and if DRRS is supported (to make sure the
9634                  * registers are not unnecessarily read).
9635                  */
9636                 if (m2_n2 && INTEL_GEN(dev_priv) < 8 &&
9637                         crtc->config->has_drrs) {
9638                         m2_n2->link_m = I915_READ(PIPE_LINK_M2(transcoder));
9639                         m2_n2->link_n = I915_READ(PIPE_LINK_N2(transcoder));
9640                         m2_n2->gmch_m = I915_READ(PIPE_DATA_M2(transcoder))
9641                                         & ~TU_SIZE_MASK;
9642                         m2_n2->gmch_n = I915_READ(PIPE_DATA_N2(transcoder));
9643                         m2_n2->tu = ((I915_READ(PIPE_DATA_M2(transcoder))
9644                                         & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
9645                 }
9646         } else {
9647                 m_n->link_m = I915_READ(PIPE_LINK_M_G4X(pipe));
9648                 m_n->link_n = I915_READ(PIPE_LINK_N_G4X(pipe));
9649                 m_n->gmch_m = I915_READ(PIPE_DATA_M_G4X(pipe))
9650                         & ~TU_SIZE_MASK;
9651                 m_n->gmch_n = I915_READ(PIPE_DATA_N_G4X(pipe));
9652                 m_n->tu = ((I915_READ(PIPE_DATA_M_G4X(pipe))
9653                             & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
9654         }
9655 }
9656
9657 void intel_dp_get_m_n(struct intel_crtc *crtc,
9658                       struct intel_crtc_state *pipe_config)
9659 {
9660         if (pipe_config->has_pch_encoder)
9661                 intel_pch_transcoder_get_m_n(crtc, &pipe_config->dp_m_n);
9662         else
9663                 intel_cpu_transcoder_get_m_n(crtc, pipe_config->cpu_transcoder,
9664                                              &pipe_config->dp_m_n,
9665                                              &pipe_config->dp_m2_n2);
9666 }
9667
9668 static void ironlake_get_fdi_m_n_config(struct intel_crtc *crtc,
9669                                         struct intel_crtc_state *pipe_config)
9670 {
9671         intel_cpu_transcoder_get_m_n(crtc, pipe_config->cpu_transcoder,
9672                                      &pipe_config->fdi_m_n, NULL);
9673 }
9674
9675 static void skylake_get_pfit_config(struct intel_crtc *crtc,
9676                                     struct intel_crtc_state *pipe_config)
9677 {
9678         struct drm_device *dev = crtc->base.dev;
9679         struct drm_i915_private *dev_priv = to_i915(dev);
9680         struct intel_crtc_scaler_state *scaler_state = &pipe_config->scaler_state;
9681         uint32_t ps_ctrl = 0;
9682         int id = -1;
9683         int i;
9684
9685         /* find scaler attached to this pipe */
9686         for (i = 0; i < crtc->num_scalers; i++) {
9687                 ps_ctrl = I915_READ(SKL_PS_CTRL(crtc->pipe, i));
9688                 if (ps_ctrl & PS_SCALER_EN && !(ps_ctrl & PS_PLANE_SEL_MASK)) {
9689                         id = i;
9690                         pipe_config->pch_pfit.enabled = true;
9691                         pipe_config->pch_pfit.pos = I915_READ(SKL_PS_WIN_POS(crtc->pipe, i));
9692                         pipe_config->pch_pfit.size = I915_READ(SKL_PS_WIN_SZ(crtc->pipe, i));
9693                         break;
9694                 }
9695         }
9696
9697         scaler_state->scaler_id = id;
9698         if (id >= 0) {
9699                 scaler_state->scaler_users |= (1 << SKL_CRTC_INDEX);
9700         } else {
9701                 scaler_state->scaler_users &= ~(1 << SKL_CRTC_INDEX);
9702         }
9703 }
9704
9705 static void
9706 skylake_get_initial_plane_config(struct intel_crtc *crtc,
9707                                  struct intel_initial_plane_config *plane_config)
9708 {
9709         struct drm_device *dev = crtc->base.dev;
9710         struct drm_i915_private *dev_priv = to_i915(dev);
9711         u32 val, base, offset, stride_mult, tiling;
9712         int pipe = crtc->pipe;
9713         int fourcc, pixel_format;
9714         unsigned int aligned_height;
9715         struct drm_framebuffer *fb;
9716         struct intel_framebuffer *intel_fb;
9717
9718         intel_fb = kzalloc(sizeof(*intel_fb), GFP_KERNEL);
9719         if (!intel_fb) {
9720                 DRM_DEBUG_KMS("failed to alloc fb\n");
9721                 return;
9722         }
9723
9724         fb = &intel_fb->base;
9725
9726         val = I915_READ(PLANE_CTL(pipe, 0));
9727         if (!(val & PLANE_CTL_ENABLE))
9728                 goto error;
9729
9730         pixel_format = val & PLANE_CTL_FORMAT_MASK;
9731         fourcc = skl_format_to_fourcc(pixel_format,
9732                                       val & PLANE_CTL_ORDER_RGBX,
9733                                       val & PLANE_CTL_ALPHA_MASK);
9734         fb->pixel_format = fourcc;
9735         fb->bits_per_pixel = drm_format_plane_cpp(fourcc, 0) * 8;
9736
9737         tiling = val & PLANE_CTL_TILED_MASK;
9738         switch (tiling) {
9739         case PLANE_CTL_TILED_LINEAR:
9740                 fb->modifier = DRM_FORMAT_MOD_NONE;
9741                 break;
9742         case PLANE_CTL_TILED_X:
9743                 plane_config->tiling = I915_TILING_X;
9744                 fb->modifier = I915_FORMAT_MOD_X_TILED;
9745                 break;
9746         case PLANE_CTL_TILED_Y:
9747                 fb->modifier = I915_FORMAT_MOD_Y_TILED;
9748                 break;
9749         case PLANE_CTL_TILED_YF:
9750                 fb->modifier = I915_FORMAT_MOD_Yf_TILED;
9751                 break;
9752         default:
9753                 MISSING_CASE(tiling);
9754                 goto error;
9755         }
9756
9757         base = I915_READ(PLANE_SURF(pipe, 0)) & 0xfffff000;
9758         plane_config->base = base;
9759
9760         offset = I915_READ(PLANE_OFFSET(pipe, 0));
9761
9762         val = I915_READ(PLANE_SIZE(pipe, 0));
9763         fb->height = ((val >> 16) & 0xfff) + 1;
9764         fb->width = ((val >> 0) & 0x1fff) + 1;
9765
9766         val = I915_READ(PLANE_STRIDE(pipe, 0));
9767         stride_mult = intel_fb_stride_alignment(dev_priv, fb->modifier,
9768                                                 fb->pixel_format);
9769         fb->pitches[0] = (val & 0x3ff) * stride_mult;
9770
9771         aligned_height = intel_fb_align_height(dev, fb->height,
9772                                                fb->pixel_format,
9773                                                fb->modifier);
9774
9775         plane_config->size = fb->pitches[0] * aligned_height;
9776
9777         DRM_DEBUG_KMS("pipe %c with fb: size=%dx%d@%d, offset=%x, pitch %d, size 0x%x\n",
9778                       pipe_name(pipe), fb->width, fb->height,
9779                       fb->bits_per_pixel, base, fb->pitches[0],
9780                       plane_config->size);
9781
9782         plane_config->fb = intel_fb;
9783         return;
9784
9785 error:
9786         kfree(intel_fb);
9787 }
9788
9789 static void ironlake_get_pfit_config(struct intel_crtc *crtc,
9790                                      struct intel_crtc_state *pipe_config)
9791 {
9792         struct drm_device *dev = crtc->base.dev;
9793         struct drm_i915_private *dev_priv = to_i915(dev);
9794         uint32_t tmp;
9795
9796         tmp = I915_READ(PF_CTL(crtc->pipe));
9797
9798         if (tmp & PF_ENABLE) {
9799                 pipe_config->pch_pfit.enabled = true;
9800                 pipe_config->pch_pfit.pos = I915_READ(PF_WIN_POS(crtc->pipe));
9801                 pipe_config->pch_pfit.size = I915_READ(PF_WIN_SZ(crtc->pipe));
9802
9803                 /* We currently do not free assignements of panel fitters on
9804                  * ivb/hsw (since we don't use the higher upscaling modes which
9805                  * differentiates them) so just WARN about this case for now. */
9806                 if (IS_GEN7(dev_priv)) {
9807                         WARN_ON((tmp & PF_PIPE_SEL_MASK_IVB) !=
9808                                 PF_PIPE_SEL_IVB(crtc->pipe));
9809                 }
9810         }
9811 }
9812
9813 static void
9814 ironlake_get_initial_plane_config(struct intel_crtc *crtc,
9815                                   struct intel_initial_plane_config *plane_config)
9816 {
9817         struct drm_device *dev = crtc->base.dev;
9818         struct drm_i915_private *dev_priv = to_i915(dev);
9819         u32 val, base, offset;
9820         int pipe = crtc->pipe;
9821         int fourcc, pixel_format;
9822         unsigned int aligned_height;
9823         struct drm_framebuffer *fb;
9824         struct intel_framebuffer *intel_fb;
9825
9826         val = I915_READ(DSPCNTR(pipe));
9827         if (!(val & DISPLAY_PLANE_ENABLE))
9828                 return;
9829
9830         intel_fb = kzalloc(sizeof(*intel_fb), GFP_KERNEL);
9831         if (!intel_fb) {
9832                 DRM_DEBUG_KMS("failed to alloc fb\n");
9833                 return;
9834         }
9835
9836         fb = &intel_fb->base;
9837
9838         if (INTEL_GEN(dev_priv) >= 4) {
9839                 if (val & DISPPLANE_TILED) {
9840                         plane_config->tiling = I915_TILING_X;
9841                         fb->modifier = I915_FORMAT_MOD_X_TILED;
9842                 }
9843         }
9844
9845         pixel_format = val & DISPPLANE_PIXFORMAT_MASK;
9846         fourcc = i9xx_format_to_fourcc(pixel_format);
9847         fb->pixel_format = fourcc;
9848         fb->bits_per_pixel = drm_format_plane_cpp(fourcc, 0) * 8;
9849
9850         base = I915_READ(DSPSURF(pipe)) & 0xfffff000;
9851         if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv)) {
9852                 offset = I915_READ(DSPOFFSET(pipe));
9853         } else {
9854                 if (plane_config->tiling)
9855                         offset = I915_READ(DSPTILEOFF(pipe));
9856                 else
9857                         offset = I915_READ(DSPLINOFF(pipe));
9858         }
9859         plane_config->base = base;
9860
9861         val = I915_READ(PIPESRC(pipe));
9862         fb->width = ((val >> 16) & 0xfff) + 1;
9863         fb->height = ((val >> 0) & 0xfff) + 1;
9864
9865         val = I915_READ(DSPSTRIDE(pipe));
9866         fb->pitches[0] = val & 0xffffffc0;
9867
9868         aligned_height = intel_fb_align_height(dev, fb->height,
9869                                                fb->pixel_format,
9870                                                fb->modifier);
9871
9872         plane_config->size = fb->pitches[0] * aligned_height;
9873
9874         DRM_DEBUG_KMS("pipe %c with fb: size=%dx%d@%d, offset=%x, pitch %d, size 0x%x\n",
9875                       pipe_name(pipe), fb->width, fb->height,
9876                       fb->bits_per_pixel, base, fb->pitches[0],
9877                       plane_config->size);
9878
9879         plane_config->fb = intel_fb;
9880 }
9881
9882 static bool ironlake_get_pipe_config(struct intel_crtc *crtc,
9883                                      struct intel_crtc_state *pipe_config)
9884 {
9885         struct drm_device *dev = crtc->base.dev;
9886         struct drm_i915_private *dev_priv = to_i915(dev);
9887         enum intel_display_power_domain power_domain;
9888         uint32_t tmp;
9889         bool ret;
9890
9891         power_domain = POWER_DOMAIN_PIPE(crtc->pipe);
9892         if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
9893                 return false;
9894
9895         pipe_config->cpu_transcoder = (enum transcoder) crtc->pipe;
9896         pipe_config->shared_dpll = NULL;
9897
9898         ret = false;
9899         tmp = I915_READ(PIPECONF(crtc->pipe));
9900         if (!(tmp & PIPECONF_ENABLE))
9901                 goto out;
9902
9903         switch (tmp & PIPECONF_BPC_MASK) {
9904         case PIPECONF_6BPC:
9905                 pipe_config->pipe_bpp = 18;
9906                 break;
9907         case PIPECONF_8BPC:
9908                 pipe_config->pipe_bpp = 24;
9909                 break;
9910         case PIPECONF_10BPC:
9911                 pipe_config->pipe_bpp = 30;
9912                 break;
9913         case PIPECONF_12BPC:
9914                 pipe_config->pipe_bpp = 36;
9915                 break;
9916         default:
9917                 break;
9918         }
9919
9920         if (tmp & PIPECONF_COLOR_RANGE_SELECT)
9921                 pipe_config->limited_color_range = true;
9922
9923         if (I915_READ(PCH_TRANSCONF(crtc->pipe)) & TRANS_ENABLE) {
9924                 struct intel_shared_dpll *pll;
9925                 enum intel_dpll_id pll_id;
9926
9927                 pipe_config->has_pch_encoder = true;
9928
9929                 tmp = I915_READ(FDI_RX_CTL(crtc->pipe));
9930                 pipe_config->fdi_lanes = ((FDI_DP_PORT_WIDTH_MASK & tmp) >>
9931                                           FDI_DP_PORT_WIDTH_SHIFT) + 1;
9932
9933                 ironlake_get_fdi_m_n_config(crtc, pipe_config);
9934
9935                 if (HAS_PCH_IBX(dev_priv)) {
9936                         /*
9937                          * The pipe->pch transcoder and pch transcoder->pll
9938                          * mapping is fixed.
9939                          */
9940                         pll_id = (enum intel_dpll_id) crtc->pipe;
9941                 } else {
9942                         tmp = I915_READ(PCH_DPLL_SEL);
9943                         if (tmp & TRANS_DPLLB_SEL(crtc->pipe))
9944                                 pll_id = DPLL_ID_PCH_PLL_B;
9945                         else
9946                                 pll_id= DPLL_ID_PCH_PLL_A;
9947                 }
9948
9949                 pipe_config->shared_dpll =
9950                         intel_get_shared_dpll_by_id(dev_priv, pll_id);
9951                 pll = pipe_config->shared_dpll;
9952
9953                 WARN_ON(!pll->funcs.get_hw_state(dev_priv, pll,
9954                                                  &pipe_config->dpll_hw_state));
9955
9956                 tmp = pipe_config->dpll_hw_state.dpll;
9957                 pipe_config->pixel_multiplier =
9958                         ((tmp & PLL_REF_SDVO_HDMI_MULTIPLIER_MASK)
9959                          >> PLL_REF_SDVO_HDMI_MULTIPLIER_SHIFT) + 1;
9960
9961                 ironlake_pch_clock_get(crtc, pipe_config);
9962         } else {
9963                 pipe_config->pixel_multiplier = 1;
9964         }
9965
9966         intel_get_pipe_timings(crtc, pipe_config);
9967         intel_get_pipe_src_size(crtc, pipe_config);
9968
9969         ironlake_get_pfit_config(crtc, pipe_config);
9970
9971         ret = true;
9972
9973 out:
9974         intel_display_power_put(dev_priv, power_domain);
9975
9976         return ret;
9977 }
9978
9979 static void assert_can_disable_lcpll(struct drm_i915_private *dev_priv)
9980 {
9981         struct drm_device *dev = &dev_priv->drm;
9982         struct intel_crtc *crtc;
9983
9984         for_each_intel_crtc(dev, crtc)
9985                 I915_STATE_WARN(crtc->active, "CRTC for pipe %c enabled\n",
9986                      pipe_name(crtc->pipe));
9987
9988         I915_STATE_WARN(I915_READ(HSW_PWR_WELL_DRIVER), "Power well on\n");
9989         I915_STATE_WARN(I915_READ(SPLL_CTL) & SPLL_PLL_ENABLE, "SPLL enabled\n");
9990         I915_STATE_WARN(I915_READ(WRPLL_CTL(0)) & WRPLL_PLL_ENABLE, "WRPLL1 enabled\n");
9991         I915_STATE_WARN(I915_READ(WRPLL_CTL(1)) & WRPLL_PLL_ENABLE, "WRPLL2 enabled\n");
9992         I915_STATE_WARN(I915_READ(PP_STATUS(0)) & PP_ON, "Panel power on\n");
9993         I915_STATE_WARN(I915_READ(BLC_PWM_CPU_CTL2) & BLM_PWM_ENABLE,
9994              "CPU PWM1 enabled\n");
9995         if (IS_HASWELL(dev_priv))
9996                 I915_STATE_WARN(I915_READ(HSW_BLC_PWM2_CTL) & BLM_PWM_ENABLE,
9997                      "CPU PWM2 enabled\n");
9998         I915_STATE_WARN(I915_READ(BLC_PWM_PCH_CTL1) & BLM_PCH_PWM_ENABLE,
9999              "PCH PWM1 enabled\n");
10000         I915_STATE_WARN(I915_READ(UTIL_PIN_CTL) & UTIL_PIN_ENABLE,
10001              "Utility pin enabled\n");
10002         I915_STATE_WARN(I915_READ(PCH_GTC_CTL) & PCH_GTC_ENABLE, "PCH GTC enabled\n");
10003
10004         /*
10005          * In theory we can still leave IRQs enabled, as long as only the HPD
10006          * interrupts remain enabled. We used to check for that, but since it's
10007          * gen-specific and since we only disable LCPLL after we fully disable
10008          * the interrupts, the check below should be enough.
10009          */
10010         I915_STATE_WARN(intel_irqs_enabled(dev_priv), "IRQs enabled\n");
10011 }
10012
10013 static uint32_t hsw_read_dcomp(struct drm_i915_private *dev_priv)
10014 {
10015         if (IS_HASWELL(dev_priv))
10016                 return I915_READ(D_COMP_HSW);
10017         else
10018                 return I915_READ(D_COMP_BDW);
10019 }
10020
10021 static void hsw_write_dcomp(struct drm_i915_private *dev_priv, uint32_t val)
10022 {
10023         if (IS_HASWELL(dev_priv)) {
10024                 mutex_lock(&dev_priv->rps.hw_lock);
10025                 if (sandybridge_pcode_write(dev_priv, GEN6_PCODE_WRITE_D_COMP,
10026                                             val))
10027                         DRM_DEBUG_KMS("Failed to write to D_COMP\n");
10028                 mutex_unlock(&dev_priv->rps.hw_lock);
10029         } else {
10030                 I915_WRITE(D_COMP_BDW, val);
10031                 POSTING_READ(D_COMP_BDW);
10032         }
10033 }
10034
10035 /*
10036  * This function implements pieces of two sequences from BSpec:
10037  * - Sequence for display software to disable LCPLL
10038  * - Sequence for display software to allow package C8+
10039  * The steps implemented here are just the steps that actually touch the LCPLL
10040  * register. Callers should take care of disabling all the display engine
10041  * functions, doing the mode unset, fixing interrupts, etc.
10042  */
10043 static void hsw_disable_lcpll(struct drm_i915_private *dev_priv,
10044                               bool switch_to_fclk, bool allow_power_down)
10045 {
10046         uint32_t val;
10047
10048         assert_can_disable_lcpll(dev_priv);
10049
10050         val = I915_READ(LCPLL_CTL);
10051
10052         if (switch_to_fclk) {
10053                 val |= LCPLL_CD_SOURCE_FCLK;
10054                 I915_WRITE(LCPLL_CTL, val);
10055
10056                 if (wait_for_us(I915_READ(LCPLL_CTL) &
10057                                 LCPLL_CD_SOURCE_FCLK_DONE, 1))
10058                         DRM_ERROR("Switching to FCLK failed\n");
10059
10060                 val = I915_READ(LCPLL_CTL);
10061         }
10062
10063         val |= LCPLL_PLL_DISABLE;
10064         I915_WRITE(LCPLL_CTL, val);
10065         POSTING_READ(LCPLL_CTL);
10066
10067         if (intel_wait_for_register(dev_priv, LCPLL_CTL, LCPLL_PLL_LOCK, 0, 1))
10068                 DRM_ERROR("LCPLL still locked\n");
10069
10070         val = hsw_read_dcomp(dev_priv);
10071         val |= D_COMP_COMP_DISABLE;
10072         hsw_write_dcomp(dev_priv, val);
10073         ndelay(100);
10074
10075         if (wait_for((hsw_read_dcomp(dev_priv) & D_COMP_RCOMP_IN_PROGRESS) == 0,
10076                      1))
10077                 DRM_ERROR("D_COMP RCOMP still in progress\n");
10078
10079         if (allow_power_down) {
10080                 val = I915_READ(LCPLL_CTL);
10081                 val |= LCPLL_POWER_DOWN_ALLOW;
10082                 I915_WRITE(LCPLL_CTL, val);
10083                 POSTING_READ(LCPLL_CTL);
10084         }
10085 }
10086
10087 /*
10088  * Fully restores LCPLL, disallowing power down and switching back to LCPLL
10089  * source.
10090  */
10091 static void hsw_restore_lcpll(struct drm_i915_private *dev_priv)
10092 {
10093         uint32_t val;
10094
10095         val = I915_READ(LCPLL_CTL);
10096
10097         if ((val & (LCPLL_PLL_LOCK | LCPLL_PLL_DISABLE | LCPLL_CD_SOURCE_FCLK |
10098                     LCPLL_POWER_DOWN_ALLOW)) == LCPLL_PLL_LOCK)
10099                 return;
10100
10101         /*
10102          * Make sure we're not on PC8 state before disabling PC8, otherwise
10103          * we'll hang the machine. To prevent PC8 state, just enable force_wake.
10104          */
10105         intel_uncore_forcewake_get(dev_priv, FORCEWAKE_ALL);
10106
10107         if (val & LCPLL_POWER_DOWN_ALLOW) {
10108                 val &= ~LCPLL_POWER_DOWN_ALLOW;
10109                 I915_WRITE(LCPLL_CTL, val);
10110                 POSTING_READ(LCPLL_CTL);
10111         }
10112
10113         val = hsw_read_dcomp(dev_priv);
10114         val |= D_COMP_COMP_FORCE;
10115         val &= ~D_COMP_COMP_DISABLE;
10116         hsw_write_dcomp(dev_priv, val);
10117
10118         val = I915_READ(LCPLL_CTL);
10119         val &= ~LCPLL_PLL_DISABLE;
10120         I915_WRITE(LCPLL_CTL, val);
10121
10122         if (intel_wait_for_register(dev_priv,
10123                                     LCPLL_CTL, LCPLL_PLL_LOCK, LCPLL_PLL_LOCK,
10124                                     5))
10125                 DRM_ERROR("LCPLL not locked yet\n");
10126
10127         if (val & LCPLL_CD_SOURCE_FCLK) {
10128                 val = I915_READ(LCPLL_CTL);
10129                 val &= ~LCPLL_CD_SOURCE_FCLK;
10130                 I915_WRITE(LCPLL_CTL, val);
10131
10132                 if (wait_for_us((I915_READ(LCPLL_CTL) &
10133                                  LCPLL_CD_SOURCE_FCLK_DONE) == 0, 1))
10134                         DRM_ERROR("Switching back to LCPLL failed\n");
10135         }
10136
10137         intel_uncore_forcewake_put(dev_priv, FORCEWAKE_ALL);
10138         intel_update_cdclk(dev_priv);
10139 }
10140
10141 /*
10142  * Package states C8 and deeper are really deep PC states that can only be
10143  * reached when all the devices on the system allow it, so even if the graphics
10144  * device allows PC8+, it doesn't mean the system will actually get to these
10145  * states. Our driver only allows PC8+ when going into runtime PM.
10146  *
10147  * The requirements for PC8+ are that all the outputs are disabled, the power
10148  * well is disabled and most interrupts are disabled, and these are also
10149  * requirements for runtime PM. When these conditions are met, we manually do
10150  * the other conditions: disable the interrupts, clocks and switch LCPLL refclk
10151  * to Fclk. If we're in PC8+ and we get an non-hotplug interrupt, we can hard
10152  * hang the machine.
10153  *
10154  * When we really reach PC8 or deeper states (not just when we allow it) we lose
10155  * the state of some registers, so when we come back from PC8+ we need to
10156  * restore this state. We don't get into PC8+ if we're not in RC6, so we don't
10157  * need to take care of the registers kept by RC6. Notice that this happens even
10158  * if we don't put the device in PCI D3 state (which is what currently happens
10159  * because of the runtime PM support).
10160  *
10161  * For more, read "Display Sequences for Package C8" on the hardware
10162  * documentation.
10163  */
10164 void hsw_enable_pc8(struct drm_i915_private *dev_priv)
10165 {
10166         struct drm_device *dev = &dev_priv->drm;
10167         uint32_t val;
10168
10169         DRM_DEBUG_KMS("Enabling package C8+\n");
10170
10171         if (HAS_PCH_LPT_LP(dev_priv)) {
10172                 val = I915_READ(SOUTH_DSPCLK_GATE_D);
10173                 val &= ~PCH_LP_PARTITION_LEVEL_DISABLE;
10174                 I915_WRITE(SOUTH_DSPCLK_GATE_D, val);
10175         }
10176
10177         lpt_disable_clkout_dp(dev);
10178         hsw_disable_lcpll(dev_priv, true, true);
10179 }
10180
10181 void hsw_disable_pc8(struct drm_i915_private *dev_priv)
10182 {
10183         struct drm_device *dev = &dev_priv->drm;
10184         uint32_t val;
10185
10186         DRM_DEBUG_KMS("Disabling package C8+\n");
10187
10188         hsw_restore_lcpll(dev_priv);
10189         lpt_init_pch_refclk(dev);
10190
10191         if (HAS_PCH_LPT_LP(dev_priv)) {
10192                 val = I915_READ(SOUTH_DSPCLK_GATE_D);
10193                 val |= PCH_LP_PARTITION_LEVEL_DISABLE;
10194                 I915_WRITE(SOUTH_DSPCLK_GATE_D, val);
10195         }
10196 }
10197
10198 static void bxt_modeset_commit_cdclk(struct drm_atomic_state *old_state)
10199 {
10200         struct drm_device *dev = old_state->dev;
10201         struct intel_atomic_state *old_intel_state =
10202                 to_intel_atomic_state(old_state);
10203         unsigned int req_cdclk = old_intel_state->dev_cdclk;
10204
10205         bxt_set_cdclk(to_i915(dev), req_cdclk);
10206 }
10207
10208 static int bdw_adjust_min_pipe_pixel_rate(struct intel_crtc_state *crtc_state,
10209                                           int pixel_rate)
10210 {
10211         struct drm_i915_private *dev_priv = to_i915(crtc_state->base.crtc->dev);
10212
10213         /* pixel rate mustn't exceed 95% of cdclk with IPS on BDW */
10214         if (IS_BROADWELL(dev_priv) && crtc_state->ips_enabled)
10215                 pixel_rate = DIV_ROUND_UP(pixel_rate * 100, 95);
10216
10217         /* BSpec says "Do not use DisplayPort with CDCLK less than
10218          * 432 MHz, audio enabled, port width x4, and link rate
10219          * HBR2 (5.4 GHz), or else there may be audio corruption or
10220          * screen corruption."
10221          */
10222         if (intel_crtc_has_dp_encoder(crtc_state) &&
10223             crtc_state->has_audio &&
10224             crtc_state->port_clock >= 540000 &&
10225             crtc_state->lane_count == 4)
10226                 pixel_rate = max(432000, pixel_rate);
10227
10228         return pixel_rate;
10229 }
10230
10231 /* compute the max rate for new configuration */
10232 static int ilk_max_pixel_rate(struct drm_atomic_state *state)
10233 {
10234         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
10235         struct drm_i915_private *dev_priv = to_i915(state->dev);
10236         struct drm_crtc *crtc;
10237         struct drm_crtc_state *cstate;
10238         struct intel_crtc_state *crtc_state;
10239         unsigned max_pixel_rate = 0, i;
10240         enum pipe pipe;
10241
10242         memcpy(intel_state->min_pixclk, dev_priv->min_pixclk,
10243                sizeof(intel_state->min_pixclk));
10244
10245         for_each_crtc_in_state(state, crtc, cstate, i) {
10246                 int pixel_rate;
10247
10248                 crtc_state = to_intel_crtc_state(cstate);
10249                 if (!crtc_state->base.enable) {
10250                         intel_state->min_pixclk[i] = 0;
10251                         continue;
10252                 }
10253
10254                 pixel_rate = ilk_pipe_pixel_rate(crtc_state);
10255
10256                 if (IS_BROADWELL(dev_priv) || IS_GEN9(dev_priv))
10257                         pixel_rate = bdw_adjust_min_pipe_pixel_rate(crtc_state,
10258                                                                     pixel_rate);
10259
10260                 intel_state->min_pixclk[i] = pixel_rate;
10261         }
10262
10263         for_each_pipe(dev_priv, pipe)
10264                 max_pixel_rate = max(intel_state->min_pixclk[pipe], max_pixel_rate);
10265
10266         return max_pixel_rate;
10267 }
10268
10269 static void broadwell_set_cdclk(struct drm_device *dev, int cdclk)
10270 {
10271         struct drm_i915_private *dev_priv = to_i915(dev);
10272         uint32_t val, data;
10273         int ret;
10274
10275         if (WARN((I915_READ(LCPLL_CTL) &
10276                   (LCPLL_PLL_DISABLE | LCPLL_PLL_LOCK |
10277                    LCPLL_CD_CLOCK_DISABLE | LCPLL_ROOT_CD_CLOCK_DISABLE |
10278                    LCPLL_CD2X_CLOCK_DISABLE | LCPLL_POWER_DOWN_ALLOW |
10279                    LCPLL_CD_SOURCE_FCLK)) != LCPLL_PLL_LOCK,
10280                  "trying to change cdclk frequency with cdclk not enabled\n"))
10281                 return;
10282
10283         mutex_lock(&dev_priv->rps.hw_lock);
10284         ret = sandybridge_pcode_write(dev_priv,
10285                                       BDW_PCODE_DISPLAY_FREQ_CHANGE_REQ, 0x0);
10286         mutex_unlock(&dev_priv->rps.hw_lock);
10287         if (ret) {
10288                 DRM_ERROR("failed to inform pcode about cdclk change\n");
10289                 return;
10290         }
10291
10292         val = I915_READ(LCPLL_CTL);
10293         val |= LCPLL_CD_SOURCE_FCLK;
10294         I915_WRITE(LCPLL_CTL, val);
10295
10296         if (wait_for_us(I915_READ(LCPLL_CTL) &
10297                         LCPLL_CD_SOURCE_FCLK_DONE, 1))
10298                 DRM_ERROR("Switching to FCLK failed\n");
10299
10300         val = I915_READ(LCPLL_CTL);
10301         val &= ~LCPLL_CLK_FREQ_MASK;
10302
10303         switch (cdclk) {
10304         case 450000:
10305                 val |= LCPLL_CLK_FREQ_450;
10306                 data = 0;
10307                 break;
10308         case 540000:
10309                 val |= LCPLL_CLK_FREQ_54O_BDW;
10310                 data = 1;
10311                 break;
10312         case 337500:
10313                 val |= LCPLL_CLK_FREQ_337_5_BDW;
10314                 data = 2;
10315                 break;
10316         case 675000:
10317                 val |= LCPLL_CLK_FREQ_675_BDW;
10318                 data = 3;
10319                 break;
10320         default:
10321                 WARN(1, "invalid cdclk frequency\n");
10322                 return;
10323         }
10324
10325         I915_WRITE(LCPLL_CTL, val);
10326
10327         val = I915_READ(LCPLL_CTL);
10328         val &= ~LCPLL_CD_SOURCE_FCLK;
10329         I915_WRITE(LCPLL_CTL, val);
10330
10331         if (wait_for_us((I915_READ(LCPLL_CTL) &
10332                         LCPLL_CD_SOURCE_FCLK_DONE) == 0, 1))
10333                 DRM_ERROR("Switching back to LCPLL failed\n");
10334
10335         mutex_lock(&dev_priv->rps.hw_lock);
10336         sandybridge_pcode_write(dev_priv, HSW_PCODE_DE_WRITE_FREQ_REQ, data);
10337         mutex_unlock(&dev_priv->rps.hw_lock);
10338
10339         I915_WRITE(CDCLK_FREQ, DIV_ROUND_CLOSEST(cdclk, 1000) - 1);
10340
10341         intel_update_cdclk(dev_priv);
10342
10343         WARN(cdclk != dev_priv->cdclk_freq,
10344              "cdclk requested %d kHz but got %d kHz\n",
10345              cdclk, dev_priv->cdclk_freq);
10346 }
10347
10348 static int broadwell_calc_cdclk(int max_pixclk)
10349 {
10350         if (max_pixclk > 540000)
10351                 return 675000;
10352         else if (max_pixclk > 450000)
10353                 return 540000;
10354         else if (max_pixclk > 337500)
10355                 return 450000;
10356         else
10357                 return 337500;
10358 }
10359
10360 static int broadwell_modeset_calc_cdclk(struct drm_atomic_state *state)
10361 {
10362         struct drm_i915_private *dev_priv = to_i915(state->dev);
10363         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
10364         int max_pixclk = ilk_max_pixel_rate(state);
10365         int cdclk;
10366
10367         /*
10368          * FIXME should also account for plane ratio
10369          * once 64bpp pixel formats are supported.
10370          */
10371         cdclk = broadwell_calc_cdclk(max_pixclk);
10372
10373         if (cdclk > dev_priv->max_cdclk_freq) {
10374                 DRM_DEBUG_KMS("requested cdclk (%d kHz) exceeds max (%d kHz)\n",
10375                               cdclk, dev_priv->max_cdclk_freq);
10376                 return -EINVAL;
10377         }
10378
10379         intel_state->cdclk = intel_state->dev_cdclk = cdclk;
10380         if (!intel_state->active_crtcs)
10381                 intel_state->dev_cdclk = broadwell_calc_cdclk(0);
10382
10383         return 0;
10384 }
10385
10386 static void broadwell_modeset_commit_cdclk(struct drm_atomic_state *old_state)
10387 {
10388         struct drm_device *dev = old_state->dev;
10389         struct intel_atomic_state *old_intel_state =
10390                 to_intel_atomic_state(old_state);
10391         unsigned req_cdclk = old_intel_state->dev_cdclk;
10392
10393         broadwell_set_cdclk(dev, req_cdclk);
10394 }
10395
10396 static int skl_modeset_calc_cdclk(struct drm_atomic_state *state)
10397 {
10398         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
10399         struct drm_i915_private *dev_priv = to_i915(state->dev);
10400         const int max_pixclk = ilk_max_pixel_rate(state);
10401         int vco = intel_state->cdclk_pll_vco;
10402         int cdclk;
10403
10404         /*
10405          * FIXME should also account for plane ratio
10406          * once 64bpp pixel formats are supported.
10407          */
10408         cdclk = skl_calc_cdclk(max_pixclk, vco);
10409
10410         /*
10411          * FIXME move the cdclk caclulation to
10412          * compute_config() so we can fail gracegully.
10413          */
10414         if (cdclk > dev_priv->max_cdclk_freq) {
10415                 DRM_ERROR("requested cdclk (%d kHz) exceeds max (%d kHz)\n",
10416                           cdclk, dev_priv->max_cdclk_freq);
10417                 cdclk = dev_priv->max_cdclk_freq;
10418         }
10419
10420         intel_state->cdclk = intel_state->dev_cdclk = cdclk;
10421         if (!intel_state->active_crtcs)
10422                 intel_state->dev_cdclk = skl_calc_cdclk(0, vco);
10423
10424         return 0;
10425 }
10426
10427 static void skl_modeset_commit_cdclk(struct drm_atomic_state *old_state)
10428 {
10429         struct drm_i915_private *dev_priv = to_i915(old_state->dev);
10430         struct intel_atomic_state *intel_state = to_intel_atomic_state(old_state);
10431         unsigned int req_cdclk = intel_state->dev_cdclk;
10432         unsigned int req_vco = intel_state->cdclk_pll_vco;
10433
10434         skl_set_cdclk(dev_priv, req_cdclk, req_vco);
10435 }
10436
10437 static int haswell_crtc_compute_clock(struct intel_crtc *crtc,
10438                                       struct intel_crtc_state *crtc_state)
10439 {
10440         if (!intel_crtc_has_type(crtc_state, INTEL_OUTPUT_DSI)) {
10441                 if (!intel_ddi_pll_select(crtc, crtc_state))
10442                         return -EINVAL;
10443         }
10444
10445         crtc->lowfreq_avail = false;
10446
10447         return 0;
10448 }
10449
10450 static void bxt_get_ddi_pll(struct drm_i915_private *dev_priv,
10451                                 enum port port,
10452                                 struct intel_crtc_state *pipe_config)
10453 {
10454         enum intel_dpll_id id;
10455
10456         switch (port) {
10457         case PORT_A:
10458                 id = DPLL_ID_SKL_DPLL0;
10459                 break;
10460         case PORT_B:
10461                 id = DPLL_ID_SKL_DPLL1;
10462                 break;
10463         case PORT_C:
10464                 id = DPLL_ID_SKL_DPLL2;
10465                 break;
10466         default:
10467                 DRM_ERROR("Incorrect port type\n");
10468                 return;
10469         }
10470
10471         pipe_config->shared_dpll = intel_get_shared_dpll_by_id(dev_priv, id);
10472 }
10473
10474 static void skylake_get_ddi_pll(struct drm_i915_private *dev_priv,
10475                                 enum port port,
10476                                 struct intel_crtc_state *pipe_config)
10477 {
10478         enum intel_dpll_id id;
10479         u32 temp;
10480
10481         temp = I915_READ(DPLL_CTRL2) & DPLL_CTRL2_DDI_CLK_SEL_MASK(port);
10482         id = temp >> (port * 3 + 1);
10483
10484         if (WARN_ON(id < SKL_DPLL0 || id > SKL_DPLL3))
10485                 return;
10486
10487         pipe_config->shared_dpll = intel_get_shared_dpll_by_id(dev_priv, id);
10488 }
10489
10490 static void haswell_get_ddi_pll(struct drm_i915_private *dev_priv,
10491                                 enum port port,
10492                                 struct intel_crtc_state *pipe_config)
10493 {
10494         enum intel_dpll_id id;
10495         uint32_t ddi_pll_sel = I915_READ(PORT_CLK_SEL(port));
10496
10497         switch (ddi_pll_sel) {
10498         case PORT_CLK_SEL_WRPLL1:
10499                 id = DPLL_ID_WRPLL1;
10500                 break;
10501         case PORT_CLK_SEL_WRPLL2:
10502                 id = DPLL_ID_WRPLL2;
10503                 break;
10504         case PORT_CLK_SEL_SPLL:
10505                 id = DPLL_ID_SPLL;
10506                 break;
10507         case PORT_CLK_SEL_LCPLL_810:
10508                 id = DPLL_ID_LCPLL_810;
10509                 break;
10510         case PORT_CLK_SEL_LCPLL_1350:
10511                 id = DPLL_ID_LCPLL_1350;
10512                 break;
10513         case PORT_CLK_SEL_LCPLL_2700:
10514                 id = DPLL_ID_LCPLL_2700;
10515                 break;
10516         default:
10517                 MISSING_CASE(ddi_pll_sel);
10518                 /* fall through */
10519         case PORT_CLK_SEL_NONE:
10520                 return;
10521         }
10522
10523         pipe_config->shared_dpll = intel_get_shared_dpll_by_id(dev_priv, id);
10524 }
10525
10526 static bool hsw_get_transcoder_state(struct intel_crtc *crtc,
10527                                      struct intel_crtc_state *pipe_config,
10528                                      unsigned long *power_domain_mask)
10529 {
10530         struct drm_device *dev = crtc->base.dev;
10531         struct drm_i915_private *dev_priv = to_i915(dev);
10532         enum intel_display_power_domain power_domain;
10533         u32 tmp;
10534
10535         /*
10536          * The pipe->transcoder mapping is fixed with the exception of the eDP
10537          * transcoder handled below.
10538          */
10539         pipe_config->cpu_transcoder = (enum transcoder) crtc->pipe;
10540
10541         /*
10542          * XXX: Do intel_display_power_get_if_enabled before reading this (for
10543          * consistency and less surprising code; it's in always on power).
10544          */
10545         tmp = I915_READ(TRANS_DDI_FUNC_CTL(TRANSCODER_EDP));
10546         if (tmp & TRANS_DDI_FUNC_ENABLE) {
10547                 enum pipe trans_edp_pipe;
10548                 switch (tmp & TRANS_DDI_EDP_INPUT_MASK) {
10549                 default:
10550                         WARN(1, "unknown pipe linked to edp transcoder\n");
10551                 case TRANS_DDI_EDP_INPUT_A_ONOFF:
10552                 case TRANS_DDI_EDP_INPUT_A_ON:
10553                         trans_edp_pipe = PIPE_A;
10554                         break;
10555                 case TRANS_DDI_EDP_INPUT_B_ONOFF:
10556                         trans_edp_pipe = PIPE_B;
10557                         break;
10558                 case TRANS_DDI_EDP_INPUT_C_ONOFF:
10559                         trans_edp_pipe = PIPE_C;
10560                         break;
10561                 }
10562
10563                 if (trans_edp_pipe == crtc->pipe)
10564                         pipe_config->cpu_transcoder = TRANSCODER_EDP;
10565         }
10566
10567         power_domain = POWER_DOMAIN_TRANSCODER(pipe_config->cpu_transcoder);
10568         if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
10569                 return false;
10570         *power_domain_mask |= BIT(power_domain);
10571
10572         tmp = I915_READ(PIPECONF(pipe_config->cpu_transcoder));
10573
10574         return tmp & PIPECONF_ENABLE;
10575 }
10576
10577 static bool bxt_get_dsi_transcoder_state(struct intel_crtc *crtc,
10578                                          struct intel_crtc_state *pipe_config,
10579                                          unsigned long *power_domain_mask)
10580 {
10581         struct drm_device *dev = crtc->base.dev;
10582         struct drm_i915_private *dev_priv = to_i915(dev);
10583         enum intel_display_power_domain power_domain;
10584         enum port port;
10585         enum transcoder cpu_transcoder;
10586         u32 tmp;
10587
10588         for_each_port_masked(port, BIT(PORT_A) | BIT(PORT_C)) {
10589                 if (port == PORT_A)
10590                         cpu_transcoder = TRANSCODER_DSI_A;
10591                 else
10592                         cpu_transcoder = TRANSCODER_DSI_C;
10593
10594                 power_domain = POWER_DOMAIN_TRANSCODER(cpu_transcoder);
10595                 if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
10596                         continue;
10597                 *power_domain_mask |= BIT(power_domain);
10598
10599                 /*
10600                  * The PLL needs to be enabled with a valid divider
10601                  * configuration, otherwise accessing DSI registers will hang
10602                  * the machine. See BSpec North Display Engine
10603                  * registers/MIPI[BXT]. We can break out here early, since we
10604                  * need the same DSI PLL to be enabled for both DSI ports.
10605                  */
10606                 if (!intel_dsi_pll_is_enabled(dev_priv))
10607                         break;
10608
10609                 /* XXX: this works for video mode only */
10610                 tmp = I915_READ(BXT_MIPI_PORT_CTRL(port));
10611                 if (!(tmp & DPI_ENABLE))
10612                         continue;
10613
10614                 tmp = I915_READ(MIPI_CTRL(port));
10615                 if ((tmp & BXT_PIPE_SELECT_MASK) != BXT_PIPE_SELECT(crtc->pipe))
10616                         continue;
10617
10618                 pipe_config->cpu_transcoder = cpu_transcoder;
10619                 break;
10620         }
10621
10622         return transcoder_is_dsi(pipe_config->cpu_transcoder);
10623 }
10624
10625 static void haswell_get_ddi_port_state(struct intel_crtc *crtc,
10626                                        struct intel_crtc_state *pipe_config)
10627 {
10628         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
10629         struct intel_shared_dpll *pll;
10630         enum port port;
10631         uint32_t tmp;
10632
10633         tmp = I915_READ(TRANS_DDI_FUNC_CTL(pipe_config->cpu_transcoder));
10634
10635         port = (tmp & TRANS_DDI_PORT_MASK) >> TRANS_DDI_PORT_SHIFT;
10636
10637         if (IS_SKYLAKE(dev_priv) || IS_KABYLAKE(dev_priv))
10638                 skylake_get_ddi_pll(dev_priv, port, pipe_config);
10639         else if (IS_BROXTON(dev_priv))
10640                 bxt_get_ddi_pll(dev_priv, port, pipe_config);
10641         else
10642                 haswell_get_ddi_pll(dev_priv, port, pipe_config);
10643
10644         pll = pipe_config->shared_dpll;
10645         if (pll) {
10646                 WARN_ON(!pll->funcs.get_hw_state(dev_priv, pll,
10647                                                  &pipe_config->dpll_hw_state));
10648         }
10649
10650         /*
10651          * Haswell has only FDI/PCH transcoder A. It is which is connected to
10652          * DDI E. So just check whether this pipe is wired to DDI E and whether
10653          * the PCH transcoder is on.
10654          */
10655         if (INTEL_GEN(dev_priv) < 9 &&
10656             (port == PORT_E) && I915_READ(LPT_TRANSCONF) & TRANS_ENABLE) {
10657                 pipe_config->has_pch_encoder = true;
10658
10659                 tmp = I915_READ(FDI_RX_CTL(PIPE_A));
10660                 pipe_config->fdi_lanes = ((FDI_DP_PORT_WIDTH_MASK & tmp) >>
10661                                           FDI_DP_PORT_WIDTH_SHIFT) + 1;
10662
10663                 ironlake_get_fdi_m_n_config(crtc, pipe_config);
10664         }
10665 }
10666
10667 static bool haswell_get_pipe_config(struct intel_crtc *crtc,
10668                                     struct intel_crtc_state *pipe_config)
10669 {
10670         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
10671         enum intel_display_power_domain power_domain;
10672         unsigned long power_domain_mask;
10673         bool active;
10674
10675         power_domain = POWER_DOMAIN_PIPE(crtc->pipe);
10676         if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
10677                 return false;
10678         power_domain_mask = BIT(power_domain);
10679
10680         pipe_config->shared_dpll = NULL;
10681
10682         active = hsw_get_transcoder_state(crtc, pipe_config, &power_domain_mask);
10683
10684         if (IS_BROXTON(dev_priv) &&
10685             bxt_get_dsi_transcoder_state(crtc, pipe_config, &power_domain_mask)) {
10686                 WARN_ON(active);
10687                 active = true;
10688         }
10689
10690         if (!active)
10691                 goto out;
10692
10693         if (!transcoder_is_dsi(pipe_config->cpu_transcoder)) {
10694                 haswell_get_ddi_port_state(crtc, pipe_config);
10695                 intel_get_pipe_timings(crtc, pipe_config);
10696         }
10697
10698         intel_get_pipe_src_size(crtc, pipe_config);
10699
10700         pipe_config->gamma_mode =
10701                 I915_READ(GAMMA_MODE(crtc->pipe)) & GAMMA_MODE_MODE_MASK;
10702
10703         if (INTEL_GEN(dev_priv) >= 9) {
10704                 skl_init_scalers(dev_priv, crtc, pipe_config);
10705
10706                 pipe_config->scaler_state.scaler_id = -1;
10707                 pipe_config->scaler_state.scaler_users &= ~(1 << SKL_CRTC_INDEX);
10708         }
10709
10710         power_domain = POWER_DOMAIN_PIPE_PANEL_FITTER(crtc->pipe);
10711         if (intel_display_power_get_if_enabled(dev_priv, power_domain)) {
10712                 power_domain_mask |= BIT(power_domain);
10713                 if (INTEL_GEN(dev_priv) >= 9)
10714                         skylake_get_pfit_config(crtc, pipe_config);
10715                 else
10716                         ironlake_get_pfit_config(crtc, pipe_config);
10717         }
10718
10719         if (IS_HASWELL(dev_priv))
10720                 pipe_config->ips_enabled = hsw_crtc_supports_ips(crtc) &&
10721                         (I915_READ(IPS_CTL) & IPS_ENABLE);
10722
10723         if (pipe_config->cpu_transcoder != TRANSCODER_EDP &&
10724             !transcoder_is_dsi(pipe_config->cpu_transcoder)) {
10725                 pipe_config->pixel_multiplier =
10726                         I915_READ(PIPE_MULT(pipe_config->cpu_transcoder)) + 1;
10727         } else {
10728                 pipe_config->pixel_multiplier = 1;
10729         }
10730
10731 out:
10732         for_each_power_domain(power_domain, power_domain_mask)
10733                 intel_display_power_put(dev_priv, power_domain);
10734
10735         return active;
10736 }
10737
10738 static void i845_update_cursor(struct drm_crtc *crtc, u32 base,
10739                                const struct intel_plane_state *plane_state)
10740 {
10741         struct drm_device *dev = crtc->dev;
10742         struct drm_i915_private *dev_priv = to_i915(dev);
10743         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10744         uint32_t cntl = 0, size = 0;
10745
10746         if (plane_state && plane_state->base.visible) {
10747                 unsigned int width = plane_state->base.crtc_w;
10748                 unsigned int height = plane_state->base.crtc_h;
10749                 unsigned int stride = roundup_pow_of_two(width) * 4;
10750
10751                 switch (stride) {
10752                 default:
10753                         WARN_ONCE(1, "Invalid cursor width/stride, width=%u, stride=%u\n",
10754                                   width, stride);
10755                         stride = 256;
10756                         /* fallthrough */
10757                 case 256:
10758                 case 512:
10759                 case 1024:
10760                 case 2048:
10761                         break;
10762                 }
10763
10764                 cntl |= CURSOR_ENABLE |
10765                         CURSOR_GAMMA_ENABLE |
10766                         CURSOR_FORMAT_ARGB |
10767                         CURSOR_STRIDE(stride);
10768
10769                 size = (height << 12) | width;
10770         }
10771
10772         if (intel_crtc->cursor_cntl != 0 &&
10773             (intel_crtc->cursor_base != base ||
10774              intel_crtc->cursor_size != size ||
10775              intel_crtc->cursor_cntl != cntl)) {
10776                 /* On these chipsets we can only modify the base/size/stride
10777                  * whilst the cursor is disabled.
10778                  */
10779                 I915_WRITE(CURCNTR(PIPE_A), 0);
10780                 POSTING_READ(CURCNTR(PIPE_A));
10781                 intel_crtc->cursor_cntl = 0;
10782         }
10783
10784         if (intel_crtc->cursor_base != base) {
10785                 I915_WRITE(CURBASE(PIPE_A), base);
10786                 intel_crtc->cursor_base = base;
10787         }
10788
10789         if (intel_crtc->cursor_size != size) {
10790                 I915_WRITE(CURSIZE, size);
10791                 intel_crtc->cursor_size = size;
10792         }
10793
10794         if (intel_crtc->cursor_cntl != cntl) {
10795                 I915_WRITE(CURCNTR(PIPE_A), cntl);
10796                 POSTING_READ(CURCNTR(PIPE_A));
10797                 intel_crtc->cursor_cntl = cntl;
10798         }
10799 }
10800
10801 static void i9xx_update_cursor(struct drm_crtc *crtc, u32 base,
10802                                const struct intel_plane_state *plane_state)
10803 {
10804         struct drm_device *dev = crtc->dev;
10805         struct drm_i915_private *dev_priv = to_i915(dev);
10806         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10807         int pipe = intel_crtc->pipe;
10808         uint32_t cntl = 0;
10809
10810         if (plane_state && plane_state->base.visible) {
10811                 cntl = MCURSOR_GAMMA_ENABLE;
10812                 switch (plane_state->base.crtc_w) {
10813                         case 64:
10814                                 cntl |= CURSOR_MODE_64_ARGB_AX;
10815                                 break;
10816                         case 128:
10817                                 cntl |= CURSOR_MODE_128_ARGB_AX;
10818                                 break;
10819                         case 256:
10820                                 cntl |= CURSOR_MODE_256_ARGB_AX;
10821                                 break;
10822                         default:
10823                                 MISSING_CASE(plane_state->base.crtc_w);
10824                                 return;
10825                 }
10826                 cntl |= pipe << 28; /* Connect to correct pipe */
10827
10828                 if (HAS_DDI(dev_priv))
10829                         cntl |= CURSOR_PIPE_CSC_ENABLE;
10830
10831                 if (plane_state->base.rotation & DRM_ROTATE_180)
10832                         cntl |= CURSOR_ROTATE_180;
10833         }
10834
10835         if (intel_crtc->cursor_cntl != cntl) {
10836                 I915_WRITE(CURCNTR(pipe), cntl);
10837                 POSTING_READ(CURCNTR(pipe));
10838                 intel_crtc->cursor_cntl = cntl;
10839         }
10840
10841         /* and commit changes on next vblank */
10842         I915_WRITE(CURBASE(pipe), base);
10843         POSTING_READ(CURBASE(pipe));
10844
10845         intel_crtc->cursor_base = base;
10846 }
10847
10848 /* If no-part of the cursor is visible on the framebuffer, then the GPU may hang... */
10849 static void intel_crtc_update_cursor(struct drm_crtc *crtc,
10850                                      const struct intel_plane_state *plane_state)
10851 {
10852         struct drm_device *dev = crtc->dev;
10853         struct drm_i915_private *dev_priv = to_i915(dev);
10854         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10855         int pipe = intel_crtc->pipe;
10856         u32 base = intel_crtc->cursor_addr;
10857         u32 pos = 0;
10858
10859         if (plane_state) {
10860                 int x = plane_state->base.crtc_x;
10861                 int y = plane_state->base.crtc_y;
10862
10863                 if (x < 0) {
10864                         pos |= CURSOR_POS_SIGN << CURSOR_X_SHIFT;
10865                         x = -x;
10866                 }
10867                 pos |= x << CURSOR_X_SHIFT;
10868
10869                 if (y < 0) {
10870                         pos |= CURSOR_POS_SIGN << CURSOR_Y_SHIFT;
10871                         y = -y;
10872                 }
10873                 pos |= y << CURSOR_Y_SHIFT;
10874
10875                 /* ILK+ do this automagically */
10876                 if (HAS_GMCH_DISPLAY(dev_priv) &&
10877                     plane_state->base.rotation & DRM_ROTATE_180) {
10878                         base += (plane_state->base.crtc_h *
10879                                  plane_state->base.crtc_w - 1) * 4;
10880                 }
10881         }
10882
10883         I915_WRITE(CURPOS(pipe), pos);
10884
10885         if (IS_845G(dev_priv) || IS_I865G(dev_priv))
10886                 i845_update_cursor(crtc, base, plane_state);
10887         else
10888                 i9xx_update_cursor(crtc, base, plane_state);
10889 }
10890
10891 static bool cursor_size_ok(struct drm_i915_private *dev_priv,
10892                            uint32_t width, uint32_t height)
10893 {
10894         if (width == 0 || height == 0)
10895                 return false;
10896
10897         /*
10898          * 845g/865g are special in that they are only limited by
10899          * the width of their cursors, the height is arbitrary up to
10900          * the precision of the register. Everything else requires
10901          * square cursors, limited to a few power-of-two sizes.
10902          */
10903         if (IS_845G(dev_priv) || IS_I865G(dev_priv)) {
10904                 if ((width & 63) != 0)
10905                         return false;
10906
10907                 if (width > (IS_845G(dev_priv) ? 64 : 512))
10908                         return false;
10909
10910                 if (height > 1023)
10911                         return false;
10912         } else {
10913                 switch (width | height) {
10914                 case 256:
10915                 case 128:
10916                         if (IS_GEN2(dev_priv))
10917                                 return false;
10918                 case 64:
10919                         break;
10920                 default:
10921                         return false;
10922                 }
10923         }
10924
10925         return true;
10926 }
10927
10928 /* VESA 640x480x72Hz mode to set on the pipe */
10929 static struct drm_display_mode load_detect_mode = {
10930         DRM_MODE("640x480", DRM_MODE_TYPE_DEFAULT, 31500, 640, 664,
10931                  704, 832, 0, 480, 489, 491, 520, 0, DRM_MODE_FLAG_NHSYNC | DRM_MODE_FLAG_NVSYNC),
10932 };
10933
10934 struct drm_framebuffer *
10935 __intel_framebuffer_create(struct drm_device *dev,
10936                            struct drm_mode_fb_cmd2 *mode_cmd,
10937                            struct drm_i915_gem_object *obj)
10938 {
10939         struct intel_framebuffer *intel_fb;
10940         int ret;
10941
10942         intel_fb = kzalloc(sizeof(*intel_fb), GFP_KERNEL);
10943         if (!intel_fb)
10944                 return ERR_PTR(-ENOMEM);
10945
10946         ret = intel_framebuffer_init(dev, intel_fb, mode_cmd, obj);
10947         if (ret)
10948                 goto err;
10949
10950         return &intel_fb->base;
10951
10952 err:
10953         kfree(intel_fb);
10954         return ERR_PTR(ret);
10955 }
10956
10957 static struct drm_framebuffer *
10958 intel_framebuffer_create(struct drm_device *dev,
10959                          struct drm_mode_fb_cmd2 *mode_cmd,
10960                          struct drm_i915_gem_object *obj)
10961 {
10962         struct drm_framebuffer *fb;
10963         int ret;
10964
10965         ret = i915_mutex_lock_interruptible(dev);
10966         if (ret)
10967                 return ERR_PTR(ret);
10968         fb = __intel_framebuffer_create(dev, mode_cmd, obj);
10969         mutex_unlock(&dev->struct_mutex);
10970
10971         return fb;
10972 }
10973
10974 static u32
10975 intel_framebuffer_pitch_for_width(int width, int bpp)
10976 {
10977         u32 pitch = DIV_ROUND_UP(width * bpp, 8);
10978         return ALIGN(pitch, 64);
10979 }
10980
10981 static u32
10982 intel_framebuffer_size_for_mode(struct drm_display_mode *mode, int bpp)
10983 {
10984         u32 pitch = intel_framebuffer_pitch_for_width(mode->hdisplay, bpp);
10985         return PAGE_ALIGN(pitch * mode->vdisplay);
10986 }
10987
10988 static struct drm_framebuffer *
10989 intel_framebuffer_create_for_mode(struct drm_device *dev,
10990                                   struct drm_display_mode *mode,
10991                                   int depth, int bpp)
10992 {
10993         struct drm_framebuffer *fb;
10994         struct drm_i915_gem_object *obj;
10995         struct drm_mode_fb_cmd2 mode_cmd = { 0 };
10996
10997         obj = i915_gem_object_create(dev,
10998                                     intel_framebuffer_size_for_mode(mode, bpp));
10999         if (IS_ERR(obj))
11000                 return ERR_CAST(obj);
11001
11002         mode_cmd.width = mode->hdisplay;
11003         mode_cmd.height = mode->vdisplay;
11004         mode_cmd.pitches[0] = intel_framebuffer_pitch_for_width(mode_cmd.width,
11005                                                                 bpp);
11006         mode_cmd.pixel_format = drm_mode_legacy_fb_format(bpp, depth);
11007
11008         fb = intel_framebuffer_create(dev, &mode_cmd, obj);
11009         if (IS_ERR(fb))
11010                 i915_gem_object_put(obj);
11011
11012         return fb;
11013 }
11014
11015 static struct drm_framebuffer *
11016 mode_fits_in_fbdev(struct drm_device *dev,
11017                    struct drm_display_mode *mode)
11018 {
11019 #ifdef CONFIG_DRM_FBDEV_EMULATION
11020         struct drm_i915_private *dev_priv = to_i915(dev);
11021         struct drm_i915_gem_object *obj;
11022         struct drm_framebuffer *fb;
11023
11024         if (!dev_priv->fbdev)
11025                 return NULL;
11026
11027         if (!dev_priv->fbdev->fb)
11028                 return NULL;
11029
11030         obj = dev_priv->fbdev->fb->obj;
11031         BUG_ON(!obj);
11032
11033         fb = &dev_priv->fbdev->fb->base;
11034         if (fb->pitches[0] < intel_framebuffer_pitch_for_width(mode->hdisplay,
11035                                                                fb->bits_per_pixel))
11036                 return NULL;
11037
11038         if (obj->base.size < mode->vdisplay * fb->pitches[0])
11039                 return NULL;
11040
11041         drm_framebuffer_reference(fb);
11042         return fb;
11043 #else
11044         return NULL;
11045 #endif
11046 }
11047
11048 static int intel_modeset_setup_plane_state(struct drm_atomic_state *state,
11049                                            struct drm_crtc *crtc,
11050                                            struct drm_display_mode *mode,
11051                                            struct drm_framebuffer *fb,
11052                                            int x, int y)
11053 {
11054         struct drm_plane_state *plane_state;
11055         int hdisplay, vdisplay;
11056         int ret;
11057
11058         plane_state = drm_atomic_get_plane_state(state, crtc->primary);
11059         if (IS_ERR(plane_state))
11060                 return PTR_ERR(plane_state);
11061
11062         if (mode)
11063                 drm_crtc_get_hv_timing(mode, &hdisplay, &vdisplay);
11064         else
11065                 hdisplay = vdisplay = 0;
11066
11067         ret = drm_atomic_set_crtc_for_plane(plane_state, fb ? crtc : NULL);
11068         if (ret)
11069                 return ret;
11070         drm_atomic_set_fb_for_plane(plane_state, fb);
11071         plane_state->crtc_x = 0;
11072         plane_state->crtc_y = 0;
11073         plane_state->crtc_w = hdisplay;
11074         plane_state->crtc_h = vdisplay;
11075         plane_state->src_x = x << 16;
11076         plane_state->src_y = y << 16;
11077         plane_state->src_w = hdisplay << 16;
11078         plane_state->src_h = vdisplay << 16;
11079
11080         return 0;
11081 }
11082
11083 bool intel_get_load_detect_pipe(struct drm_connector *connector,
11084                                 struct drm_display_mode *mode,
11085                                 struct intel_load_detect_pipe *old,
11086                                 struct drm_modeset_acquire_ctx *ctx)
11087 {
11088         struct intel_crtc *intel_crtc;
11089         struct intel_encoder *intel_encoder =
11090                 intel_attached_encoder(connector);
11091         struct drm_crtc *possible_crtc;
11092         struct drm_encoder *encoder = &intel_encoder->base;
11093         struct drm_crtc *crtc = NULL;
11094         struct drm_device *dev = encoder->dev;
11095         struct drm_i915_private *dev_priv = to_i915(dev);
11096         struct drm_framebuffer *fb;
11097         struct drm_mode_config *config = &dev->mode_config;
11098         struct drm_atomic_state *state = NULL, *restore_state = NULL;
11099         struct drm_connector_state *connector_state;
11100         struct intel_crtc_state *crtc_state;
11101         int ret, i = -1;
11102
11103         DRM_DEBUG_KMS("[CONNECTOR:%d:%s], [ENCODER:%d:%s]\n",
11104                       connector->base.id, connector->name,
11105                       encoder->base.id, encoder->name);
11106
11107         old->restore_state = NULL;
11108
11109 retry:
11110         ret = drm_modeset_lock(&config->connection_mutex, ctx);
11111         if (ret)
11112                 goto fail;
11113
11114         /*
11115          * Algorithm gets a little messy:
11116          *
11117          *   - if the connector already has an assigned crtc, use it (but make
11118          *     sure it's on first)
11119          *
11120          *   - try to find the first unused crtc that can drive this connector,
11121          *     and use that if we find one
11122          */
11123
11124         /* See if we already have a CRTC for this connector */
11125         if (connector->state->crtc) {
11126                 crtc = connector->state->crtc;
11127
11128                 ret = drm_modeset_lock(&crtc->mutex, ctx);
11129                 if (ret)
11130                         goto fail;
11131
11132                 /* Make sure the crtc and connector are running */
11133                 goto found;
11134         }
11135
11136         /* Find an unused one (if possible) */
11137         for_each_crtc(dev, possible_crtc) {
11138                 i++;
11139                 if (!(encoder->possible_crtcs & (1 << i)))
11140                         continue;
11141
11142                 ret = drm_modeset_lock(&possible_crtc->mutex, ctx);
11143                 if (ret)
11144                         goto fail;
11145
11146                 if (possible_crtc->state->enable) {
11147                         drm_modeset_unlock(&possible_crtc->mutex);
11148                         continue;
11149                 }
11150
11151                 crtc = possible_crtc;
11152                 break;
11153         }
11154
11155         /*
11156          * If we didn't find an unused CRTC, don't use any.
11157          */
11158         if (!crtc) {
11159                 DRM_DEBUG_KMS("no pipe available for load-detect\n");
11160                 goto fail;
11161         }
11162
11163 found:
11164         intel_crtc = to_intel_crtc(crtc);
11165
11166         ret = drm_modeset_lock(&crtc->primary->mutex, ctx);
11167         if (ret)
11168                 goto fail;
11169
11170         state = drm_atomic_state_alloc(dev);
11171         restore_state = drm_atomic_state_alloc(dev);
11172         if (!state || !restore_state) {
11173                 ret = -ENOMEM;
11174                 goto fail;
11175         }
11176
11177         state->acquire_ctx = ctx;
11178         restore_state->acquire_ctx = ctx;
11179
11180         connector_state = drm_atomic_get_connector_state(state, connector);
11181         if (IS_ERR(connector_state)) {
11182                 ret = PTR_ERR(connector_state);
11183                 goto fail;
11184         }
11185
11186         ret = drm_atomic_set_crtc_for_connector(connector_state, crtc);
11187         if (ret)
11188                 goto fail;
11189
11190         crtc_state = intel_atomic_get_crtc_state(state, intel_crtc);
11191         if (IS_ERR(crtc_state)) {
11192                 ret = PTR_ERR(crtc_state);
11193                 goto fail;
11194         }
11195
11196         crtc_state->base.active = crtc_state->base.enable = true;
11197
11198         if (!mode)
11199                 mode = &load_detect_mode;
11200
11201         /* We need a framebuffer large enough to accommodate all accesses
11202          * that the plane may generate whilst we perform load detection.
11203          * We can not rely on the fbcon either being present (we get called
11204          * during its initialisation to detect all boot displays, or it may
11205          * not even exist) or that it is large enough to satisfy the
11206          * requested mode.
11207          */
11208         fb = mode_fits_in_fbdev(dev, mode);
11209         if (fb == NULL) {
11210                 DRM_DEBUG_KMS("creating tmp fb for load-detection\n");
11211                 fb = intel_framebuffer_create_for_mode(dev, mode, 24, 32);
11212         } else
11213                 DRM_DEBUG_KMS("reusing fbdev for load-detection framebuffer\n");
11214         if (IS_ERR(fb)) {
11215                 DRM_DEBUG_KMS("failed to allocate framebuffer for load-detection\n");
11216                 goto fail;
11217         }
11218
11219         ret = intel_modeset_setup_plane_state(state, crtc, mode, fb, 0, 0);
11220         if (ret)
11221                 goto fail;
11222
11223         drm_framebuffer_unreference(fb);
11224
11225         ret = drm_atomic_set_mode_for_crtc(&crtc_state->base, mode);
11226         if (ret)
11227                 goto fail;
11228
11229         ret = PTR_ERR_OR_ZERO(drm_atomic_get_connector_state(restore_state, connector));
11230         if (!ret)
11231                 ret = PTR_ERR_OR_ZERO(drm_atomic_get_crtc_state(restore_state, crtc));
11232         if (!ret)
11233                 ret = PTR_ERR_OR_ZERO(drm_atomic_get_plane_state(restore_state, crtc->primary));
11234         if (ret) {
11235                 DRM_DEBUG_KMS("Failed to create a copy of old state to restore: %i\n", ret);
11236                 goto fail;
11237         }
11238
11239         ret = drm_atomic_commit(state);
11240         if (ret) {
11241                 DRM_DEBUG_KMS("failed to set mode on load-detect pipe\n");
11242                 goto fail;
11243         }
11244
11245         old->restore_state = restore_state;
11246
11247         /* let the connector get through one full cycle before testing */
11248         intel_wait_for_vblank(dev_priv, intel_crtc->pipe);
11249         return true;
11250
11251 fail:
11252         if (state) {
11253                 drm_atomic_state_put(state);
11254                 state = NULL;
11255         }
11256         if (restore_state) {
11257                 drm_atomic_state_put(restore_state);
11258                 restore_state = NULL;
11259         }
11260
11261         if (ret == -EDEADLK) {
11262                 drm_modeset_backoff(ctx);
11263                 goto retry;
11264         }
11265
11266         return false;
11267 }
11268
11269 void intel_release_load_detect_pipe(struct drm_connector *connector,
11270                                     struct intel_load_detect_pipe *old,
11271                                     struct drm_modeset_acquire_ctx *ctx)
11272 {
11273         struct intel_encoder *intel_encoder =
11274                 intel_attached_encoder(connector);
11275         struct drm_encoder *encoder = &intel_encoder->base;
11276         struct drm_atomic_state *state = old->restore_state;
11277         int ret;
11278
11279         DRM_DEBUG_KMS("[CONNECTOR:%d:%s], [ENCODER:%d:%s]\n",
11280                       connector->base.id, connector->name,
11281                       encoder->base.id, encoder->name);
11282
11283         if (!state)
11284                 return;
11285
11286         ret = drm_atomic_commit(state);
11287         if (ret)
11288                 DRM_DEBUG_KMS("Couldn't release load detect pipe: %i\n", ret);
11289         drm_atomic_state_put(state);
11290 }
11291
11292 static int i9xx_pll_refclk(struct drm_device *dev,
11293                            const struct intel_crtc_state *pipe_config)
11294 {
11295         struct drm_i915_private *dev_priv = to_i915(dev);
11296         u32 dpll = pipe_config->dpll_hw_state.dpll;
11297
11298         if ((dpll & PLL_REF_INPUT_MASK) == PLLB_REF_INPUT_SPREADSPECTRUMIN)
11299                 return dev_priv->vbt.lvds_ssc_freq;
11300         else if (HAS_PCH_SPLIT(dev_priv))
11301                 return 120000;
11302         else if (!IS_GEN2(dev_priv))
11303                 return 96000;
11304         else
11305                 return 48000;
11306 }
11307
11308 /* Returns the clock of the currently programmed mode of the given pipe. */
11309 static void i9xx_crtc_clock_get(struct intel_crtc *crtc,
11310                                 struct intel_crtc_state *pipe_config)
11311 {
11312         struct drm_device *dev = crtc->base.dev;
11313         struct drm_i915_private *dev_priv = to_i915(dev);
11314         int pipe = pipe_config->cpu_transcoder;
11315         u32 dpll = pipe_config->dpll_hw_state.dpll;
11316         u32 fp;
11317         struct dpll clock;
11318         int port_clock;
11319         int refclk = i9xx_pll_refclk(dev, pipe_config);
11320
11321         if ((dpll & DISPLAY_RATE_SELECT_FPA1) == 0)
11322                 fp = pipe_config->dpll_hw_state.fp0;
11323         else
11324                 fp = pipe_config->dpll_hw_state.fp1;
11325
11326         clock.m1 = (fp & FP_M1_DIV_MASK) >> FP_M1_DIV_SHIFT;
11327         if (IS_PINEVIEW(dev_priv)) {
11328                 clock.n = ffs((fp & FP_N_PINEVIEW_DIV_MASK) >> FP_N_DIV_SHIFT) - 1;
11329                 clock.m2 = (fp & FP_M2_PINEVIEW_DIV_MASK) >> FP_M2_DIV_SHIFT;
11330         } else {
11331                 clock.n = (fp & FP_N_DIV_MASK) >> FP_N_DIV_SHIFT;
11332                 clock.m2 = (fp & FP_M2_DIV_MASK) >> FP_M2_DIV_SHIFT;
11333         }
11334
11335         if (!IS_GEN2(dev_priv)) {
11336                 if (IS_PINEVIEW(dev_priv))
11337                         clock.p1 = ffs((dpll & DPLL_FPA01_P1_POST_DIV_MASK_PINEVIEW) >>
11338                                 DPLL_FPA01_P1_POST_DIV_SHIFT_PINEVIEW);
11339                 else
11340                         clock.p1 = ffs((dpll & DPLL_FPA01_P1_POST_DIV_MASK) >>
11341                                DPLL_FPA01_P1_POST_DIV_SHIFT);
11342
11343                 switch (dpll & DPLL_MODE_MASK) {
11344                 case DPLLB_MODE_DAC_SERIAL:
11345                         clock.p2 = dpll & DPLL_DAC_SERIAL_P2_CLOCK_DIV_5 ?
11346                                 5 : 10;
11347                         break;
11348                 case DPLLB_MODE_LVDS:
11349                         clock.p2 = dpll & DPLLB_LVDS_P2_CLOCK_DIV_7 ?
11350                                 7 : 14;
11351                         break;
11352                 default:
11353                         DRM_DEBUG_KMS("Unknown DPLL mode %08x in programmed "
11354                                   "mode\n", (int)(dpll & DPLL_MODE_MASK));
11355                         return;
11356                 }
11357
11358                 if (IS_PINEVIEW(dev_priv))
11359                         port_clock = pnv_calc_dpll_params(refclk, &clock);
11360                 else
11361                         port_clock = i9xx_calc_dpll_params(refclk, &clock);
11362         } else {
11363                 u32 lvds = IS_I830(dev_priv) ? 0 : I915_READ(LVDS);
11364                 bool is_lvds = (pipe == 1) && (lvds & LVDS_PORT_EN);
11365
11366                 if (is_lvds) {
11367                         clock.p1 = ffs((dpll & DPLL_FPA01_P1_POST_DIV_MASK_I830_LVDS) >>
11368                                        DPLL_FPA01_P1_POST_DIV_SHIFT);
11369
11370                         if (lvds & LVDS_CLKB_POWER_UP)
11371                                 clock.p2 = 7;
11372                         else
11373                                 clock.p2 = 14;
11374                 } else {
11375                         if (dpll & PLL_P1_DIVIDE_BY_TWO)
11376                                 clock.p1 = 2;
11377                         else {
11378                                 clock.p1 = ((dpll & DPLL_FPA01_P1_POST_DIV_MASK_I830) >>
11379                                             DPLL_FPA01_P1_POST_DIV_SHIFT) + 2;
11380                         }
11381                         if (dpll & PLL_P2_DIVIDE_BY_4)
11382                                 clock.p2 = 4;
11383                         else
11384                                 clock.p2 = 2;
11385                 }
11386
11387                 port_clock = i9xx_calc_dpll_params(refclk, &clock);
11388         }
11389
11390         /*
11391          * This value includes pixel_multiplier. We will use
11392          * port_clock to compute adjusted_mode.crtc_clock in the
11393          * encoder's get_config() function.
11394          */
11395         pipe_config->port_clock = port_clock;
11396 }
11397
11398 int intel_dotclock_calculate(int link_freq,
11399                              const struct intel_link_m_n *m_n)
11400 {
11401         /*
11402          * The calculation for the data clock is:
11403          * pixel_clock = ((m/n)*(link_clock * nr_lanes))/bpp
11404          * But we want to avoid losing precison if possible, so:
11405          * pixel_clock = ((m * link_clock * nr_lanes)/(n*bpp))
11406          *
11407          * and the link clock is simpler:
11408          * link_clock = (m * link_clock) / n
11409          */
11410
11411         if (!m_n->link_n)
11412                 return 0;
11413
11414         return div_u64((u64)m_n->link_m * link_freq, m_n->link_n);
11415 }
11416
11417 static void ironlake_pch_clock_get(struct intel_crtc *crtc,
11418                                    struct intel_crtc_state *pipe_config)
11419 {
11420         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
11421
11422         /* read out port_clock from the DPLL */
11423         i9xx_crtc_clock_get(crtc, pipe_config);
11424
11425         /*
11426          * In case there is an active pipe without active ports,
11427          * we may need some idea for the dotclock anyway.
11428          * Calculate one based on the FDI configuration.
11429          */
11430         pipe_config->base.adjusted_mode.crtc_clock =
11431                 intel_dotclock_calculate(intel_fdi_link_freq(dev_priv, pipe_config),
11432                                          &pipe_config->fdi_m_n);
11433 }
11434
11435 /** Returns the currently programmed mode of the given pipe. */
11436 struct drm_display_mode *intel_crtc_mode_get(struct drm_device *dev,
11437                                              struct drm_crtc *crtc)
11438 {
11439         struct drm_i915_private *dev_priv = to_i915(dev);
11440         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11441         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
11442         struct drm_display_mode *mode;
11443         struct intel_crtc_state *pipe_config;
11444         int htot = I915_READ(HTOTAL(cpu_transcoder));
11445         int hsync = I915_READ(HSYNC(cpu_transcoder));
11446         int vtot = I915_READ(VTOTAL(cpu_transcoder));
11447         int vsync = I915_READ(VSYNC(cpu_transcoder));
11448         enum pipe pipe = intel_crtc->pipe;
11449
11450         mode = kzalloc(sizeof(*mode), GFP_KERNEL);
11451         if (!mode)
11452                 return NULL;
11453
11454         pipe_config = kzalloc(sizeof(*pipe_config), GFP_KERNEL);
11455         if (!pipe_config) {
11456                 kfree(mode);
11457                 return NULL;
11458         }
11459
11460         /*
11461          * Construct a pipe_config sufficient for getting the clock info
11462          * back out of crtc_clock_get.
11463          *
11464          * Note, if LVDS ever uses a non-1 pixel multiplier, we'll need
11465          * to use a real value here instead.
11466          */
11467         pipe_config->cpu_transcoder = (enum transcoder) pipe;
11468         pipe_config->pixel_multiplier = 1;
11469         pipe_config->dpll_hw_state.dpll = I915_READ(DPLL(pipe));
11470         pipe_config->dpll_hw_state.fp0 = I915_READ(FP0(pipe));
11471         pipe_config->dpll_hw_state.fp1 = I915_READ(FP1(pipe));
11472         i9xx_crtc_clock_get(intel_crtc, pipe_config);
11473
11474         mode->clock = pipe_config->port_clock / pipe_config->pixel_multiplier;
11475         mode->hdisplay = (htot & 0xffff) + 1;
11476         mode->htotal = ((htot & 0xffff0000) >> 16) + 1;
11477         mode->hsync_start = (hsync & 0xffff) + 1;
11478         mode->hsync_end = ((hsync & 0xffff0000) >> 16) + 1;
11479         mode->vdisplay = (vtot & 0xffff) + 1;
11480         mode->vtotal = ((vtot & 0xffff0000) >> 16) + 1;
11481         mode->vsync_start = (vsync & 0xffff) + 1;
11482         mode->vsync_end = ((vsync & 0xffff0000) >> 16) + 1;
11483
11484         drm_mode_set_name(mode);
11485
11486         kfree(pipe_config);
11487
11488         return mode;
11489 }
11490
11491 static void intel_crtc_destroy(struct drm_crtc *crtc)
11492 {
11493         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11494         struct drm_device *dev = crtc->dev;
11495         struct intel_flip_work *work;
11496
11497         spin_lock_irq(&dev->event_lock);
11498         work = intel_crtc->flip_work;
11499         intel_crtc->flip_work = NULL;
11500         spin_unlock_irq(&dev->event_lock);
11501
11502         if (work) {
11503                 cancel_work_sync(&work->mmio_work);
11504                 cancel_work_sync(&work->unpin_work);
11505                 kfree(work);
11506         }
11507
11508         drm_crtc_cleanup(crtc);
11509
11510         kfree(intel_crtc);
11511 }
11512
11513 static void intel_unpin_work_fn(struct work_struct *__work)
11514 {
11515         struct intel_flip_work *work =
11516                 container_of(__work, struct intel_flip_work, unpin_work);
11517         struct intel_crtc *crtc = to_intel_crtc(work->crtc);
11518         struct drm_device *dev = crtc->base.dev;
11519         struct drm_plane *primary = crtc->base.primary;
11520
11521         if (is_mmio_work(work))
11522                 flush_work(&work->mmio_work);
11523
11524         mutex_lock(&dev->struct_mutex);
11525         intel_unpin_fb_obj(work->old_fb, primary->state->rotation);
11526         i915_gem_object_put(work->pending_flip_obj);
11527         mutex_unlock(&dev->struct_mutex);
11528
11529         i915_gem_request_put(work->flip_queued_req);
11530
11531         intel_frontbuffer_flip_complete(to_i915(dev),
11532                                         to_intel_plane(primary)->frontbuffer_bit);
11533         intel_fbc_post_update(crtc);
11534         drm_framebuffer_unreference(work->old_fb);
11535
11536         BUG_ON(atomic_read(&crtc->unpin_work_count) == 0);
11537         atomic_dec(&crtc->unpin_work_count);
11538
11539         kfree(work);
11540 }
11541
11542 /* Is 'a' after or equal to 'b'? */
11543 static bool g4x_flip_count_after_eq(u32 a, u32 b)
11544 {
11545         return !((a - b) & 0x80000000);
11546 }
11547
11548 static bool __pageflip_finished_cs(struct intel_crtc *crtc,
11549                                    struct intel_flip_work *work)
11550 {
11551         struct drm_device *dev = crtc->base.dev;
11552         struct drm_i915_private *dev_priv = to_i915(dev);
11553
11554         if (abort_flip_on_reset(crtc))
11555                 return true;
11556
11557         /*
11558          * The relevant registers doen't exist on pre-ctg.
11559          * As the flip done interrupt doesn't trigger for mmio
11560          * flips on gmch platforms, a flip count check isn't
11561          * really needed there. But since ctg has the registers,
11562          * include it in the check anyway.
11563          */
11564         if (INTEL_GEN(dev_priv) < 5 && !IS_G4X(dev_priv))
11565                 return true;
11566
11567         /*
11568          * BDW signals flip done immediately if the plane
11569          * is disabled, even if the plane enable is already
11570          * armed to occur at the next vblank :(
11571          */
11572
11573         /*
11574          * A DSPSURFLIVE check isn't enough in case the mmio and CS flips
11575          * used the same base address. In that case the mmio flip might
11576          * have completed, but the CS hasn't even executed the flip yet.
11577          *
11578          * A flip count check isn't enough as the CS might have updated
11579          * the base address just after start of vblank, but before we
11580          * managed to process the interrupt. This means we'd complete the
11581          * CS flip too soon.
11582          *
11583          * Combining both checks should get us a good enough result. It may
11584          * still happen that the CS flip has been executed, but has not
11585          * yet actually completed. But in case the base address is the same
11586          * anyway, we don't really care.
11587          */
11588         return (I915_READ(DSPSURFLIVE(crtc->plane)) & ~0xfff) ==
11589                 crtc->flip_work->gtt_offset &&
11590                 g4x_flip_count_after_eq(I915_READ(PIPE_FLIPCOUNT_G4X(crtc->pipe)),
11591                                     crtc->flip_work->flip_count);
11592 }
11593
11594 static bool
11595 __pageflip_finished_mmio(struct intel_crtc *crtc,
11596                                struct intel_flip_work *work)
11597 {
11598         /*
11599          * MMIO work completes when vblank is different from
11600          * flip_queued_vblank.
11601          *
11602          * Reset counter value doesn't matter, this is handled by
11603          * i915_wait_request finishing early, so no need to handle
11604          * reset here.
11605          */
11606         return intel_crtc_get_vblank_counter(crtc) != work->flip_queued_vblank;
11607 }
11608
11609
11610 static bool pageflip_finished(struct intel_crtc *crtc,
11611                               struct intel_flip_work *work)
11612 {
11613         if (!atomic_read(&work->pending))
11614                 return false;
11615
11616         smp_rmb();
11617
11618         if (is_mmio_work(work))
11619                 return __pageflip_finished_mmio(crtc, work);
11620         else
11621                 return __pageflip_finished_cs(crtc, work);
11622 }
11623
11624 void intel_finish_page_flip_cs(struct drm_i915_private *dev_priv, int pipe)
11625 {
11626         struct drm_device *dev = &dev_priv->drm;
11627         struct intel_crtc *crtc = intel_get_crtc_for_pipe(dev_priv, pipe);
11628         struct intel_flip_work *work;
11629         unsigned long flags;
11630
11631         /* Ignore early vblank irqs */
11632         if (!crtc)
11633                 return;
11634
11635         /*
11636          * This is called both by irq handlers and the reset code (to complete
11637          * lost pageflips) so needs the full irqsave spinlocks.
11638          */
11639         spin_lock_irqsave(&dev->event_lock, flags);
11640         work = crtc->flip_work;
11641
11642         if (work != NULL &&
11643             !is_mmio_work(work) &&
11644             pageflip_finished(crtc, work))
11645                 page_flip_completed(crtc);
11646
11647         spin_unlock_irqrestore(&dev->event_lock, flags);
11648 }
11649
11650 void intel_finish_page_flip_mmio(struct drm_i915_private *dev_priv, int pipe)
11651 {
11652         struct drm_device *dev = &dev_priv->drm;
11653         struct intel_crtc *crtc = intel_get_crtc_for_pipe(dev_priv, pipe);
11654         struct intel_flip_work *work;
11655         unsigned long flags;
11656
11657         /* Ignore early vblank irqs */
11658         if (!crtc)
11659                 return;
11660
11661         /*
11662          * This is called both by irq handlers and the reset code (to complete
11663          * lost pageflips) so needs the full irqsave spinlocks.
11664          */
11665         spin_lock_irqsave(&dev->event_lock, flags);
11666         work = crtc->flip_work;
11667
11668         if (work != NULL &&
11669             is_mmio_work(work) &&
11670             pageflip_finished(crtc, work))
11671                 page_flip_completed(crtc);
11672
11673         spin_unlock_irqrestore(&dev->event_lock, flags);
11674 }
11675
11676 static inline void intel_mark_page_flip_active(struct intel_crtc *crtc,
11677                                                struct intel_flip_work *work)
11678 {
11679         work->flip_queued_vblank = intel_crtc_get_vblank_counter(crtc);
11680
11681         /* Ensure that the work item is consistent when activating it ... */
11682         smp_mb__before_atomic();
11683         atomic_set(&work->pending, 1);
11684 }
11685
11686 static int intel_gen2_queue_flip(struct drm_device *dev,
11687                                  struct drm_crtc *crtc,
11688                                  struct drm_framebuffer *fb,
11689                                  struct drm_i915_gem_object *obj,
11690                                  struct drm_i915_gem_request *req,
11691                                  uint32_t flags)
11692 {
11693         struct intel_ring *ring = req->ring;
11694         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11695         u32 flip_mask;
11696         int ret;
11697
11698         ret = intel_ring_begin(req, 6);
11699         if (ret)
11700                 return ret;
11701
11702         /* Can't queue multiple flips, so wait for the previous
11703          * one to finish before executing the next.
11704          */
11705         if (intel_crtc->plane)
11706                 flip_mask = MI_WAIT_FOR_PLANE_B_FLIP;
11707         else
11708                 flip_mask = MI_WAIT_FOR_PLANE_A_FLIP;
11709         intel_ring_emit(ring, MI_WAIT_FOR_EVENT | flip_mask);
11710         intel_ring_emit(ring, MI_NOOP);
11711         intel_ring_emit(ring, MI_DISPLAY_FLIP |
11712                         MI_DISPLAY_FLIP_PLANE(intel_crtc->plane));
11713         intel_ring_emit(ring, fb->pitches[0]);
11714         intel_ring_emit(ring, intel_crtc->flip_work->gtt_offset);
11715         intel_ring_emit(ring, 0); /* aux display base address, unused */
11716
11717         return 0;
11718 }
11719
11720 static int intel_gen3_queue_flip(struct drm_device *dev,
11721                                  struct drm_crtc *crtc,
11722                                  struct drm_framebuffer *fb,
11723                                  struct drm_i915_gem_object *obj,
11724                                  struct drm_i915_gem_request *req,
11725                                  uint32_t flags)
11726 {
11727         struct intel_ring *ring = req->ring;
11728         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11729         u32 flip_mask;
11730         int ret;
11731
11732         ret = intel_ring_begin(req, 6);
11733         if (ret)
11734                 return ret;
11735
11736         if (intel_crtc->plane)
11737                 flip_mask = MI_WAIT_FOR_PLANE_B_FLIP;
11738         else
11739                 flip_mask = MI_WAIT_FOR_PLANE_A_FLIP;
11740         intel_ring_emit(ring, MI_WAIT_FOR_EVENT | flip_mask);
11741         intel_ring_emit(ring, MI_NOOP);
11742         intel_ring_emit(ring, MI_DISPLAY_FLIP_I915 |
11743                         MI_DISPLAY_FLIP_PLANE(intel_crtc->plane));
11744         intel_ring_emit(ring, fb->pitches[0]);
11745         intel_ring_emit(ring, intel_crtc->flip_work->gtt_offset);
11746         intel_ring_emit(ring, MI_NOOP);
11747
11748         return 0;
11749 }
11750
11751 static int intel_gen4_queue_flip(struct drm_device *dev,
11752                                  struct drm_crtc *crtc,
11753                                  struct drm_framebuffer *fb,
11754                                  struct drm_i915_gem_object *obj,
11755                                  struct drm_i915_gem_request *req,
11756                                  uint32_t flags)
11757 {
11758         struct intel_ring *ring = req->ring;
11759         struct drm_i915_private *dev_priv = to_i915(dev);
11760         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11761         uint32_t pf, pipesrc;
11762         int ret;
11763
11764         ret = intel_ring_begin(req, 4);
11765         if (ret)
11766                 return ret;
11767
11768         /* i965+ uses the linear or tiled offsets from the
11769          * Display Registers (which do not change across a page-flip)
11770          * so we need only reprogram the base address.
11771          */
11772         intel_ring_emit(ring, MI_DISPLAY_FLIP |
11773                         MI_DISPLAY_FLIP_PLANE(intel_crtc->plane));
11774         intel_ring_emit(ring, fb->pitches[0]);
11775         intel_ring_emit(ring, intel_crtc->flip_work->gtt_offset |
11776                         intel_fb_modifier_to_tiling(fb->modifier));
11777
11778         /* XXX Enabling the panel-fitter across page-flip is so far
11779          * untested on non-native modes, so ignore it for now.
11780          * pf = I915_READ(pipe == 0 ? PFA_CTL_1 : PFB_CTL_1) & PF_ENABLE;
11781          */
11782         pf = 0;
11783         pipesrc = I915_READ(PIPESRC(intel_crtc->pipe)) & 0x0fff0fff;
11784         intel_ring_emit(ring, pf | pipesrc);
11785
11786         return 0;
11787 }
11788
11789 static int intel_gen6_queue_flip(struct drm_device *dev,
11790                                  struct drm_crtc *crtc,
11791                                  struct drm_framebuffer *fb,
11792                                  struct drm_i915_gem_object *obj,
11793                                  struct drm_i915_gem_request *req,
11794                                  uint32_t flags)
11795 {
11796         struct intel_ring *ring = req->ring;
11797         struct drm_i915_private *dev_priv = to_i915(dev);
11798         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11799         uint32_t pf, pipesrc;
11800         int ret;
11801
11802         ret = intel_ring_begin(req, 4);
11803         if (ret)
11804                 return ret;
11805
11806         intel_ring_emit(ring, MI_DISPLAY_FLIP |
11807                         MI_DISPLAY_FLIP_PLANE(intel_crtc->plane));
11808         intel_ring_emit(ring, fb->pitches[0] |
11809                         intel_fb_modifier_to_tiling(fb->modifier));
11810         intel_ring_emit(ring, intel_crtc->flip_work->gtt_offset);
11811
11812         /* Contrary to the suggestions in the documentation,
11813          * "Enable Panel Fitter" does not seem to be required when page
11814          * flipping with a non-native mode, and worse causes a normal
11815          * modeset to fail.
11816          * pf = I915_READ(PF_CTL(intel_crtc->pipe)) & PF_ENABLE;
11817          */
11818         pf = 0;
11819         pipesrc = I915_READ(PIPESRC(intel_crtc->pipe)) & 0x0fff0fff;
11820         intel_ring_emit(ring, pf | pipesrc);
11821
11822         return 0;
11823 }
11824
11825 static int intel_gen7_queue_flip(struct drm_device *dev,
11826                                  struct drm_crtc *crtc,
11827                                  struct drm_framebuffer *fb,
11828                                  struct drm_i915_gem_object *obj,
11829                                  struct drm_i915_gem_request *req,
11830                                  uint32_t flags)
11831 {
11832         struct drm_i915_private *dev_priv = to_i915(dev);
11833         struct intel_ring *ring = req->ring;
11834         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11835         uint32_t plane_bit = 0;
11836         int len, ret;
11837
11838         switch (intel_crtc->plane) {
11839         case PLANE_A:
11840                 plane_bit = MI_DISPLAY_FLIP_IVB_PLANE_A;
11841                 break;
11842         case PLANE_B:
11843                 plane_bit = MI_DISPLAY_FLIP_IVB_PLANE_B;
11844                 break;
11845         case PLANE_C:
11846                 plane_bit = MI_DISPLAY_FLIP_IVB_PLANE_C;
11847                 break;
11848         default:
11849                 WARN_ONCE(1, "unknown plane in flip command\n");
11850                 return -ENODEV;
11851         }
11852
11853         len = 4;
11854         if (req->engine->id == RCS) {
11855                 len += 6;
11856                 /*
11857                  * On Gen 8, SRM is now taking an extra dword to accommodate
11858                  * 48bits addresses, and we need a NOOP for the batch size to
11859                  * stay even.
11860                  */
11861                 if (IS_GEN8(dev_priv))
11862                         len += 2;
11863         }
11864
11865         /*
11866          * BSpec MI_DISPLAY_FLIP for IVB:
11867          * "The full packet must be contained within the same cache line."
11868          *
11869          * Currently the LRI+SRM+MI_DISPLAY_FLIP all fit within the same
11870          * cacheline, if we ever start emitting more commands before
11871          * the MI_DISPLAY_FLIP we may need to first emit everything else,
11872          * then do the cacheline alignment, and finally emit the
11873          * MI_DISPLAY_FLIP.
11874          */
11875         ret = intel_ring_cacheline_align(req);
11876         if (ret)
11877                 return ret;
11878
11879         ret = intel_ring_begin(req, len);
11880         if (ret)
11881                 return ret;
11882
11883         /* Unmask the flip-done completion message. Note that the bspec says that
11884          * we should do this for both the BCS and RCS, and that we must not unmask
11885          * more than one flip event at any time (or ensure that one flip message
11886          * can be sent by waiting for flip-done prior to queueing new flips).
11887          * Experimentation says that BCS works despite DERRMR masking all
11888          * flip-done completion events and that unmasking all planes at once
11889          * for the RCS also doesn't appear to drop events. Setting the DERRMR
11890          * to zero does lead to lockups within MI_DISPLAY_FLIP.
11891          */
11892         if (req->engine->id == RCS) {
11893                 intel_ring_emit(ring, MI_LOAD_REGISTER_IMM(1));
11894                 intel_ring_emit_reg(ring, DERRMR);
11895                 intel_ring_emit(ring, ~(DERRMR_PIPEA_PRI_FLIP_DONE |
11896                                           DERRMR_PIPEB_PRI_FLIP_DONE |
11897                                           DERRMR_PIPEC_PRI_FLIP_DONE));
11898                 if (IS_GEN8(dev_priv))
11899                         intel_ring_emit(ring, MI_STORE_REGISTER_MEM_GEN8 |
11900                                               MI_SRM_LRM_GLOBAL_GTT);
11901                 else
11902                         intel_ring_emit(ring, MI_STORE_REGISTER_MEM |
11903                                               MI_SRM_LRM_GLOBAL_GTT);
11904                 intel_ring_emit_reg(ring, DERRMR);
11905                 intel_ring_emit(ring,
11906                                 i915_ggtt_offset(req->engine->scratch) + 256);
11907                 if (IS_GEN8(dev_priv)) {
11908                         intel_ring_emit(ring, 0);
11909                         intel_ring_emit(ring, MI_NOOP);
11910                 }
11911         }
11912
11913         intel_ring_emit(ring, MI_DISPLAY_FLIP_I915 | plane_bit);
11914         intel_ring_emit(ring, fb->pitches[0] |
11915                         intel_fb_modifier_to_tiling(fb->modifier));
11916         intel_ring_emit(ring, intel_crtc->flip_work->gtt_offset);
11917         intel_ring_emit(ring, (MI_NOOP));
11918
11919         return 0;
11920 }
11921
11922 static bool use_mmio_flip(struct intel_engine_cs *engine,
11923                           struct drm_i915_gem_object *obj)
11924 {
11925         /*
11926          * This is not being used for older platforms, because
11927          * non-availability of flip done interrupt forces us to use
11928          * CS flips. Older platforms derive flip done using some clever
11929          * tricks involving the flip_pending status bits and vblank irqs.
11930          * So using MMIO flips there would disrupt this mechanism.
11931          */
11932
11933         if (engine == NULL)
11934                 return true;
11935
11936         if (INTEL_GEN(engine->i915) < 5)
11937                 return false;
11938
11939         if (i915.use_mmio_flip < 0)
11940                 return false;
11941         else if (i915.use_mmio_flip > 0)
11942                 return true;
11943         else if (i915.enable_execlists)
11944                 return true;
11945
11946         return engine != i915_gem_object_last_write_engine(obj);
11947 }
11948
11949 static void skl_do_mmio_flip(struct intel_crtc *intel_crtc,
11950                              unsigned int rotation,
11951                              struct intel_flip_work *work)
11952 {
11953         struct drm_device *dev = intel_crtc->base.dev;
11954         struct drm_i915_private *dev_priv = to_i915(dev);
11955         struct drm_framebuffer *fb = intel_crtc->base.primary->fb;
11956         const enum pipe pipe = intel_crtc->pipe;
11957         u32 ctl, stride = skl_plane_stride(fb, 0, rotation);
11958
11959         ctl = I915_READ(PLANE_CTL(pipe, 0));
11960         ctl &= ~PLANE_CTL_TILED_MASK;
11961         switch (fb->modifier) {
11962         case DRM_FORMAT_MOD_NONE:
11963                 break;
11964         case I915_FORMAT_MOD_X_TILED:
11965                 ctl |= PLANE_CTL_TILED_X;
11966                 break;
11967         case I915_FORMAT_MOD_Y_TILED:
11968                 ctl |= PLANE_CTL_TILED_Y;
11969                 break;
11970         case I915_FORMAT_MOD_Yf_TILED:
11971                 ctl |= PLANE_CTL_TILED_YF;
11972                 break;
11973         default:
11974                 MISSING_CASE(fb->modifier);
11975         }
11976
11977         /*
11978          * Both PLANE_CTL and PLANE_STRIDE are not updated on vblank but on
11979          * PLANE_SURF updates, the update is then guaranteed to be atomic.
11980          */
11981         I915_WRITE(PLANE_CTL(pipe, 0), ctl);
11982         I915_WRITE(PLANE_STRIDE(pipe, 0), stride);
11983
11984         I915_WRITE(PLANE_SURF(pipe, 0), work->gtt_offset);
11985         POSTING_READ(PLANE_SURF(pipe, 0));
11986 }
11987
11988 static void ilk_do_mmio_flip(struct intel_crtc *intel_crtc,
11989                              struct intel_flip_work *work)
11990 {
11991         struct drm_device *dev = intel_crtc->base.dev;
11992         struct drm_i915_private *dev_priv = to_i915(dev);
11993         struct drm_framebuffer *fb = intel_crtc->base.primary->fb;
11994         i915_reg_t reg = DSPCNTR(intel_crtc->plane);
11995         u32 dspcntr;
11996
11997         dspcntr = I915_READ(reg);
11998
11999         if (fb->modifier == I915_FORMAT_MOD_X_TILED)
12000                 dspcntr |= DISPPLANE_TILED;
12001         else
12002                 dspcntr &= ~DISPPLANE_TILED;
12003
12004         I915_WRITE(reg, dspcntr);
12005
12006         I915_WRITE(DSPSURF(intel_crtc->plane), work->gtt_offset);
12007         POSTING_READ(DSPSURF(intel_crtc->plane));
12008 }
12009
12010 static void intel_mmio_flip_work_func(struct work_struct *w)
12011 {
12012         struct intel_flip_work *work =
12013                 container_of(w, struct intel_flip_work, mmio_work);
12014         struct intel_crtc *crtc = to_intel_crtc(work->crtc);
12015         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
12016         struct intel_framebuffer *intel_fb =
12017                 to_intel_framebuffer(crtc->base.primary->fb);
12018         struct drm_i915_gem_object *obj = intel_fb->obj;
12019
12020         WARN_ON(i915_gem_object_wait(obj, 0, MAX_SCHEDULE_TIMEOUT, NULL) < 0);
12021
12022         intel_pipe_update_start(crtc);
12023
12024         if (INTEL_GEN(dev_priv) >= 9)
12025                 skl_do_mmio_flip(crtc, work->rotation, work);
12026         else
12027                 /* use_mmio_flip() retricts MMIO flips to ilk+ */
12028                 ilk_do_mmio_flip(crtc, work);
12029
12030         intel_pipe_update_end(crtc, work);
12031 }
12032
12033 static int intel_default_queue_flip(struct drm_device *dev,
12034                                     struct drm_crtc *crtc,
12035                                     struct drm_framebuffer *fb,
12036                                     struct drm_i915_gem_object *obj,
12037                                     struct drm_i915_gem_request *req,
12038                                     uint32_t flags)
12039 {
12040         return -ENODEV;
12041 }
12042
12043 static bool __pageflip_stall_check_cs(struct drm_i915_private *dev_priv,
12044                                       struct intel_crtc *intel_crtc,
12045                                       struct intel_flip_work *work)
12046 {
12047         u32 addr, vblank;
12048
12049         if (!atomic_read(&work->pending))
12050                 return false;
12051
12052         smp_rmb();
12053
12054         vblank = intel_crtc_get_vblank_counter(intel_crtc);
12055         if (work->flip_ready_vblank == 0) {
12056                 if (work->flip_queued_req &&
12057                     !i915_gem_request_completed(work->flip_queued_req))
12058                         return false;
12059
12060                 work->flip_ready_vblank = vblank;
12061         }
12062
12063         if (vblank - work->flip_ready_vblank < 3)
12064                 return false;
12065
12066         /* Potential stall - if we see that the flip has happened,
12067          * assume a missed interrupt. */
12068         if (INTEL_GEN(dev_priv) >= 4)
12069                 addr = I915_HI_DISPBASE(I915_READ(DSPSURF(intel_crtc->plane)));
12070         else
12071                 addr = I915_READ(DSPADDR(intel_crtc->plane));
12072
12073         /* There is a potential issue here with a false positive after a flip
12074          * to the same address. We could address this by checking for a
12075          * non-incrementing frame counter.
12076          */
12077         return addr == work->gtt_offset;
12078 }
12079
12080 void intel_check_page_flip(struct drm_i915_private *dev_priv, int pipe)
12081 {
12082         struct drm_device *dev = &dev_priv->drm;
12083         struct intel_crtc *crtc = intel_get_crtc_for_pipe(dev_priv, pipe);
12084         struct intel_flip_work *work;
12085
12086         WARN_ON(!in_interrupt());
12087
12088         if (crtc == NULL)
12089                 return;
12090
12091         spin_lock(&dev->event_lock);
12092         work = crtc->flip_work;
12093
12094         if (work != NULL && !is_mmio_work(work) &&
12095             __pageflip_stall_check_cs(dev_priv, crtc, work)) {
12096                 WARN_ONCE(1,
12097                           "Kicking stuck page flip: queued at %d, now %d\n",
12098                         work->flip_queued_vblank, intel_crtc_get_vblank_counter(crtc));
12099                 page_flip_completed(crtc);
12100                 work = NULL;
12101         }
12102
12103         if (work != NULL && !is_mmio_work(work) &&
12104             intel_crtc_get_vblank_counter(crtc) - work->flip_queued_vblank > 1)
12105                 intel_queue_rps_boost_for_request(work->flip_queued_req);
12106         spin_unlock(&dev->event_lock);
12107 }
12108
12109 static int intel_crtc_page_flip(struct drm_crtc *crtc,
12110                                 struct drm_framebuffer *fb,
12111                                 struct drm_pending_vblank_event *event,
12112                                 uint32_t page_flip_flags)
12113 {
12114         struct drm_device *dev = crtc->dev;
12115         struct drm_i915_private *dev_priv = to_i915(dev);
12116         struct drm_framebuffer *old_fb = crtc->primary->fb;
12117         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
12118         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
12119         struct drm_plane *primary = crtc->primary;
12120         enum pipe pipe = intel_crtc->pipe;
12121         struct intel_flip_work *work;
12122         struct intel_engine_cs *engine;
12123         bool mmio_flip;
12124         struct drm_i915_gem_request *request;
12125         struct i915_vma *vma;
12126         int ret;
12127
12128         /*
12129          * drm_mode_page_flip_ioctl() should already catch this, but double
12130          * check to be safe.  In the future we may enable pageflipping from
12131          * a disabled primary plane.
12132          */
12133         if (WARN_ON(intel_fb_obj(old_fb) == NULL))
12134                 return -EBUSY;
12135
12136         /* Can't change pixel format via MI display flips. */
12137         if (fb->pixel_format != crtc->primary->fb->pixel_format)
12138                 return -EINVAL;
12139
12140         /*
12141          * TILEOFF/LINOFF registers can't be changed via MI display flips.
12142          * Note that pitch changes could also affect these register.
12143          */
12144         if (INTEL_GEN(dev_priv) > 3 &&
12145             (fb->offsets[0] != crtc->primary->fb->offsets[0] ||
12146              fb->pitches[0] != crtc->primary->fb->pitches[0]))
12147                 return -EINVAL;
12148
12149         if (i915_terminally_wedged(&dev_priv->gpu_error))
12150                 goto out_hang;
12151
12152         work = kzalloc(sizeof(*work), GFP_KERNEL);
12153         if (work == NULL)
12154                 return -ENOMEM;
12155
12156         work->event = event;
12157         work->crtc = crtc;
12158         work->old_fb = old_fb;
12159         INIT_WORK(&work->unpin_work, intel_unpin_work_fn);
12160
12161         ret = drm_crtc_vblank_get(crtc);
12162         if (ret)
12163                 goto free_work;
12164
12165         /* We borrow the event spin lock for protecting flip_work */
12166         spin_lock_irq(&dev->event_lock);
12167         if (intel_crtc->flip_work) {
12168                 /* Before declaring the flip queue wedged, check if
12169                  * the hardware completed the operation behind our backs.
12170                  */
12171                 if (pageflip_finished(intel_crtc, intel_crtc->flip_work)) {
12172                         DRM_DEBUG_DRIVER("flip queue: previous flip completed, continuing\n");
12173                         page_flip_completed(intel_crtc);
12174                 } else {
12175                         DRM_DEBUG_DRIVER("flip queue: crtc already busy\n");
12176                         spin_unlock_irq(&dev->event_lock);
12177
12178                         drm_crtc_vblank_put(crtc);
12179                         kfree(work);
12180                         return -EBUSY;
12181                 }
12182         }
12183         intel_crtc->flip_work = work;
12184         spin_unlock_irq(&dev->event_lock);
12185
12186         if (atomic_read(&intel_crtc->unpin_work_count) >= 2)
12187                 flush_workqueue(dev_priv->wq);
12188
12189         /* Reference the objects for the scheduled work. */
12190         drm_framebuffer_reference(work->old_fb);
12191
12192         crtc->primary->fb = fb;
12193         update_state_fb(crtc->primary);
12194
12195         work->pending_flip_obj = i915_gem_object_get(obj);
12196
12197         ret = i915_mutex_lock_interruptible(dev);
12198         if (ret)
12199                 goto cleanup;
12200
12201         intel_crtc->reset_count = i915_reset_count(&dev_priv->gpu_error);
12202         if (i915_reset_in_progress_or_wedged(&dev_priv->gpu_error)) {
12203                 ret = -EIO;
12204                 goto unlock;
12205         }
12206
12207         atomic_inc(&intel_crtc->unpin_work_count);
12208
12209         if (INTEL_GEN(dev_priv) >= 5 || IS_G4X(dev_priv))
12210                 work->flip_count = I915_READ(PIPE_FLIPCOUNT_G4X(pipe)) + 1;
12211
12212         if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv)) {
12213                 engine = dev_priv->engine[BCS];
12214                 if (fb->modifier != old_fb->modifier)
12215                         /* vlv: DISPLAY_FLIP fails to change tiling */
12216                         engine = NULL;
12217         } else if (IS_IVYBRIDGE(dev_priv) || IS_HASWELL(dev_priv)) {
12218                 engine = dev_priv->engine[BCS];
12219         } else if (INTEL_GEN(dev_priv) >= 7) {
12220                 engine = i915_gem_object_last_write_engine(obj);
12221                 if (engine == NULL || engine->id != RCS)
12222                         engine = dev_priv->engine[BCS];
12223         } else {
12224                 engine = dev_priv->engine[RCS];
12225         }
12226
12227         mmio_flip = use_mmio_flip(engine, obj);
12228
12229         vma = intel_pin_and_fence_fb_obj(fb, primary->state->rotation);
12230         if (IS_ERR(vma)) {
12231                 ret = PTR_ERR(vma);
12232                 goto cleanup_pending;
12233         }
12234
12235         work->gtt_offset = intel_fb_gtt_offset(fb, primary->state->rotation);
12236         work->gtt_offset += intel_crtc->dspaddr_offset;
12237         work->rotation = crtc->primary->state->rotation;
12238
12239         /*
12240          * There's the potential that the next frame will not be compatible with
12241          * FBC, so we want to call pre_update() before the actual page flip.
12242          * The problem is that pre_update() caches some information about the fb
12243          * object, so we want to do this only after the object is pinned. Let's
12244          * be on the safe side and do this immediately before scheduling the
12245          * flip.
12246          */
12247         intel_fbc_pre_update(intel_crtc, intel_crtc->config,
12248                              to_intel_plane_state(primary->state));
12249
12250         if (mmio_flip) {
12251                 INIT_WORK(&work->mmio_work, intel_mmio_flip_work_func);
12252                 queue_work(system_unbound_wq, &work->mmio_work);
12253         } else {
12254                 request = i915_gem_request_alloc(engine, engine->last_context);
12255                 if (IS_ERR(request)) {
12256                         ret = PTR_ERR(request);
12257                         goto cleanup_unpin;
12258                 }
12259
12260                 ret = i915_gem_request_await_object(request, obj, false);
12261                 if (ret)
12262                         goto cleanup_request;
12263
12264                 ret = dev_priv->display.queue_flip(dev, crtc, fb, obj, request,
12265                                                    page_flip_flags);
12266                 if (ret)
12267                         goto cleanup_request;
12268
12269                 intel_mark_page_flip_active(intel_crtc, work);
12270
12271                 work->flip_queued_req = i915_gem_request_get(request);
12272                 i915_add_request_no_flush(request);
12273         }
12274
12275         i915_gem_object_wait_priority(obj, 0, I915_PRIORITY_DISPLAY);
12276         i915_gem_track_fb(intel_fb_obj(old_fb), obj,
12277                           to_intel_plane(primary)->frontbuffer_bit);
12278         mutex_unlock(&dev->struct_mutex);
12279
12280         intel_frontbuffer_flip_prepare(to_i915(dev),
12281                                        to_intel_plane(primary)->frontbuffer_bit);
12282
12283         trace_i915_flip_request(intel_crtc->plane, obj);
12284
12285         return 0;
12286
12287 cleanup_request:
12288         i915_add_request_no_flush(request);
12289 cleanup_unpin:
12290         intel_unpin_fb_obj(fb, crtc->primary->state->rotation);
12291 cleanup_pending:
12292         atomic_dec(&intel_crtc->unpin_work_count);
12293 unlock:
12294         mutex_unlock(&dev->struct_mutex);
12295 cleanup:
12296         crtc->primary->fb = old_fb;
12297         update_state_fb(crtc->primary);
12298
12299         i915_gem_object_put(obj);
12300         drm_framebuffer_unreference(work->old_fb);
12301
12302         spin_lock_irq(&dev->event_lock);
12303         intel_crtc->flip_work = NULL;
12304         spin_unlock_irq(&dev->event_lock);
12305
12306         drm_crtc_vblank_put(crtc);
12307 free_work:
12308         kfree(work);
12309
12310         if (ret == -EIO) {
12311                 struct drm_atomic_state *state;
12312                 struct drm_plane_state *plane_state;
12313
12314 out_hang:
12315                 state = drm_atomic_state_alloc(dev);
12316                 if (!state)
12317                         return -ENOMEM;
12318                 state->acquire_ctx = drm_modeset_legacy_acquire_ctx(crtc);
12319
12320 retry:
12321                 plane_state = drm_atomic_get_plane_state(state, primary);
12322                 ret = PTR_ERR_OR_ZERO(plane_state);
12323                 if (!ret) {
12324                         drm_atomic_set_fb_for_plane(plane_state, fb);
12325
12326                         ret = drm_atomic_set_crtc_for_plane(plane_state, crtc);
12327                         if (!ret)
12328                                 ret = drm_atomic_commit(state);
12329                 }
12330
12331                 if (ret == -EDEADLK) {
12332                         drm_modeset_backoff(state->acquire_ctx);
12333                         drm_atomic_state_clear(state);
12334                         goto retry;
12335                 }
12336
12337                 drm_atomic_state_put(state);
12338
12339                 if (ret == 0 && event) {
12340                         spin_lock_irq(&dev->event_lock);
12341                         drm_crtc_send_vblank_event(crtc, event);
12342                         spin_unlock_irq(&dev->event_lock);
12343                 }
12344         }
12345         return ret;
12346 }
12347
12348
12349 /**
12350  * intel_wm_need_update - Check whether watermarks need updating
12351  * @plane: drm plane
12352  * @state: new plane state
12353  *
12354  * Check current plane state versus the new one to determine whether
12355  * watermarks need to be recalculated.
12356  *
12357  * Returns true or false.
12358  */
12359 static bool intel_wm_need_update(struct drm_plane *plane,
12360                                  struct drm_plane_state *state)
12361 {
12362         struct intel_plane_state *new = to_intel_plane_state(state);
12363         struct intel_plane_state *cur = to_intel_plane_state(plane->state);
12364
12365         /* Update watermarks on tiling or size changes. */
12366         if (new->base.visible != cur->base.visible)
12367                 return true;
12368
12369         if (!cur->base.fb || !new->base.fb)
12370                 return false;
12371
12372         if (cur->base.fb->modifier != new->base.fb->modifier ||
12373             cur->base.rotation != new->base.rotation ||
12374             drm_rect_width(&new->base.src) != drm_rect_width(&cur->base.src) ||
12375             drm_rect_height(&new->base.src) != drm_rect_height(&cur->base.src) ||
12376             drm_rect_width(&new->base.dst) != drm_rect_width(&cur->base.dst) ||
12377             drm_rect_height(&new->base.dst) != drm_rect_height(&cur->base.dst))
12378                 return true;
12379
12380         return false;
12381 }
12382
12383 static bool needs_scaling(struct intel_plane_state *state)
12384 {
12385         int src_w = drm_rect_width(&state->base.src) >> 16;
12386         int src_h = drm_rect_height(&state->base.src) >> 16;
12387         int dst_w = drm_rect_width(&state->base.dst);
12388         int dst_h = drm_rect_height(&state->base.dst);
12389
12390         return (src_w != dst_w || src_h != dst_h);
12391 }
12392
12393 int intel_plane_atomic_calc_changes(struct drm_crtc_state *crtc_state,
12394                                     struct drm_plane_state *plane_state)
12395 {
12396         struct intel_crtc_state *pipe_config = to_intel_crtc_state(crtc_state);
12397         struct drm_crtc *crtc = crtc_state->crtc;
12398         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
12399         struct drm_plane *plane = plane_state->plane;
12400         struct drm_device *dev = crtc->dev;
12401         struct drm_i915_private *dev_priv = to_i915(dev);
12402         struct intel_plane_state *old_plane_state =
12403                 to_intel_plane_state(plane->state);
12404         bool mode_changed = needs_modeset(crtc_state);
12405         bool was_crtc_enabled = crtc->state->active;
12406         bool is_crtc_enabled = crtc_state->active;
12407         bool turn_off, turn_on, visible, was_visible;
12408         struct drm_framebuffer *fb = plane_state->fb;
12409         int ret;
12410
12411         if (INTEL_GEN(dev_priv) >= 9 && plane->type != DRM_PLANE_TYPE_CURSOR) {
12412                 ret = skl_update_scaler_plane(
12413                         to_intel_crtc_state(crtc_state),
12414                         to_intel_plane_state(plane_state));
12415                 if (ret)
12416                         return ret;
12417         }
12418
12419         was_visible = old_plane_state->base.visible;
12420         visible = to_intel_plane_state(plane_state)->base.visible;
12421
12422         if (!was_crtc_enabled && WARN_ON(was_visible))
12423                 was_visible = false;
12424
12425         /*
12426          * Visibility is calculated as if the crtc was on, but
12427          * after scaler setup everything depends on it being off
12428          * when the crtc isn't active.
12429          *
12430          * FIXME this is wrong for watermarks. Watermarks should also
12431          * be computed as if the pipe would be active. Perhaps move
12432          * per-plane wm computation to the .check_plane() hook, and
12433          * only combine the results from all planes in the current place?
12434          */
12435         if (!is_crtc_enabled)
12436                 to_intel_plane_state(plane_state)->base.visible = visible = false;
12437
12438         if (!was_visible && !visible)
12439                 return 0;
12440
12441         if (fb != old_plane_state->base.fb)
12442                 pipe_config->fb_changed = true;
12443
12444         turn_off = was_visible && (!visible || mode_changed);
12445         turn_on = visible && (!was_visible || mode_changed);
12446
12447         DRM_DEBUG_ATOMIC("[CRTC:%d:%s] has [PLANE:%d:%s] with fb %i\n",
12448                          intel_crtc->base.base.id,
12449                          intel_crtc->base.name,
12450                          plane->base.id, plane->name,
12451                          fb ? fb->base.id : -1);
12452
12453         DRM_DEBUG_ATOMIC("[PLANE:%d:%s] visible %i -> %i, off %i, on %i, ms %i\n",
12454                          plane->base.id, plane->name,
12455                          was_visible, visible,
12456                          turn_off, turn_on, mode_changed);
12457
12458         if (turn_on) {
12459                 pipe_config->update_wm_pre = true;
12460
12461                 /* must disable cxsr around plane enable/disable */
12462                 if (plane->type != DRM_PLANE_TYPE_CURSOR)
12463                         pipe_config->disable_cxsr = true;
12464         } else if (turn_off) {
12465                 pipe_config->update_wm_post = true;
12466
12467                 /* must disable cxsr around plane enable/disable */
12468                 if (plane->type != DRM_PLANE_TYPE_CURSOR)
12469                         pipe_config->disable_cxsr = true;
12470         } else if (intel_wm_need_update(plane, plane_state)) {
12471                 /* FIXME bollocks */
12472                 pipe_config->update_wm_pre = true;
12473                 pipe_config->update_wm_post = true;
12474         }
12475
12476         /* Pre-gen9 platforms need two-step watermark updates */
12477         if ((pipe_config->update_wm_pre || pipe_config->update_wm_post) &&
12478             INTEL_GEN(dev_priv) < 9 && dev_priv->display.optimize_watermarks)
12479                 to_intel_crtc_state(crtc_state)->wm.need_postvbl_update = true;
12480
12481         if (visible || was_visible)
12482                 pipe_config->fb_bits |= to_intel_plane(plane)->frontbuffer_bit;
12483
12484         /*
12485          * WaCxSRDisabledForSpriteScaling:ivb
12486          *
12487          * cstate->update_wm was already set above, so this flag will
12488          * take effect when we commit and program watermarks.
12489          */
12490         if (plane->type == DRM_PLANE_TYPE_OVERLAY && IS_IVYBRIDGE(dev_priv) &&
12491             needs_scaling(to_intel_plane_state(plane_state)) &&
12492             !needs_scaling(old_plane_state))
12493                 pipe_config->disable_lp_wm = true;
12494
12495         return 0;
12496 }
12497
12498 static bool encoders_cloneable(const struct intel_encoder *a,
12499                                const struct intel_encoder *b)
12500 {
12501         /* masks could be asymmetric, so check both ways */
12502         return a == b || (a->cloneable & (1 << b->type) &&
12503                           b->cloneable & (1 << a->type));
12504 }
12505
12506 static bool check_single_encoder_cloning(struct drm_atomic_state *state,
12507                                          struct intel_crtc *crtc,
12508                                          struct intel_encoder *encoder)
12509 {
12510         struct intel_encoder *source_encoder;
12511         struct drm_connector *connector;
12512         struct drm_connector_state *connector_state;
12513         int i;
12514
12515         for_each_connector_in_state(state, connector, connector_state, i) {
12516                 if (connector_state->crtc != &crtc->base)
12517                         continue;
12518
12519                 source_encoder =
12520                         to_intel_encoder(connector_state->best_encoder);
12521                 if (!encoders_cloneable(encoder, source_encoder))
12522                         return false;
12523         }
12524
12525         return true;
12526 }
12527
12528 static int intel_crtc_atomic_check(struct drm_crtc *crtc,
12529                                    struct drm_crtc_state *crtc_state)
12530 {
12531         struct drm_device *dev = crtc->dev;
12532         struct drm_i915_private *dev_priv = to_i915(dev);
12533         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
12534         struct intel_crtc_state *pipe_config =
12535                 to_intel_crtc_state(crtc_state);
12536         struct drm_atomic_state *state = crtc_state->state;
12537         int ret;
12538         bool mode_changed = needs_modeset(crtc_state);
12539
12540         if (mode_changed && !crtc_state->active)
12541                 pipe_config->update_wm_post = true;
12542
12543         if (mode_changed && crtc_state->enable &&
12544             dev_priv->display.crtc_compute_clock &&
12545             !WARN_ON(pipe_config->shared_dpll)) {
12546                 ret = dev_priv->display.crtc_compute_clock(intel_crtc,
12547                                                            pipe_config);
12548                 if (ret)
12549                         return ret;
12550         }
12551
12552         if (crtc_state->color_mgmt_changed) {
12553                 ret = intel_color_check(crtc, crtc_state);
12554                 if (ret)
12555                         return ret;
12556
12557                 /*
12558                  * Changing color management on Intel hardware is
12559                  * handled as part of planes update.
12560                  */
12561                 crtc_state->planes_changed = true;
12562         }
12563
12564         ret = 0;
12565         if (dev_priv->display.compute_pipe_wm) {
12566                 ret = dev_priv->display.compute_pipe_wm(pipe_config);
12567                 if (ret) {
12568                         DRM_DEBUG_KMS("Target pipe watermarks are invalid\n");
12569                         return ret;
12570                 }
12571         }
12572
12573         if (dev_priv->display.compute_intermediate_wm &&
12574             !to_intel_atomic_state(state)->skip_intermediate_wm) {
12575                 if (WARN_ON(!dev_priv->display.compute_pipe_wm))
12576                         return 0;
12577
12578                 /*
12579                  * Calculate 'intermediate' watermarks that satisfy both the
12580                  * old state and the new state.  We can program these
12581                  * immediately.
12582                  */
12583                 ret = dev_priv->display.compute_intermediate_wm(dev,
12584                                                                 intel_crtc,
12585                                                                 pipe_config);
12586                 if (ret) {
12587                         DRM_DEBUG_KMS("No valid intermediate pipe watermarks are possible\n");
12588                         return ret;
12589                 }
12590         } else if (dev_priv->display.compute_intermediate_wm) {
12591                 if (HAS_PCH_SPLIT(dev_priv) && INTEL_GEN(dev_priv) < 9)
12592                         pipe_config->wm.ilk.intermediate = pipe_config->wm.ilk.optimal;
12593         }
12594
12595         if (INTEL_GEN(dev_priv) >= 9) {
12596                 if (mode_changed)
12597                         ret = skl_update_scaler_crtc(pipe_config);
12598
12599                 if (!ret)
12600                         ret = intel_atomic_setup_scalers(dev, intel_crtc,
12601                                                          pipe_config);
12602         }
12603
12604         return ret;
12605 }
12606
12607 static const struct drm_crtc_helper_funcs intel_helper_funcs = {
12608         .mode_set_base_atomic = intel_pipe_set_base_atomic,
12609         .atomic_begin = intel_begin_crtc_commit,
12610         .atomic_flush = intel_finish_crtc_commit,
12611         .atomic_check = intel_crtc_atomic_check,
12612 };
12613
12614 static void intel_modeset_update_connector_atomic_state(struct drm_device *dev)
12615 {
12616         struct intel_connector *connector;
12617
12618         for_each_intel_connector(dev, connector) {
12619                 if (connector->base.state->crtc)
12620                         drm_connector_unreference(&connector->base);
12621
12622                 if (connector->base.encoder) {
12623                         connector->base.state->best_encoder =
12624                                 connector->base.encoder;
12625                         connector->base.state->crtc =
12626                                 connector->base.encoder->crtc;
12627
12628                         drm_connector_reference(&connector->base);
12629                 } else {
12630                         connector->base.state->best_encoder = NULL;
12631                         connector->base.state->crtc = NULL;
12632                 }
12633         }
12634 }
12635
12636 static void
12637 connected_sink_compute_bpp(struct intel_connector *connector,
12638                            struct intel_crtc_state *pipe_config)
12639 {
12640         const struct drm_display_info *info = &connector->base.display_info;
12641         int bpp = pipe_config->pipe_bpp;
12642
12643         DRM_DEBUG_KMS("[CONNECTOR:%d:%s] checking for sink bpp constrains\n",
12644                       connector->base.base.id,
12645                       connector->base.name);
12646
12647         /* Don't use an invalid EDID bpc value */
12648         if (info->bpc != 0 && info->bpc * 3 < bpp) {
12649                 DRM_DEBUG_KMS("clamping display bpp (was %d) to EDID reported max of %d\n",
12650                               bpp, info->bpc * 3);
12651                 pipe_config->pipe_bpp = info->bpc * 3;
12652         }
12653
12654         /* Clamp bpp to 8 on screens without EDID 1.4 */
12655         if (info->bpc == 0 && bpp > 24) {
12656                 DRM_DEBUG_KMS("clamping display bpp (was %d) to default limit of 24\n",
12657                               bpp);
12658                 pipe_config->pipe_bpp = 24;
12659         }
12660 }
12661
12662 static int
12663 compute_baseline_pipe_bpp(struct intel_crtc *crtc,
12664                           struct intel_crtc_state *pipe_config)
12665 {
12666         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
12667         struct drm_atomic_state *state;
12668         struct drm_connector *connector;
12669         struct drm_connector_state *connector_state;
12670         int bpp, i;
12671
12672         if ((IS_G4X(dev_priv) || IS_VALLEYVIEW(dev_priv) ||
12673             IS_CHERRYVIEW(dev_priv)))
12674                 bpp = 10*3;
12675         else if (INTEL_GEN(dev_priv) >= 5)
12676                 bpp = 12*3;
12677         else
12678                 bpp = 8*3;
12679
12680
12681         pipe_config->pipe_bpp = bpp;
12682
12683         state = pipe_config->base.state;
12684
12685         /* Clamp display bpp to EDID value */
12686         for_each_connector_in_state(state, connector, connector_state, i) {
12687                 if (connector_state->crtc != &crtc->base)
12688                         continue;
12689
12690                 connected_sink_compute_bpp(to_intel_connector(connector),
12691                                            pipe_config);
12692         }
12693
12694         return bpp;
12695 }
12696
12697 static void intel_dump_crtc_timings(const struct drm_display_mode *mode)
12698 {
12699         DRM_DEBUG_KMS("crtc timings: %d %d %d %d %d %d %d %d %d, "
12700                         "type: 0x%x flags: 0x%x\n",
12701                 mode->crtc_clock,
12702                 mode->crtc_hdisplay, mode->crtc_hsync_start,
12703                 mode->crtc_hsync_end, mode->crtc_htotal,
12704                 mode->crtc_vdisplay, mode->crtc_vsync_start,
12705                 mode->crtc_vsync_end, mode->crtc_vtotal, mode->type, mode->flags);
12706 }
12707
12708 static inline void
12709 intel_dump_m_n_config(struct intel_crtc_state *pipe_config, char *id,
12710                       unsigned int lane_count, struct intel_link_m_n *m_n)
12711 {
12712         DRM_DEBUG_KMS("%s: lanes: %i; gmch_m: %u, gmch_n: %u, link_m: %u, link_n: %u, tu: %u\n",
12713                       id, lane_count,
12714                       m_n->gmch_m, m_n->gmch_n,
12715                       m_n->link_m, m_n->link_n, m_n->tu);
12716 }
12717
12718 static void intel_dump_pipe_config(struct intel_crtc *crtc,
12719                                    struct intel_crtc_state *pipe_config,
12720                                    const char *context)
12721 {
12722         struct drm_device *dev = crtc->base.dev;
12723         struct drm_i915_private *dev_priv = to_i915(dev);
12724         struct drm_plane *plane;
12725         struct intel_plane *intel_plane;
12726         struct intel_plane_state *state;
12727         struct drm_framebuffer *fb;
12728
12729         DRM_DEBUG_KMS("[CRTC:%d:%s]%s\n",
12730                       crtc->base.base.id, crtc->base.name, context);
12731
12732         DRM_DEBUG_KMS("cpu_transcoder: %s, pipe bpp: %i, dithering: %i\n",
12733                       transcoder_name(pipe_config->cpu_transcoder),
12734                       pipe_config->pipe_bpp, pipe_config->dither);
12735
12736         if (pipe_config->has_pch_encoder)
12737                 intel_dump_m_n_config(pipe_config, "fdi",
12738                                       pipe_config->fdi_lanes,
12739                                       &pipe_config->fdi_m_n);
12740
12741         if (intel_crtc_has_dp_encoder(pipe_config)) {
12742                 intel_dump_m_n_config(pipe_config, "dp m_n",
12743                                 pipe_config->lane_count, &pipe_config->dp_m_n);
12744                 if (pipe_config->has_drrs)
12745                         intel_dump_m_n_config(pipe_config, "dp m2_n2",
12746                                               pipe_config->lane_count,
12747                                               &pipe_config->dp_m2_n2);
12748         }
12749
12750         DRM_DEBUG_KMS("audio: %i, infoframes: %i\n",
12751                       pipe_config->has_audio, pipe_config->has_infoframe);
12752
12753         DRM_DEBUG_KMS("requested mode:\n");
12754         drm_mode_debug_printmodeline(&pipe_config->base.mode);
12755         DRM_DEBUG_KMS("adjusted mode:\n");
12756         drm_mode_debug_printmodeline(&pipe_config->base.adjusted_mode);
12757         intel_dump_crtc_timings(&pipe_config->base.adjusted_mode);
12758         DRM_DEBUG_KMS("port clock: %d, pipe src size: %dx%d\n",
12759                       pipe_config->port_clock,
12760                       pipe_config->pipe_src_w, pipe_config->pipe_src_h);
12761
12762         if (INTEL_GEN(dev_priv) >= 9)
12763                 DRM_DEBUG_KMS("num_scalers: %d, scaler_users: 0x%x, scaler_id: %d\n",
12764                               crtc->num_scalers,
12765                               pipe_config->scaler_state.scaler_users,
12766                               pipe_config->scaler_state.scaler_id);
12767
12768         if (HAS_GMCH_DISPLAY(dev_priv))
12769                 DRM_DEBUG_KMS("gmch pfit: control: 0x%08x, ratios: 0x%08x, lvds border: 0x%08x\n",
12770                               pipe_config->gmch_pfit.control,
12771                               pipe_config->gmch_pfit.pgm_ratios,
12772                               pipe_config->gmch_pfit.lvds_border_bits);
12773         else
12774                 DRM_DEBUG_KMS("pch pfit: pos: 0x%08x, size: 0x%08x, %s\n",
12775                               pipe_config->pch_pfit.pos,
12776                               pipe_config->pch_pfit.size,
12777                               enableddisabled(pipe_config->pch_pfit.enabled));
12778
12779         DRM_DEBUG_KMS("ips: %i, double wide: %i\n",
12780                       pipe_config->ips_enabled, pipe_config->double_wide);
12781
12782         if (IS_BROXTON(dev_priv)) {
12783                 DRM_DEBUG_KMS("dpll_hw_state: ebb0: 0x%x, ebb4: 0x%x,"
12784                               "pll0: 0x%x, pll1: 0x%x, pll2: 0x%x, pll3: 0x%x, "
12785                               "pll6: 0x%x, pll8: 0x%x, pll9: 0x%x, pll10: 0x%x, pcsdw12: 0x%x\n",
12786                               pipe_config->dpll_hw_state.ebb0,
12787                               pipe_config->dpll_hw_state.ebb4,
12788                               pipe_config->dpll_hw_state.pll0,
12789                               pipe_config->dpll_hw_state.pll1,
12790                               pipe_config->dpll_hw_state.pll2,
12791                               pipe_config->dpll_hw_state.pll3,
12792                               pipe_config->dpll_hw_state.pll6,
12793                               pipe_config->dpll_hw_state.pll8,
12794                               pipe_config->dpll_hw_state.pll9,
12795                               pipe_config->dpll_hw_state.pll10,
12796                               pipe_config->dpll_hw_state.pcsdw12);
12797         } else if (IS_SKYLAKE(dev_priv) || IS_KABYLAKE(dev_priv)) {
12798                 DRM_DEBUG_KMS("dpll_hw_state: "
12799                               "ctrl1: 0x%x, cfgcr1: 0x%x, cfgcr2: 0x%x\n",
12800                               pipe_config->dpll_hw_state.ctrl1,
12801                               pipe_config->dpll_hw_state.cfgcr1,
12802                               pipe_config->dpll_hw_state.cfgcr2);
12803         } else if (HAS_DDI(dev_priv)) {
12804                 DRM_DEBUG_KMS("dpll_hw_state: wrpll: 0x%x spll: 0x%x\n",
12805                               pipe_config->dpll_hw_state.wrpll,
12806                               pipe_config->dpll_hw_state.spll);
12807         } else {
12808                 DRM_DEBUG_KMS("dpll_hw_state: dpll: 0x%x, dpll_md: 0x%x, "
12809                               "fp0: 0x%x, fp1: 0x%x\n",
12810                               pipe_config->dpll_hw_state.dpll,
12811                               pipe_config->dpll_hw_state.dpll_md,
12812                               pipe_config->dpll_hw_state.fp0,
12813                               pipe_config->dpll_hw_state.fp1);
12814         }
12815
12816         DRM_DEBUG_KMS("planes on this crtc\n");
12817         list_for_each_entry(plane, &dev->mode_config.plane_list, head) {
12818                 struct drm_format_name_buf format_name;
12819                 intel_plane = to_intel_plane(plane);
12820                 if (intel_plane->pipe != crtc->pipe)
12821                         continue;
12822
12823                 state = to_intel_plane_state(plane->state);
12824                 fb = state->base.fb;
12825                 if (!fb) {
12826                         DRM_DEBUG_KMS("[PLANE:%d:%s] disabled, scaler_id = %d\n",
12827                                       plane->base.id, plane->name, state->scaler_id);
12828                         continue;
12829                 }
12830
12831                 DRM_DEBUG_KMS("[PLANE:%d:%s] FB:%d, fb = %ux%u format = %s\n",
12832                               plane->base.id, plane->name,
12833                               fb->base.id, fb->width, fb->height,
12834                               drm_get_format_name(fb->pixel_format, &format_name));
12835                 if (INTEL_GEN(dev_priv) >= 9)
12836                         DRM_DEBUG_KMS("\tscaler:%d src %dx%d+%d+%d dst %dx%d+%d+%d\n",
12837                                       state->scaler_id,
12838                                       state->base.src.x1 >> 16,
12839                                       state->base.src.y1 >> 16,
12840                                       drm_rect_width(&state->base.src) >> 16,
12841                                       drm_rect_height(&state->base.src) >> 16,
12842                                       state->base.dst.x1, state->base.dst.y1,
12843                                       drm_rect_width(&state->base.dst),
12844                                       drm_rect_height(&state->base.dst));
12845         }
12846 }
12847
12848 static bool check_digital_port_conflicts(struct drm_atomic_state *state)
12849 {
12850         struct drm_device *dev = state->dev;
12851         struct drm_connector *connector;
12852         unsigned int used_ports = 0;
12853         unsigned int used_mst_ports = 0;
12854
12855         /*
12856          * Walk the connector list instead of the encoder
12857          * list to detect the problem on ddi platforms
12858          * where there's just one encoder per digital port.
12859          */
12860         drm_for_each_connector(connector, dev) {
12861                 struct drm_connector_state *connector_state;
12862                 struct intel_encoder *encoder;
12863
12864                 connector_state = drm_atomic_get_existing_connector_state(state, connector);
12865                 if (!connector_state)
12866                         connector_state = connector->state;
12867
12868                 if (!connector_state->best_encoder)
12869                         continue;
12870
12871                 encoder = to_intel_encoder(connector_state->best_encoder);
12872
12873                 WARN_ON(!connector_state->crtc);
12874
12875                 switch (encoder->type) {
12876                         unsigned int port_mask;
12877                 case INTEL_OUTPUT_UNKNOWN:
12878                         if (WARN_ON(!HAS_DDI(to_i915(dev))))
12879                                 break;
12880                 case INTEL_OUTPUT_DP:
12881                 case INTEL_OUTPUT_HDMI:
12882                 case INTEL_OUTPUT_EDP:
12883                         port_mask = 1 << enc_to_dig_port(&encoder->base)->port;
12884
12885                         /* the same port mustn't appear more than once */
12886                         if (used_ports & port_mask)
12887                                 return false;
12888
12889                         used_ports |= port_mask;
12890                         break;
12891                 case INTEL_OUTPUT_DP_MST:
12892                         used_mst_ports |=
12893                                 1 << enc_to_mst(&encoder->base)->primary->port;
12894                         break;
12895                 default:
12896                         break;
12897                 }
12898         }
12899
12900         /* can't mix MST and SST/HDMI on the same port */
12901         if (used_ports & used_mst_ports)
12902                 return false;
12903
12904         return true;
12905 }
12906
12907 static void
12908 clear_intel_crtc_state(struct intel_crtc_state *crtc_state)
12909 {
12910         struct drm_crtc_state tmp_state;
12911         struct intel_crtc_scaler_state scaler_state;
12912         struct intel_dpll_hw_state dpll_hw_state;
12913         struct intel_shared_dpll *shared_dpll;
12914         bool force_thru;
12915
12916         /* FIXME: before the switch to atomic started, a new pipe_config was
12917          * kzalloc'd. Code that depends on any field being zero should be
12918          * fixed, so that the crtc_state can be safely duplicated. For now,
12919          * only fields that are know to not cause problems are preserved. */
12920
12921         tmp_state = crtc_state->base;
12922         scaler_state = crtc_state->scaler_state;
12923         shared_dpll = crtc_state->shared_dpll;
12924         dpll_hw_state = crtc_state->dpll_hw_state;
12925         force_thru = crtc_state->pch_pfit.force_thru;
12926
12927         memset(crtc_state, 0, sizeof *crtc_state);
12928
12929         crtc_state->base = tmp_state;
12930         crtc_state->scaler_state = scaler_state;
12931         crtc_state->shared_dpll = shared_dpll;
12932         crtc_state->dpll_hw_state = dpll_hw_state;
12933         crtc_state->pch_pfit.force_thru = force_thru;
12934 }
12935
12936 static int
12937 intel_modeset_pipe_config(struct drm_crtc *crtc,
12938                           struct intel_crtc_state *pipe_config)
12939 {
12940         struct drm_atomic_state *state = pipe_config->base.state;
12941         struct intel_encoder *encoder;
12942         struct drm_connector *connector;
12943         struct drm_connector_state *connector_state;
12944         int base_bpp, ret = -EINVAL;
12945         int i;
12946         bool retry = true;
12947
12948         clear_intel_crtc_state(pipe_config);
12949
12950         pipe_config->cpu_transcoder =
12951                 (enum transcoder) to_intel_crtc(crtc)->pipe;
12952
12953         /*
12954          * Sanitize sync polarity flags based on requested ones. If neither
12955          * positive or negative polarity is requested, treat this as meaning
12956          * negative polarity.
12957          */
12958         if (!(pipe_config->base.adjusted_mode.flags &
12959               (DRM_MODE_FLAG_PHSYNC | DRM_MODE_FLAG_NHSYNC)))
12960                 pipe_config->base.adjusted_mode.flags |= DRM_MODE_FLAG_NHSYNC;
12961
12962         if (!(pipe_config->base.adjusted_mode.flags &
12963               (DRM_MODE_FLAG_PVSYNC | DRM_MODE_FLAG_NVSYNC)))
12964                 pipe_config->base.adjusted_mode.flags |= DRM_MODE_FLAG_NVSYNC;
12965
12966         base_bpp = compute_baseline_pipe_bpp(to_intel_crtc(crtc),
12967                                              pipe_config);
12968         if (base_bpp < 0)
12969                 goto fail;
12970
12971         /*
12972          * Determine the real pipe dimensions. Note that stereo modes can
12973          * increase the actual pipe size due to the frame doubling and
12974          * insertion of additional space for blanks between the frame. This
12975          * is stored in the crtc timings. We use the requested mode to do this
12976          * computation to clearly distinguish it from the adjusted mode, which
12977          * can be changed by the connectors in the below retry loop.
12978          */
12979         drm_crtc_get_hv_timing(&pipe_config->base.mode,
12980                                &pipe_config->pipe_src_w,
12981                                &pipe_config->pipe_src_h);
12982
12983         for_each_connector_in_state(state, connector, connector_state, i) {
12984                 if (connector_state->crtc != crtc)
12985                         continue;
12986
12987                 encoder = to_intel_encoder(connector_state->best_encoder);
12988
12989                 if (!check_single_encoder_cloning(state, to_intel_crtc(crtc), encoder)) {
12990                         DRM_DEBUG_KMS("rejecting invalid cloning configuration\n");
12991                         goto fail;
12992                 }
12993
12994                 /*
12995                  * Determine output_types before calling the .compute_config()
12996                  * hooks so that the hooks can use this information safely.
12997                  */
12998                 pipe_config->output_types |= 1 << encoder->type;
12999         }
13000
13001 encoder_retry:
13002         /* Ensure the port clock defaults are reset when retrying. */
13003         pipe_config->port_clock = 0;
13004         pipe_config->pixel_multiplier = 1;
13005
13006         /* Fill in default crtc timings, allow encoders to overwrite them. */
13007         drm_mode_set_crtcinfo(&pipe_config->base.adjusted_mode,
13008                               CRTC_STEREO_DOUBLE);
13009
13010         /* Pass our mode to the connectors and the CRTC to give them a chance to
13011          * adjust it according to limitations or connector properties, and also
13012          * a chance to reject the mode entirely.
13013          */
13014         for_each_connector_in_state(state, connector, connector_state, i) {
13015                 if (connector_state->crtc != crtc)
13016                         continue;
13017
13018                 encoder = to_intel_encoder(connector_state->best_encoder);
13019
13020                 if (!(encoder->compute_config(encoder, pipe_config, connector_state))) {
13021                         DRM_DEBUG_KMS("Encoder config failure\n");
13022                         goto fail;
13023                 }
13024         }
13025
13026         /* Set default port clock if not overwritten by the encoder. Needs to be
13027          * done afterwards in case the encoder adjusts the mode. */
13028         if (!pipe_config->port_clock)
13029                 pipe_config->port_clock = pipe_config->base.adjusted_mode.crtc_clock
13030                         * pipe_config->pixel_multiplier;
13031
13032         ret = intel_crtc_compute_config(to_intel_crtc(crtc), pipe_config);
13033         if (ret < 0) {
13034                 DRM_DEBUG_KMS("CRTC fixup failed\n");
13035                 goto fail;
13036         }
13037
13038         if (ret == RETRY) {
13039                 if (WARN(!retry, "loop in pipe configuration computation\n")) {
13040                         ret = -EINVAL;
13041                         goto fail;
13042                 }
13043
13044                 DRM_DEBUG_KMS("CRTC bw constrained, retrying\n");
13045                 retry = false;
13046                 goto encoder_retry;
13047         }
13048
13049         /* Dithering seems to not pass-through bits correctly when it should, so
13050          * only enable it on 6bpc panels. */
13051         pipe_config->dither = pipe_config->pipe_bpp == 6*3;
13052         DRM_DEBUG_KMS("hw max bpp: %i, pipe bpp: %i, dithering: %i\n",
13053                       base_bpp, pipe_config->pipe_bpp, pipe_config->dither);
13054
13055 fail:
13056         return ret;
13057 }
13058
13059 static void
13060 intel_modeset_update_crtc_state(struct drm_atomic_state *state)
13061 {
13062         struct drm_crtc *crtc;
13063         struct drm_crtc_state *crtc_state;
13064         int i;
13065
13066         /* Double check state. */
13067         for_each_crtc_in_state(state, crtc, crtc_state, i) {
13068                 to_intel_crtc(crtc)->config = to_intel_crtc_state(crtc->state);
13069
13070                 /* Update hwmode for vblank functions */
13071                 if (crtc->state->active)
13072                         crtc->hwmode = crtc->state->adjusted_mode;
13073                 else
13074                         crtc->hwmode.crtc_clock = 0;
13075
13076                 /*
13077                  * Update legacy state to satisfy fbc code. This can
13078                  * be removed when fbc uses the atomic state.
13079                  */
13080                 if (drm_atomic_get_existing_plane_state(state, crtc->primary)) {
13081                         struct drm_plane_state *plane_state = crtc->primary->state;
13082
13083                         crtc->primary->fb = plane_state->fb;
13084                         crtc->x = plane_state->src_x >> 16;
13085                         crtc->y = plane_state->src_y >> 16;
13086                 }
13087         }
13088 }
13089
13090 static bool intel_fuzzy_clock_check(int clock1, int clock2)
13091 {
13092         int diff;
13093
13094         if (clock1 == clock2)
13095                 return true;
13096
13097         if (!clock1 || !clock2)
13098                 return false;
13099
13100         diff = abs(clock1 - clock2);
13101
13102         if (((((diff + clock1 + clock2) * 100)) / (clock1 + clock2)) < 105)
13103                 return true;
13104
13105         return false;
13106 }
13107
13108 static bool
13109 intel_compare_m_n(unsigned int m, unsigned int n,
13110                   unsigned int m2, unsigned int n2,
13111                   bool exact)
13112 {
13113         if (m == m2 && n == n2)
13114                 return true;
13115
13116         if (exact || !m || !n || !m2 || !n2)
13117                 return false;
13118
13119         BUILD_BUG_ON(DATA_LINK_M_N_MASK > INT_MAX);
13120
13121         if (n > n2) {
13122                 while (n > n2) {
13123                         m2 <<= 1;
13124                         n2 <<= 1;
13125                 }
13126         } else if (n < n2) {
13127                 while (n < n2) {
13128                         m <<= 1;
13129                         n <<= 1;
13130                 }
13131         }
13132
13133         if (n != n2)
13134                 return false;
13135
13136         return intel_fuzzy_clock_check(m, m2);
13137 }
13138
13139 static bool
13140 intel_compare_link_m_n(const struct intel_link_m_n *m_n,
13141                        struct intel_link_m_n *m2_n2,
13142                        bool adjust)
13143 {
13144         if (m_n->tu == m2_n2->tu &&
13145             intel_compare_m_n(m_n->gmch_m, m_n->gmch_n,
13146                               m2_n2->gmch_m, m2_n2->gmch_n, !adjust) &&
13147             intel_compare_m_n(m_n->link_m, m_n->link_n,
13148                               m2_n2->link_m, m2_n2->link_n, !adjust)) {
13149                 if (adjust)
13150                         *m2_n2 = *m_n;
13151
13152                 return true;
13153         }
13154
13155         return false;
13156 }
13157
13158 static bool
13159 intel_pipe_config_compare(struct drm_i915_private *dev_priv,
13160                           struct intel_crtc_state *current_config,
13161                           struct intel_crtc_state *pipe_config,
13162                           bool adjust)
13163 {
13164         bool ret = true;
13165
13166 #define INTEL_ERR_OR_DBG_KMS(fmt, ...) \
13167         do { \
13168                 if (!adjust) \
13169                         DRM_ERROR(fmt, ##__VA_ARGS__); \
13170                 else \
13171                         DRM_DEBUG_KMS(fmt, ##__VA_ARGS__); \
13172         } while (0)
13173
13174 #define PIPE_CONF_CHECK_X(name) \
13175         if (current_config->name != pipe_config->name) { \
13176                 INTEL_ERR_OR_DBG_KMS("mismatch in " #name " " \
13177                           "(expected 0x%08x, found 0x%08x)\n", \
13178                           current_config->name, \
13179                           pipe_config->name); \
13180                 ret = false; \
13181         }
13182
13183 #define PIPE_CONF_CHECK_I(name) \
13184         if (current_config->name != pipe_config->name) { \
13185                 INTEL_ERR_OR_DBG_KMS("mismatch in " #name " " \
13186                           "(expected %i, found %i)\n", \
13187                           current_config->name, \
13188                           pipe_config->name); \
13189                 ret = false; \
13190         }
13191
13192 #define PIPE_CONF_CHECK_P(name) \
13193         if (current_config->name != pipe_config->name) { \
13194                 INTEL_ERR_OR_DBG_KMS("mismatch in " #name " " \
13195                           "(expected %p, found %p)\n", \
13196                           current_config->name, \
13197                           pipe_config->name); \
13198                 ret = false; \
13199         }
13200
13201 #define PIPE_CONF_CHECK_M_N(name) \
13202         if (!intel_compare_link_m_n(&current_config->name, \
13203                                     &pipe_config->name,\
13204                                     adjust)) { \
13205                 INTEL_ERR_OR_DBG_KMS("mismatch in " #name " " \
13206                           "(expected tu %i gmch %i/%i link %i/%i, " \
13207                           "found tu %i, gmch %i/%i link %i/%i)\n", \
13208                           current_config->name.tu, \
13209                           current_config->name.gmch_m, \
13210                           current_config->name.gmch_n, \
13211                           current_config->name.link_m, \
13212                           current_config->name.link_n, \
13213                           pipe_config->name.tu, \
13214                           pipe_config->name.gmch_m, \
13215                           pipe_config->name.gmch_n, \
13216                           pipe_config->name.link_m, \
13217                           pipe_config->name.link_n); \
13218                 ret = false; \
13219         }
13220
13221 /* This is required for BDW+ where there is only one set of registers for
13222  * switching between high and low RR.
13223  * This macro can be used whenever a comparison has to be made between one
13224  * hw state and multiple sw state variables.
13225  */
13226 #define PIPE_CONF_CHECK_M_N_ALT(name, alt_name) \
13227         if (!intel_compare_link_m_n(&current_config->name, \
13228                                     &pipe_config->name, adjust) && \
13229             !intel_compare_link_m_n(&current_config->alt_name, \
13230                                     &pipe_config->name, adjust)) { \
13231                 INTEL_ERR_OR_DBG_KMS("mismatch in " #name " " \
13232                           "(expected tu %i gmch %i/%i link %i/%i, " \
13233                           "or tu %i gmch %i/%i link %i/%i, " \
13234                           "found tu %i, gmch %i/%i link %i/%i)\n", \
13235                           current_config->name.tu, \
13236                           current_config->name.gmch_m, \
13237                           current_config->name.gmch_n, \
13238                           current_config->name.link_m, \
13239                           current_config->name.link_n, \
13240                           current_config->alt_name.tu, \
13241                           current_config->alt_name.gmch_m, \
13242                           current_config->alt_name.gmch_n, \
13243                           current_config->alt_name.link_m, \
13244                           current_config->alt_name.link_n, \
13245                           pipe_config->name.tu, \
13246                           pipe_config->name.gmch_m, \
13247                           pipe_config->name.gmch_n, \
13248                           pipe_config->name.link_m, \
13249                           pipe_config->name.link_n); \
13250                 ret = false; \
13251         }
13252
13253 #define PIPE_CONF_CHECK_FLAGS(name, mask)       \
13254         if ((current_config->name ^ pipe_config->name) & (mask)) { \
13255                 INTEL_ERR_OR_DBG_KMS("mismatch in " #name "(" #mask ") " \
13256                           "(expected %i, found %i)\n", \
13257                           current_config->name & (mask), \
13258                           pipe_config->name & (mask)); \
13259                 ret = false; \
13260         }
13261
13262 #define PIPE_CONF_CHECK_CLOCK_FUZZY(name) \
13263         if (!intel_fuzzy_clock_check(current_config->name, pipe_config->name)) { \
13264                 INTEL_ERR_OR_DBG_KMS("mismatch in " #name " " \
13265                           "(expected %i, found %i)\n", \
13266                           current_config->name, \
13267                           pipe_config->name); \
13268                 ret = false; \
13269         }
13270
13271 #define PIPE_CONF_QUIRK(quirk)  \
13272         ((current_config->quirks | pipe_config->quirks) & (quirk))
13273
13274         PIPE_CONF_CHECK_I(cpu_transcoder);
13275
13276         PIPE_CONF_CHECK_I(has_pch_encoder);
13277         PIPE_CONF_CHECK_I(fdi_lanes);
13278         PIPE_CONF_CHECK_M_N(fdi_m_n);
13279
13280         PIPE_CONF_CHECK_I(lane_count);
13281         PIPE_CONF_CHECK_X(lane_lat_optim_mask);
13282
13283         if (INTEL_GEN(dev_priv) < 8) {
13284                 PIPE_CONF_CHECK_M_N(dp_m_n);
13285
13286                 if (current_config->has_drrs)
13287                         PIPE_CONF_CHECK_M_N(dp_m2_n2);
13288         } else
13289                 PIPE_CONF_CHECK_M_N_ALT(dp_m_n, dp_m2_n2);
13290
13291         PIPE_CONF_CHECK_X(output_types);
13292
13293         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hdisplay);
13294         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_htotal);
13295         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hblank_start);
13296         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hblank_end);
13297         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hsync_start);
13298         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hsync_end);
13299
13300         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vdisplay);
13301         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vtotal);
13302         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vblank_start);
13303         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vblank_end);
13304         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vsync_start);
13305         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vsync_end);
13306
13307         PIPE_CONF_CHECK_I(pixel_multiplier);
13308         PIPE_CONF_CHECK_I(has_hdmi_sink);
13309         if ((INTEL_GEN(dev_priv) < 8 && !IS_HASWELL(dev_priv)) ||
13310             IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
13311                 PIPE_CONF_CHECK_I(limited_color_range);
13312         PIPE_CONF_CHECK_I(has_infoframe);
13313
13314         PIPE_CONF_CHECK_I(has_audio);
13315
13316         PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
13317                               DRM_MODE_FLAG_INTERLACE);
13318
13319         if (!PIPE_CONF_QUIRK(PIPE_CONFIG_QUIRK_MODE_SYNC_FLAGS)) {
13320                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
13321                                       DRM_MODE_FLAG_PHSYNC);
13322                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
13323                                       DRM_MODE_FLAG_NHSYNC);
13324                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
13325                                       DRM_MODE_FLAG_PVSYNC);
13326                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
13327                                       DRM_MODE_FLAG_NVSYNC);
13328         }
13329
13330         PIPE_CONF_CHECK_X(gmch_pfit.control);
13331         /* pfit ratios are autocomputed by the hw on gen4+ */
13332         if (INTEL_GEN(dev_priv) < 4)
13333                 PIPE_CONF_CHECK_X(gmch_pfit.pgm_ratios);
13334         PIPE_CONF_CHECK_X(gmch_pfit.lvds_border_bits);
13335
13336         if (!adjust) {
13337                 PIPE_CONF_CHECK_I(pipe_src_w);
13338                 PIPE_CONF_CHECK_I(pipe_src_h);
13339
13340                 PIPE_CONF_CHECK_I(pch_pfit.enabled);
13341                 if (current_config->pch_pfit.enabled) {
13342                         PIPE_CONF_CHECK_X(pch_pfit.pos);
13343                         PIPE_CONF_CHECK_X(pch_pfit.size);
13344                 }
13345
13346                 PIPE_CONF_CHECK_I(scaler_state.scaler_id);
13347         }
13348
13349         /* BDW+ don't expose a synchronous way to read the state */
13350         if (IS_HASWELL(dev_priv))
13351                 PIPE_CONF_CHECK_I(ips_enabled);
13352
13353         PIPE_CONF_CHECK_I(double_wide);
13354
13355         PIPE_CONF_CHECK_P(shared_dpll);
13356         PIPE_CONF_CHECK_X(dpll_hw_state.dpll);
13357         PIPE_CONF_CHECK_X(dpll_hw_state.dpll_md);
13358         PIPE_CONF_CHECK_X(dpll_hw_state.fp0);
13359         PIPE_CONF_CHECK_X(dpll_hw_state.fp1);
13360         PIPE_CONF_CHECK_X(dpll_hw_state.wrpll);
13361         PIPE_CONF_CHECK_X(dpll_hw_state.spll);
13362         PIPE_CONF_CHECK_X(dpll_hw_state.ctrl1);
13363         PIPE_CONF_CHECK_X(dpll_hw_state.cfgcr1);
13364         PIPE_CONF_CHECK_X(dpll_hw_state.cfgcr2);
13365
13366         PIPE_CONF_CHECK_X(dsi_pll.ctrl);
13367         PIPE_CONF_CHECK_X(dsi_pll.div);
13368
13369         if (IS_G4X(dev_priv) || INTEL_GEN(dev_priv) >= 5)
13370                 PIPE_CONF_CHECK_I(pipe_bpp);
13371
13372         PIPE_CONF_CHECK_CLOCK_FUZZY(base.adjusted_mode.crtc_clock);
13373         PIPE_CONF_CHECK_CLOCK_FUZZY(port_clock);
13374
13375 #undef PIPE_CONF_CHECK_X
13376 #undef PIPE_CONF_CHECK_I
13377 #undef PIPE_CONF_CHECK_P
13378 #undef PIPE_CONF_CHECK_FLAGS
13379 #undef PIPE_CONF_CHECK_CLOCK_FUZZY
13380 #undef PIPE_CONF_QUIRK
13381 #undef INTEL_ERR_OR_DBG_KMS
13382
13383         return ret;
13384 }
13385
13386 static void intel_pipe_config_sanity_check(struct drm_i915_private *dev_priv,
13387                                            const struct intel_crtc_state *pipe_config)
13388 {
13389         if (pipe_config->has_pch_encoder) {
13390                 int fdi_dotclock = intel_dotclock_calculate(intel_fdi_link_freq(dev_priv, pipe_config),
13391                                                             &pipe_config->fdi_m_n);
13392                 int dotclock = pipe_config->base.adjusted_mode.crtc_clock;
13393
13394                 /*
13395                  * FDI already provided one idea for the dotclock.
13396                  * Yell if the encoder disagrees.
13397                  */
13398                 WARN(!intel_fuzzy_clock_check(fdi_dotclock, dotclock),
13399                      "FDI dotclock and encoder dotclock mismatch, fdi: %i, encoder: %i\n",
13400                      fdi_dotclock, dotclock);
13401         }
13402 }
13403
13404 static void verify_wm_state(struct drm_crtc *crtc,
13405                             struct drm_crtc_state *new_state)
13406 {
13407         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
13408         struct skl_ddb_allocation hw_ddb, *sw_ddb;
13409         struct skl_pipe_wm hw_wm, *sw_wm;
13410         struct skl_plane_wm *hw_plane_wm, *sw_plane_wm;
13411         struct skl_ddb_entry *hw_ddb_entry, *sw_ddb_entry;
13412         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
13413         const enum pipe pipe = intel_crtc->pipe;
13414         int plane, level, max_level = ilk_wm_max_level(dev_priv);
13415
13416         if (INTEL_GEN(dev_priv) < 9 || !new_state->active)
13417                 return;
13418
13419         skl_pipe_wm_get_hw_state(crtc, &hw_wm);
13420         sw_wm = &to_intel_crtc_state(new_state)->wm.skl.optimal;
13421
13422         skl_ddb_get_hw_state(dev_priv, &hw_ddb);
13423         sw_ddb = &dev_priv->wm.skl_hw.ddb;
13424
13425         /* planes */
13426         for_each_universal_plane(dev_priv, pipe, plane) {
13427                 hw_plane_wm = &hw_wm.planes[plane];
13428                 sw_plane_wm = &sw_wm->planes[plane];
13429
13430                 /* Watermarks */
13431                 for (level = 0; level <= max_level; level++) {
13432                         if (skl_wm_level_equals(&hw_plane_wm->wm[level],
13433                                                 &sw_plane_wm->wm[level]))
13434                                 continue;
13435
13436                         DRM_ERROR("mismatch in WM pipe %c plane %d level %d (expected e=%d b=%u l=%u, got e=%d b=%u l=%u)\n",
13437                                   pipe_name(pipe), plane + 1, level,
13438                                   sw_plane_wm->wm[level].plane_en,
13439                                   sw_plane_wm->wm[level].plane_res_b,
13440                                   sw_plane_wm->wm[level].plane_res_l,
13441                                   hw_plane_wm->wm[level].plane_en,
13442                                   hw_plane_wm->wm[level].plane_res_b,
13443                                   hw_plane_wm->wm[level].plane_res_l);
13444                 }
13445
13446                 if (!skl_wm_level_equals(&hw_plane_wm->trans_wm,
13447                                          &sw_plane_wm->trans_wm)) {
13448                         DRM_ERROR("mismatch in trans WM pipe %c plane %d (expected e=%d b=%u l=%u, got e=%d b=%u l=%u)\n",
13449                                   pipe_name(pipe), plane + 1,
13450                                   sw_plane_wm->trans_wm.plane_en,
13451                                   sw_plane_wm->trans_wm.plane_res_b,
13452                                   sw_plane_wm->trans_wm.plane_res_l,
13453                                   hw_plane_wm->trans_wm.plane_en,
13454                                   hw_plane_wm->trans_wm.plane_res_b,
13455                                   hw_plane_wm->trans_wm.plane_res_l);
13456                 }
13457
13458                 /* DDB */
13459                 hw_ddb_entry = &hw_ddb.plane[pipe][plane];
13460                 sw_ddb_entry = &sw_ddb->plane[pipe][plane];
13461
13462                 if (!skl_ddb_entry_equal(hw_ddb_entry, sw_ddb_entry)) {
13463                         DRM_ERROR("mismatch in DDB state pipe %c plane %d (expected (%u,%u), found (%u,%u))\n",
13464                                   pipe_name(pipe), plane + 1,
13465                                   sw_ddb_entry->start, sw_ddb_entry->end,
13466                                   hw_ddb_entry->start, hw_ddb_entry->end);
13467                 }
13468         }
13469
13470         /*
13471          * cursor
13472          * If the cursor plane isn't active, we may not have updated it's ddb
13473          * allocation. In that case since the ddb allocation will be updated
13474          * once the plane becomes visible, we can skip this check
13475          */
13476         if (intel_crtc->cursor_addr) {
13477                 hw_plane_wm = &hw_wm.planes[PLANE_CURSOR];
13478                 sw_plane_wm = &sw_wm->planes[PLANE_CURSOR];
13479
13480                 /* Watermarks */
13481                 for (level = 0; level <= max_level; level++) {
13482                         if (skl_wm_level_equals(&hw_plane_wm->wm[level],
13483                                                 &sw_plane_wm->wm[level]))
13484                                 continue;
13485
13486                         DRM_ERROR("mismatch in WM pipe %c cursor level %d (expected e=%d b=%u l=%u, got e=%d b=%u l=%u)\n",
13487                                   pipe_name(pipe), level,
13488                                   sw_plane_wm->wm[level].plane_en,
13489                                   sw_plane_wm->wm[level].plane_res_b,
13490                                   sw_plane_wm->wm[level].plane_res_l,
13491                                   hw_plane_wm->wm[level].plane_en,
13492                                   hw_plane_wm->wm[level].plane_res_b,
13493                                   hw_plane_wm->wm[level].plane_res_l);
13494                 }
13495
13496                 if (!skl_wm_level_equals(&hw_plane_wm->trans_wm,
13497                                          &sw_plane_wm->trans_wm)) {
13498                         DRM_ERROR("mismatch in trans WM pipe %c cursor (expected e=%d b=%u l=%u, got e=%d b=%u l=%u)\n",
13499                                   pipe_name(pipe),
13500                                   sw_plane_wm->trans_wm.plane_en,
13501                                   sw_plane_wm->trans_wm.plane_res_b,
13502                                   sw_plane_wm->trans_wm.plane_res_l,
13503                                   hw_plane_wm->trans_wm.plane_en,
13504                                   hw_plane_wm->trans_wm.plane_res_b,
13505                                   hw_plane_wm->trans_wm.plane_res_l);
13506                 }
13507
13508                 /* DDB */
13509                 hw_ddb_entry = &hw_ddb.plane[pipe][PLANE_CURSOR];
13510                 sw_ddb_entry = &sw_ddb->plane[pipe][PLANE_CURSOR];
13511
13512                 if (!skl_ddb_entry_equal(hw_ddb_entry, sw_ddb_entry)) {
13513                         DRM_ERROR("mismatch in DDB state pipe %c cursor (expected (%u,%u), found (%u,%u))\n",
13514                                   pipe_name(pipe),
13515                                   sw_ddb_entry->start, sw_ddb_entry->end,
13516                                   hw_ddb_entry->start, hw_ddb_entry->end);
13517                 }
13518         }
13519 }
13520
13521 static void
13522 verify_connector_state(struct drm_device *dev,
13523                        struct drm_atomic_state *state,
13524                        struct drm_crtc *crtc)
13525 {
13526         struct drm_connector *connector;
13527         struct drm_connector_state *old_conn_state;
13528         int i;
13529
13530         for_each_connector_in_state(state, connector, old_conn_state, i) {
13531                 struct drm_encoder *encoder = connector->encoder;
13532                 struct drm_connector_state *state = connector->state;
13533
13534                 if (state->crtc != crtc)
13535                         continue;
13536
13537                 intel_connector_verify_state(to_intel_connector(connector));
13538
13539                 I915_STATE_WARN(state->best_encoder != encoder,
13540                      "connector's atomic encoder doesn't match legacy encoder\n");
13541         }
13542 }
13543
13544 static void
13545 verify_encoder_state(struct drm_device *dev)
13546 {
13547         struct intel_encoder *encoder;
13548         struct intel_connector *connector;
13549
13550         for_each_intel_encoder(dev, encoder) {
13551                 bool enabled = false;
13552                 enum pipe pipe;
13553
13554                 DRM_DEBUG_KMS("[ENCODER:%d:%s]\n",
13555                               encoder->base.base.id,
13556                               encoder->base.name);
13557
13558                 for_each_intel_connector(dev, connector) {
13559                         if (connector->base.state->best_encoder != &encoder->base)
13560                                 continue;
13561                         enabled = true;
13562
13563                         I915_STATE_WARN(connector->base.state->crtc !=
13564                                         encoder->base.crtc,
13565                              "connector's crtc doesn't match encoder crtc\n");
13566                 }
13567
13568                 I915_STATE_WARN(!!encoder->base.crtc != enabled,
13569                      "encoder's enabled state mismatch "
13570                      "(expected %i, found %i)\n",
13571                      !!encoder->base.crtc, enabled);
13572
13573                 if (!encoder->base.crtc) {
13574                         bool active;
13575
13576                         active = encoder->get_hw_state(encoder, &pipe);
13577                         I915_STATE_WARN(active,
13578                              "encoder detached but still enabled on pipe %c.\n",
13579                              pipe_name(pipe));
13580                 }
13581         }
13582 }
13583
13584 static void
13585 verify_crtc_state(struct drm_crtc *crtc,
13586                   struct drm_crtc_state *old_crtc_state,
13587                   struct drm_crtc_state *new_crtc_state)
13588 {
13589         struct drm_device *dev = crtc->dev;
13590         struct drm_i915_private *dev_priv = to_i915(dev);
13591         struct intel_encoder *encoder;
13592         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
13593         struct intel_crtc_state *pipe_config, *sw_config;
13594         struct drm_atomic_state *old_state;
13595         bool active;
13596
13597         old_state = old_crtc_state->state;
13598         __drm_atomic_helper_crtc_destroy_state(old_crtc_state);
13599         pipe_config = to_intel_crtc_state(old_crtc_state);
13600         memset(pipe_config, 0, sizeof(*pipe_config));
13601         pipe_config->base.crtc = crtc;
13602         pipe_config->base.state = old_state;
13603
13604         DRM_DEBUG_KMS("[CRTC:%d:%s]\n", crtc->base.id, crtc->name);
13605
13606         active = dev_priv->display.get_pipe_config(intel_crtc, pipe_config);
13607
13608         /* hw state is inconsistent with the pipe quirk */
13609         if ((intel_crtc->pipe == PIPE_A && dev_priv->quirks & QUIRK_PIPEA_FORCE) ||
13610             (intel_crtc->pipe == PIPE_B && dev_priv->quirks & QUIRK_PIPEB_FORCE))
13611                 active = new_crtc_state->active;
13612
13613         I915_STATE_WARN(new_crtc_state->active != active,
13614              "crtc active state doesn't match with hw state "
13615              "(expected %i, found %i)\n", new_crtc_state->active, active);
13616
13617         I915_STATE_WARN(intel_crtc->active != new_crtc_state->active,
13618              "transitional active state does not match atomic hw state "
13619              "(expected %i, found %i)\n", new_crtc_state->active, intel_crtc->active);
13620
13621         for_each_encoder_on_crtc(dev, crtc, encoder) {
13622                 enum pipe pipe;
13623
13624                 active = encoder->get_hw_state(encoder, &pipe);
13625                 I915_STATE_WARN(active != new_crtc_state->active,
13626                         "[ENCODER:%i] active %i with crtc active %i\n",
13627                         encoder->base.base.id, active, new_crtc_state->active);
13628
13629                 I915_STATE_WARN(active && intel_crtc->pipe != pipe,
13630                                 "Encoder connected to wrong pipe %c\n",
13631                                 pipe_name(pipe));
13632
13633                 if (active) {
13634                         pipe_config->output_types |= 1 << encoder->type;
13635                         encoder->get_config(encoder, pipe_config);
13636                 }
13637         }
13638
13639         if (!new_crtc_state->active)
13640                 return;
13641
13642         intel_pipe_config_sanity_check(dev_priv, pipe_config);
13643
13644         sw_config = to_intel_crtc_state(crtc->state);
13645         if (!intel_pipe_config_compare(dev_priv, sw_config,
13646                                        pipe_config, false)) {
13647                 I915_STATE_WARN(1, "pipe state doesn't match!\n");
13648                 intel_dump_pipe_config(intel_crtc, pipe_config,
13649                                        "[hw state]");
13650                 intel_dump_pipe_config(intel_crtc, sw_config,
13651                                        "[sw state]");
13652         }
13653 }
13654
13655 static void
13656 verify_single_dpll_state(struct drm_i915_private *dev_priv,
13657                          struct intel_shared_dpll *pll,
13658                          struct drm_crtc *crtc,
13659                          struct drm_crtc_state *new_state)
13660 {
13661         struct intel_dpll_hw_state dpll_hw_state;
13662         unsigned crtc_mask;
13663         bool active;
13664
13665         memset(&dpll_hw_state, 0, sizeof(dpll_hw_state));
13666
13667         DRM_DEBUG_KMS("%s\n", pll->name);
13668
13669         active = pll->funcs.get_hw_state(dev_priv, pll, &dpll_hw_state);
13670
13671         if (!(pll->flags & INTEL_DPLL_ALWAYS_ON)) {
13672                 I915_STATE_WARN(!pll->on && pll->active_mask,
13673                      "pll in active use but not on in sw tracking\n");
13674                 I915_STATE_WARN(pll->on && !pll->active_mask,
13675                      "pll is on but not used by any active crtc\n");
13676                 I915_STATE_WARN(pll->on != active,
13677                      "pll on state mismatch (expected %i, found %i)\n",
13678                      pll->on, active);
13679         }
13680
13681         if (!crtc) {
13682                 I915_STATE_WARN(pll->active_mask & ~pll->config.crtc_mask,
13683                                 "more active pll users than references: %x vs %x\n",
13684                                 pll->active_mask, pll->config.crtc_mask);
13685
13686                 return;
13687         }
13688
13689         crtc_mask = 1 << drm_crtc_index(crtc);
13690
13691         if (new_state->active)
13692                 I915_STATE_WARN(!(pll->active_mask & crtc_mask),
13693                                 "pll active mismatch (expected pipe %c in active mask 0x%02x)\n",
13694                                 pipe_name(drm_crtc_index(crtc)), pll->active_mask);
13695         else
13696                 I915_STATE_WARN(pll->active_mask & crtc_mask,
13697                                 "pll active mismatch (didn't expect pipe %c in active mask 0x%02x)\n",
13698                                 pipe_name(drm_crtc_index(crtc)), pll->active_mask);
13699
13700         I915_STATE_WARN(!(pll->config.crtc_mask & crtc_mask),
13701                         "pll enabled crtcs mismatch (expected 0x%x in 0x%02x)\n",
13702                         crtc_mask, pll->config.crtc_mask);
13703
13704         I915_STATE_WARN(pll->on && memcmp(&pll->config.hw_state,
13705                                           &dpll_hw_state,
13706                                           sizeof(dpll_hw_state)),
13707                         "pll hw state mismatch\n");
13708 }
13709
13710 static void
13711 verify_shared_dpll_state(struct drm_device *dev, struct drm_crtc *crtc,
13712                          struct drm_crtc_state *old_crtc_state,
13713                          struct drm_crtc_state *new_crtc_state)
13714 {
13715         struct drm_i915_private *dev_priv = to_i915(dev);
13716         struct intel_crtc_state *old_state = to_intel_crtc_state(old_crtc_state);
13717         struct intel_crtc_state *new_state = to_intel_crtc_state(new_crtc_state);
13718
13719         if (new_state->shared_dpll)
13720                 verify_single_dpll_state(dev_priv, new_state->shared_dpll, crtc, new_crtc_state);
13721
13722         if (old_state->shared_dpll &&
13723             old_state->shared_dpll != new_state->shared_dpll) {
13724                 unsigned crtc_mask = 1 << drm_crtc_index(crtc);
13725                 struct intel_shared_dpll *pll = old_state->shared_dpll;
13726
13727                 I915_STATE_WARN(pll->active_mask & crtc_mask,
13728                                 "pll active mismatch (didn't expect pipe %c in active mask)\n",
13729                                 pipe_name(drm_crtc_index(crtc)));
13730                 I915_STATE_WARN(pll->config.crtc_mask & crtc_mask,
13731                                 "pll enabled crtcs mismatch (found %x in enabled mask)\n",
13732                                 pipe_name(drm_crtc_index(crtc)));
13733         }
13734 }
13735
13736 static void
13737 intel_modeset_verify_crtc(struct drm_crtc *crtc,
13738                           struct drm_atomic_state *state,
13739                           struct drm_crtc_state *old_state,
13740                           struct drm_crtc_state *new_state)
13741 {
13742         if (!needs_modeset(new_state) &&
13743             !to_intel_crtc_state(new_state)->update_pipe)
13744                 return;
13745
13746         verify_wm_state(crtc, new_state);
13747         verify_connector_state(crtc->dev, state, crtc);
13748         verify_crtc_state(crtc, old_state, new_state);
13749         verify_shared_dpll_state(crtc->dev, crtc, old_state, new_state);
13750 }
13751
13752 static void
13753 verify_disabled_dpll_state(struct drm_device *dev)
13754 {
13755         struct drm_i915_private *dev_priv = to_i915(dev);
13756         int i;
13757
13758         for (i = 0; i < dev_priv->num_shared_dpll; i++)
13759                 verify_single_dpll_state(dev_priv, &dev_priv->shared_dplls[i], NULL, NULL);
13760 }
13761
13762 static void
13763 intel_modeset_verify_disabled(struct drm_device *dev,
13764                               struct drm_atomic_state *state)
13765 {
13766         verify_encoder_state(dev);
13767         verify_connector_state(dev, state, NULL);
13768         verify_disabled_dpll_state(dev);
13769 }
13770
13771 static void update_scanline_offset(struct intel_crtc *crtc)
13772 {
13773         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
13774
13775         /*
13776          * The scanline counter increments at the leading edge of hsync.
13777          *
13778          * On most platforms it starts counting from vtotal-1 on the
13779          * first active line. That means the scanline counter value is
13780          * always one less than what we would expect. Ie. just after
13781          * start of vblank, which also occurs at start of hsync (on the
13782          * last active line), the scanline counter will read vblank_start-1.
13783          *
13784          * On gen2 the scanline counter starts counting from 1 instead
13785          * of vtotal-1, so we have to subtract one (or rather add vtotal-1
13786          * to keep the value positive), instead of adding one.
13787          *
13788          * On HSW+ the behaviour of the scanline counter depends on the output
13789          * type. For DP ports it behaves like most other platforms, but on HDMI
13790          * there's an extra 1 line difference. So we need to add two instead of
13791          * one to the value.
13792          */
13793         if (IS_GEN2(dev_priv)) {
13794                 const struct drm_display_mode *adjusted_mode = &crtc->config->base.adjusted_mode;
13795                 int vtotal;
13796
13797                 vtotal = adjusted_mode->crtc_vtotal;
13798                 if (adjusted_mode->flags & DRM_MODE_FLAG_INTERLACE)
13799                         vtotal /= 2;
13800
13801                 crtc->scanline_offset = vtotal - 1;
13802         } else if (HAS_DDI(dev_priv) &&
13803                    intel_crtc_has_type(crtc->config, INTEL_OUTPUT_HDMI)) {
13804                 crtc->scanline_offset = 2;
13805         } else
13806                 crtc->scanline_offset = 1;
13807 }
13808
13809 static void intel_modeset_clear_plls(struct drm_atomic_state *state)
13810 {
13811         struct drm_device *dev = state->dev;
13812         struct drm_i915_private *dev_priv = to_i915(dev);
13813         struct intel_shared_dpll_config *shared_dpll = NULL;
13814         struct drm_crtc *crtc;
13815         struct drm_crtc_state *crtc_state;
13816         int i;
13817
13818         if (!dev_priv->display.crtc_compute_clock)
13819                 return;
13820
13821         for_each_crtc_in_state(state, crtc, crtc_state, i) {
13822                 struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
13823                 struct intel_shared_dpll *old_dpll =
13824                         to_intel_crtc_state(crtc->state)->shared_dpll;
13825
13826                 if (!needs_modeset(crtc_state))
13827                         continue;
13828
13829                 to_intel_crtc_state(crtc_state)->shared_dpll = NULL;
13830
13831                 if (!old_dpll)
13832                         continue;
13833
13834                 if (!shared_dpll)
13835                         shared_dpll = intel_atomic_get_shared_dpll_state(state);
13836
13837                 intel_shared_dpll_config_put(shared_dpll, old_dpll, intel_crtc);
13838         }
13839 }
13840
13841 /*
13842  * This implements the workaround described in the "notes" section of the mode
13843  * set sequence documentation. When going from no pipes or single pipe to
13844  * multiple pipes, and planes are enabled after the pipe, we need to wait at
13845  * least 2 vblanks on the first pipe before enabling planes on the second pipe.
13846  */
13847 static int haswell_mode_set_planes_workaround(struct drm_atomic_state *state)
13848 {
13849         struct drm_crtc_state *crtc_state;
13850         struct intel_crtc *intel_crtc;
13851         struct drm_crtc *crtc;
13852         struct intel_crtc_state *first_crtc_state = NULL;
13853         struct intel_crtc_state *other_crtc_state = NULL;
13854         enum pipe first_pipe = INVALID_PIPE, enabled_pipe = INVALID_PIPE;
13855         int i;
13856
13857         /* look at all crtc's that are going to be enabled in during modeset */
13858         for_each_crtc_in_state(state, crtc, crtc_state, i) {
13859                 intel_crtc = to_intel_crtc(crtc);
13860
13861                 if (!crtc_state->active || !needs_modeset(crtc_state))
13862                         continue;
13863
13864                 if (first_crtc_state) {
13865                         other_crtc_state = to_intel_crtc_state(crtc_state);
13866                         break;
13867                 } else {
13868                         first_crtc_state = to_intel_crtc_state(crtc_state);
13869                         first_pipe = intel_crtc->pipe;
13870                 }
13871         }
13872
13873         /* No workaround needed? */
13874         if (!first_crtc_state)
13875                 return 0;
13876
13877         /* w/a possibly needed, check how many crtc's are already enabled. */
13878         for_each_intel_crtc(state->dev, intel_crtc) {
13879                 struct intel_crtc_state *pipe_config;
13880
13881                 pipe_config = intel_atomic_get_crtc_state(state, intel_crtc);
13882                 if (IS_ERR(pipe_config))
13883                         return PTR_ERR(pipe_config);
13884
13885                 pipe_config->hsw_workaround_pipe = INVALID_PIPE;
13886
13887                 if (!pipe_config->base.active ||
13888                     needs_modeset(&pipe_config->base))
13889                         continue;
13890
13891                 /* 2 or more enabled crtcs means no need for w/a */
13892                 if (enabled_pipe != INVALID_PIPE)
13893                         return 0;
13894
13895                 enabled_pipe = intel_crtc->pipe;
13896         }
13897
13898         if (enabled_pipe != INVALID_PIPE)
13899                 first_crtc_state->hsw_workaround_pipe = enabled_pipe;
13900         else if (other_crtc_state)
13901                 other_crtc_state->hsw_workaround_pipe = first_pipe;
13902
13903         return 0;
13904 }
13905
13906 static int intel_modeset_all_pipes(struct drm_atomic_state *state)
13907 {
13908         struct drm_crtc *crtc;
13909         struct drm_crtc_state *crtc_state;
13910         int ret = 0;
13911
13912         /* add all active pipes to the state */
13913         for_each_crtc(state->dev, crtc) {
13914                 crtc_state = drm_atomic_get_crtc_state(state, crtc);
13915                 if (IS_ERR(crtc_state))
13916                         return PTR_ERR(crtc_state);
13917
13918                 if (!crtc_state->active || needs_modeset(crtc_state))
13919                         continue;
13920
13921                 crtc_state->mode_changed = true;
13922
13923                 ret = drm_atomic_add_affected_connectors(state, crtc);
13924                 if (ret)
13925                         break;
13926
13927                 ret = drm_atomic_add_affected_planes(state, crtc);
13928                 if (ret)
13929                         break;
13930         }
13931
13932         return ret;
13933 }
13934
13935 static int intel_modeset_checks(struct drm_atomic_state *state)
13936 {
13937         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
13938         struct drm_i915_private *dev_priv = to_i915(state->dev);
13939         struct drm_crtc *crtc;
13940         struct drm_crtc_state *crtc_state;
13941         int ret = 0, i;
13942
13943         if (!check_digital_port_conflicts(state)) {
13944                 DRM_DEBUG_KMS("rejecting conflicting digital port configuration\n");
13945                 return -EINVAL;
13946         }
13947
13948         intel_state->modeset = true;
13949         intel_state->active_crtcs = dev_priv->active_crtcs;
13950
13951         for_each_crtc_in_state(state, crtc, crtc_state, i) {
13952                 if (crtc_state->active)
13953                         intel_state->active_crtcs |= 1 << i;
13954                 else
13955                         intel_state->active_crtcs &= ~(1 << i);
13956
13957                 if (crtc_state->active != crtc->state->active)
13958                         intel_state->active_pipe_changes |= drm_crtc_mask(crtc);
13959         }
13960
13961         /*
13962          * See if the config requires any additional preparation, e.g.
13963          * to adjust global state with pipes off.  We need to do this
13964          * here so we can get the modeset_pipe updated config for the new
13965          * mode set on this crtc.  For other crtcs we need to use the
13966          * adjusted_mode bits in the crtc directly.
13967          */
13968         if (dev_priv->display.modeset_calc_cdclk) {
13969                 if (!intel_state->cdclk_pll_vco)
13970                         intel_state->cdclk_pll_vco = dev_priv->cdclk_pll.vco;
13971                 if (!intel_state->cdclk_pll_vco)
13972                         intel_state->cdclk_pll_vco = dev_priv->skl_preferred_vco_freq;
13973
13974                 ret = dev_priv->display.modeset_calc_cdclk(state);
13975                 if (ret < 0)
13976                         return ret;
13977
13978                 if (intel_state->dev_cdclk != dev_priv->cdclk_freq ||
13979                     intel_state->cdclk_pll_vco != dev_priv->cdclk_pll.vco)
13980                         ret = intel_modeset_all_pipes(state);
13981
13982                 if (ret < 0)
13983                         return ret;
13984
13985                 DRM_DEBUG_KMS("New cdclk calculated to be atomic %u, actual %u\n",
13986                               intel_state->cdclk, intel_state->dev_cdclk);
13987         } else {
13988                 to_intel_atomic_state(state)->cdclk = dev_priv->atomic_cdclk_freq;
13989         }
13990
13991         intel_modeset_clear_plls(state);
13992
13993         if (IS_HASWELL(dev_priv))
13994                 return haswell_mode_set_planes_workaround(state);
13995
13996         return 0;
13997 }
13998
13999 /*
14000  * Handle calculation of various watermark data at the end of the atomic check
14001  * phase.  The code here should be run after the per-crtc and per-plane 'check'
14002  * handlers to ensure that all derived state has been updated.
14003  */
14004 static int calc_watermark_data(struct drm_atomic_state *state)
14005 {
14006         struct drm_device *dev = state->dev;
14007         struct drm_i915_private *dev_priv = to_i915(dev);
14008
14009         /* Is there platform-specific watermark information to calculate? */
14010         if (dev_priv->display.compute_global_watermarks)
14011                 return dev_priv->display.compute_global_watermarks(state);
14012
14013         return 0;
14014 }
14015
14016 /**
14017  * intel_atomic_check - validate state object
14018  * @dev: drm device
14019  * @state: state to validate
14020  */
14021 static int intel_atomic_check(struct drm_device *dev,
14022                               struct drm_atomic_state *state)
14023 {
14024         struct drm_i915_private *dev_priv = to_i915(dev);
14025         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
14026         struct drm_crtc *crtc;
14027         struct drm_crtc_state *crtc_state;
14028         int ret, i;
14029         bool any_ms = false;
14030
14031         ret = drm_atomic_helper_check_modeset(dev, state);
14032         if (ret)
14033                 return ret;
14034
14035         for_each_crtc_in_state(state, crtc, crtc_state, i) {
14036                 struct intel_crtc_state *pipe_config =
14037                         to_intel_crtc_state(crtc_state);
14038
14039                 /* Catch I915_MODE_FLAG_INHERITED */
14040                 if (crtc_state->mode.private_flags != crtc->state->mode.private_flags)
14041                         crtc_state->mode_changed = true;
14042
14043                 if (!needs_modeset(crtc_state))
14044                         continue;
14045
14046                 if (!crtc_state->enable) {
14047                         any_ms = true;
14048                         continue;
14049                 }
14050
14051                 /* FIXME: For only active_changed we shouldn't need to do any
14052                  * state recomputation at all. */
14053
14054                 ret = drm_atomic_add_affected_connectors(state, crtc);
14055                 if (ret)
14056                         return ret;
14057
14058                 ret = intel_modeset_pipe_config(crtc, pipe_config);
14059                 if (ret) {
14060                         intel_dump_pipe_config(to_intel_crtc(crtc),
14061                                                pipe_config, "[failed]");
14062                         return ret;
14063                 }
14064
14065                 if (i915.fastboot &&
14066                     intel_pipe_config_compare(dev_priv,
14067                                         to_intel_crtc_state(crtc->state),
14068                                         pipe_config, true)) {
14069                         crtc_state->mode_changed = false;
14070                         to_intel_crtc_state(crtc_state)->update_pipe = true;
14071                 }
14072
14073                 if (needs_modeset(crtc_state))
14074                         any_ms = true;
14075
14076                 ret = drm_atomic_add_affected_planes(state, crtc);
14077                 if (ret)
14078                         return ret;
14079
14080                 intel_dump_pipe_config(to_intel_crtc(crtc), pipe_config,
14081                                        needs_modeset(crtc_state) ?
14082                                        "[modeset]" : "[fastset]");
14083         }
14084
14085         if (any_ms) {
14086                 ret = intel_modeset_checks(state);
14087
14088                 if (ret)
14089                         return ret;
14090         } else {
14091                 intel_state->cdclk = dev_priv->atomic_cdclk_freq;
14092         }
14093
14094         ret = drm_atomic_helper_check_planes(dev, state);
14095         if (ret)
14096                 return ret;
14097
14098         intel_fbc_choose_crtc(dev_priv, state);
14099         return calc_watermark_data(state);
14100 }
14101
14102 static int intel_atomic_prepare_commit(struct drm_device *dev,
14103                                        struct drm_atomic_state *state)
14104 {
14105         struct drm_i915_private *dev_priv = to_i915(dev);
14106         struct drm_crtc_state *crtc_state;
14107         struct drm_crtc *crtc;
14108         int i, ret;
14109
14110         for_each_crtc_in_state(state, crtc, crtc_state, i) {
14111                 if (state->legacy_cursor_update)
14112                         continue;
14113
14114                 ret = intel_crtc_wait_for_pending_flips(crtc);
14115                 if (ret)
14116                         return ret;
14117
14118                 if (atomic_read(&to_intel_crtc(crtc)->unpin_work_count) >= 2)
14119                         flush_workqueue(dev_priv->wq);
14120         }
14121
14122         ret = mutex_lock_interruptible(&dev->struct_mutex);
14123         if (ret)
14124                 return ret;
14125
14126         ret = drm_atomic_helper_prepare_planes(dev, state);
14127         mutex_unlock(&dev->struct_mutex);
14128
14129         return ret;
14130 }
14131
14132 u32 intel_crtc_get_vblank_counter(struct intel_crtc *crtc)
14133 {
14134         struct drm_device *dev = crtc->base.dev;
14135
14136         if (!dev->max_vblank_count)
14137                 return drm_accurate_vblank_count(&crtc->base);
14138
14139         return dev->driver->get_vblank_counter(dev, crtc->pipe);
14140 }
14141
14142 static void intel_atomic_wait_for_vblanks(struct drm_device *dev,
14143                                           struct drm_i915_private *dev_priv,
14144                                           unsigned crtc_mask)
14145 {
14146         unsigned last_vblank_count[I915_MAX_PIPES];
14147         enum pipe pipe;
14148         int ret;
14149
14150         if (!crtc_mask)
14151                 return;
14152
14153         for_each_pipe(dev_priv, pipe) {
14154                 struct intel_crtc *crtc = intel_get_crtc_for_pipe(dev_priv,
14155                                                                   pipe);
14156
14157                 if (!((1 << pipe) & crtc_mask))
14158                         continue;
14159
14160                 ret = drm_crtc_vblank_get(&crtc->base);
14161                 if (WARN_ON(ret != 0)) {
14162                         crtc_mask &= ~(1 << pipe);
14163                         continue;
14164                 }
14165
14166                 last_vblank_count[pipe] = drm_crtc_vblank_count(&crtc->base);
14167         }
14168
14169         for_each_pipe(dev_priv, pipe) {
14170                 struct intel_crtc *crtc = intel_get_crtc_for_pipe(dev_priv,
14171                                                                   pipe);
14172                 long lret;
14173
14174                 if (!((1 << pipe) & crtc_mask))
14175                         continue;
14176
14177                 lret = wait_event_timeout(dev->vblank[pipe].queue,
14178                                 last_vblank_count[pipe] !=
14179                                         drm_crtc_vblank_count(&crtc->base),
14180                                 msecs_to_jiffies(50));
14181
14182                 WARN(!lret, "pipe %c vblank wait timed out\n", pipe_name(pipe));
14183
14184                 drm_crtc_vblank_put(&crtc->base);
14185         }
14186 }
14187
14188 static bool needs_vblank_wait(struct intel_crtc_state *crtc_state)
14189 {
14190         /* fb updated, need to unpin old fb */
14191         if (crtc_state->fb_changed)
14192                 return true;
14193
14194         /* wm changes, need vblank before final wm's */
14195         if (crtc_state->update_wm_post)
14196                 return true;
14197
14198         /*
14199          * cxsr is re-enabled after vblank.
14200          * This is already handled by crtc_state->update_wm_post,
14201          * but added for clarity.
14202          */
14203         if (crtc_state->disable_cxsr)
14204                 return true;
14205
14206         return false;
14207 }
14208
14209 static void intel_update_crtc(struct drm_crtc *crtc,
14210                               struct drm_atomic_state *state,
14211                               struct drm_crtc_state *old_crtc_state,
14212                               unsigned int *crtc_vblank_mask)
14213 {
14214         struct drm_device *dev = crtc->dev;
14215         struct drm_i915_private *dev_priv = to_i915(dev);
14216         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
14217         struct intel_crtc_state *pipe_config = to_intel_crtc_state(crtc->state);
14218         bool modeset = needs_modeset(crtc->state);
14219
14220         if (modeset) {
14221                 update_scanline_offset(intel_crtc);
14222                 dev_priv->display.crtc_enable(pipe_config, state);
14223         } else {
14224                 intel_pre_plane_update(to_intel_crtc_state(old_crtc_state));
14225         }
14226
14227         if (drm_atomic_get_existing_plane_state(state, crtc->primary)) {
14228                 intel_fbc_enable(
14229                     intel_crtc, pipe_config,
14230                     to_intel_plane_state(crtc->primary->state));
14231         }
14232
14233         drm_atomic_helper_commit_planes_on_crtc(old_crtc_state);
14234
14235         if (needs_vblank_wait(pipe_config))
14236                 *crtc_vblank_mask |= drm_crtc_mask(crtc);
14237 }
14238
14239 static void intel_update_crtcs(struct drm_atomic_state *state,
14240                                unsigned int *crtc_vblank_mask)
14241 {
14242         struct drm_crtc *crtc;
14243         struct drm_crtc_state *old_crtc_state;
14244         int i;
14245
14246         for_each_crtc_in_state(state, crtc, old_crtc_state, i) {
14247                 if (!crtc->state->active)
14248                         continue;
14249
14250                 intel_update_crtc(crtc, state, old_crtc_state,
14251                                   crtc_vblank_mask);
14252         }
14253 }
14254
14255 static void skl_update_crtcs(struct drm_atomic_state *state,
14256                              unsigned int *crtc_vblank_mask)
14257 {
14258         struct drm_i915_private *dev_priv = to_i915(state->dev);
14259         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
14260         struct drm_crtc *crtc;
14261         struct intel_crtc *intel_crtc;
14262         struct drm_crtc_state *old_crtc_state;
14263         struct intel_crtc_state *cstate;
14264         unsigned int updated = 0;
14265         bool progress;
14266         enum pipe pipe;
14267         int i;
14268
14269         const struct skl_ddb_entry *entries[I915_MAX_PIPES] = {};
14270
14271         for_each_crtc_in_state(state, crtc, old_crtc_state, i)
14272                 /* ignore allocations for crtc's that have been turned off. */
14273                 if (crtc->state->active)
14274                         entries[i] = &to_intel_crtc_state(old_crtc_state)->wm.skl.ddb;
14275
14276         /*
14277          * Whenever the number of active pipes changes, we need to make sure we
14278          * update the pipes in the right order so that their ddb allocations
14279          * never overlap with eachother inbetween CRTC updates. Otherwise we'll
14280          * cause pipe underruns and other bad stuff.
14281          */
14282         do {
14283                 progress = false;
14284
14285                 for_each_crtc_in_state(state, crtc, old_crtc_state, i) {
14286                         bool vbl_wait = false;
14287                         unsigned int cmask = drm_crtc_mask(crtc);
14288
14289                         intel_crtc = to_intel_crtc(crtc);
14290                         cstate = to_intel_crtc_state(crtc->state);
14291                         pipe = intel_crtc->pipe;
14292
14293                         if (updated & cmask || !cstate->base.active)
14294                                 continue;
14295
14296                         if (skl_ddb_allocation_overlaps(entries, &cstate->wm.skl.ddb, i))
14297                                 continue;
14298
14299                         updated |= cmask;
14300                         entries[i] = &cstate->wm.skl.ddb;
14301
14302                         /*
14303                          * If this is an already active pipe, it's DDB changed,
14304                          * and this isn't the last pipe that needs updating
14305                          * then we need to wait for a vblank to pass for the
14306                          * new ddb allocation to take effect.
14307                          */
14308                         if (!skl_ddb_entry_equal(&cstate->wm.skl.ddb,
14309                                                  &to_intel_crtc_state(old_crtc_state)->wm.skl.ddb) &&
14310                             !crtc->state->active_changed &&
14311                             intel_state->wm_results.dirty_pipes != updated)
14312                                 vbl_wait = true;
14313
14314                         intel_update_crtc(crtc, state, old_crtc_state,
14315                                           crtc_vblank_mask);
14316
14317                         if (vbl_wait)
14318                                 intel_wait_for_vblank(dev_priv, pipe);
14319
14320                         progress = true;
14321                 }
14322         } while (progress);
14323 }
14324
14325 static void intel_atomic_commit_tail(struct drm_atomic_state *state)
14326 {
14327         struct drm_device *dev = state->dev;
14328         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
14329         struct drm_i915_private *dev_priv = to_i915(dev);
14330         struct drm_crtc_state *old_crtc_state;
14331         struct drm_crtc *crtc;
14332         struct intel_crtc_state *intel_cstate;
14333         bool hw_check = intel_state->modeset;
14334         unsigned long put_domains[I915_MAX_PIPES] = {};
14335         unsigned crtc_vblank_mask = 0;
14336         int i;
14337
14338         drm_atomic_helper_wait_for_dependencies(state);
14339
14340         if (intel_state->modeset)
14341                 intel_display_power_get(dev_priv, POWER_DOMAIN_MODESET);
14342
14343         for_each_crtc_in_state(state, crtc, old_crtc_state, i) {
14344                 struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
14345
14346                 if (needs_modeset(crtc->state) ||
14347                     to_intel_crtc_state(crtc->state)->update_pipe) {
14348                         hw_check = true;
14349
14350                         put_domains[to_intel_crtc(crtc)->pipe] =
14351                                 modeset_get_crtc_power_domains(crtc,
14352                                         to_intel_crtc_state(crtc->state));
14353                 }
14354
14355                 if (!needs_modeset(crtc->state))
14356                         continue;
14357
14358                 intel_pre_plane_update(to_intel_crtc_state(old_crtc_state));
14359
14360                 if (old_crtc_state->active) {
14361                         intel_crtc_disable_planes(crtc, old_crtc_state->plane_mask);
14362                         dev_priv->display.crtc_disable(to_intel_crtc_state(old_crtc_state), state);
14363                         intel_crtc->active = false;
14364                         intel_fbc_disable(intel_crtc);
14365                         intel_disable_shared_dpll(intel_crtc);
14366
14367                         /*
14368                          * Underruns don't always raise
14369                          * interrupts, so check manually.
14370                          */
14371                         intel_check_cpu_fifo_underruns(dev_priv);
14372                         intel_check_pch_fifo_underruns(dev_priv);
14373
14374                         if (!crtc->state->active) {
14375                                 /*
14376                                  * Make sure we don't call initial_watermarks
14377                                  * for ILK-style watermark updates.
14378                                  */
14379                                 if (dev_priv->display.atomic_update_watermarks)
14380                                         dev_priv->display.initial_watermarks(intel_state,
14381                                                                              to_intel_crtc_state(crtc->state));
14382                                 else
14383                                         intel_update_watermarks(intel_crtc);
14384                         }
14385                 }
14386         }
14387
14388         /* Only after disabling all output pipelines that will be changed can we
14389          * update the the output configuration. */
14390         intel_modeset_update_crtc_state(state);
14391
14392         if (intel_state->modeset) {
14393                 drm_atomic_helper_update_legacy_modeset_state(state->dev, state);
14394
14395                 if (dev_priv->display.modeset_commit_cdclk &&
14396                     (intel_state->dev_cdclk != dev_priv->cdclk_freq ||
14397                      intel_state->cdclk_pll_vco != dev_priv->cdclk_pll.vco))
14398                         dev_priv->display.modeset_commit_cdclk(state);
14399
14400                 /*
14401                  * SKL workaround: bspec recommends we disable the SAGV when we
14402                  * have more then one pipe enabled
14403                  */
14404                 if (!intel_can_enable_sagv(state))
14405                         intel_disable_sagv(dev_priv);
14406
14407                 intel_modeset_verify_disabled(dev, state);
14408         }
14409
14410         /* Complete the events for pipes that have now been disabled */
14411         for_each_crtc_in_state(state, crtc, old_crtc_state, i) {
14412                 bool modeset = needs_modeset(crtc->state);
14413
14414                 /* Complete events for now disable pipes here. */
14415                 if (modeset && !crtc->state->active && crtc->state->event) {
14416                         spin_lock_irq(&dev->event_lock);
14417                         drm_crtc_send_vblank_event(crtc, crtc->state->event);
14418                         spin_unlock_irq(&dev->event_lock);
14419
14420                         crtc->state->event = NULL;
14421                 }
14422         }
14423
14424         /* Now enable the clocks, plane, pipe, and connectors that we set up. */
14425         dev_priv->display.update_crtcs(state, &crtc_vblank_mask);
14426
14427         /* FIXME: We should call drm_atomic_helper_commit_hw_done() here
14428          * already, but still need the state for the delayed optimization. To
14429          * fix this:
14430          * - wrap the optimization/post_plane_update stuff into a per-crtc work.
14431          * - schedule that vblank worker _before_ calling hw_done
14432          * - at the start of commit_tail, cancel it _synchrously
14433          * - switch over to the vblank wait helper in the core after that since
14434          *   we don't need out special handling any more.
14435          */
14436         if (!state->legacy_cursor_update)
14437                 intel_atomic_wait_for_vblanks(dev, dev_priv, crtc_vblank_mask);
14438
14439         /*
14440          * Now that the vblank has passed, we can go ahead and program the
14441          * optimal watermarks on platforms that need two-step watermark
14442          * programming.
14443          *
14444          * TODO: Move this (and other cleanup) to an async worker eventually.
14445          */
14446         for_each_crtc_in_state(state, crtc, old_crtc_state, i) {
14447                 intel_cstate = to_intel_crtc_state(crtc->state);
14448
14449                 if (dev_priv->display.optimize_watermarks)
14450                         dev_priv->display.optimize_watermarks(intel_state,
14451                                                               intel_cstate);
14452         }
14453
14454         for_each_crtc_in_state(state, crtc, old_crtc_state, i) {
14455                 intel_post_plane_update(to_intel_crtc_state(old_crtc_state));
14456
14457                 if (put_domains[i])
14458                         modeset_put_power_domains(dev_priv, put_domains[i]);
14459
14460                 intel_modeset_verify_crtc(crtc, state, old_crtc_state, crtc->state);
14461         }
14462
14463         if (intel_state->modeset && intel_can_enable_sagv(state))
14464                 intel_enable_sagv(dev_priv);
14465
14466         drm_atomic_helper_commit_hw_done(state);
14467
14468         if (intel_state->modeset)
14469                 intel_display_power_put(dev_priv, POWER_DOMAIN_MODESET);
14470
14471         mutex_lock(&dev->struct_mutex);
14472         drm_atomic_helper_cleanup_planes(dev, state);
14473         mutex_unlock(&dev->struct_mutex);
14474
14475         drm_atomic_helper_commit_cleanup_done(state);
14476
14477         drm_atomic_state_put(state);
14478
14479         /* As one of the primary mmio accessors, KMS has a high likelihood
14480          * of triggering bugs in unclaimed access. After we finish
14481          * modesetting, see if an error has been flagged, and if so
14482          * enable debugging for the next modeset - and hope we catch
14483          * the culprit.
14484          *
14485          * XXX note that we assume display power is on at this point.
14486          * This might hold true now but we need to add pm helper to check
14487          * unclaimed only when the hardware is on, as atomic commits
14488          * can happen also when the device is completely off.
14489          */
14490         intel_uncore_arm_unclaimed_mmio_detection(dev_priv);
14491 }
14492
14493 static void intel_atomic_commit_work(struct work_struct *work)
14494 {
14495         struct drm_atomic_state *state =
14496                 container_of(work, struct drm_atomic_state, commit_work);
14497
14498         intel_atomic_commit_tail(state);
14499 }
14500
14501 static int __i915_sw_fence_call
14502 intel_atomic_commit_ready(struct i915_sw_fence *fence,
14503                           enum i915_sw_fence_notify notify)
14504 {
14505         struct intel_atomic_state *state =
14506                 container_of(fence, struct intel_atomic_state, commit_ready);
14507
14508         switch (notify) {
14509         case FENCE_COMPLETE:
14510                 if (state->base.commit_work.func)
14511                         queue_work(system_unbound_wq, &state->base.commit_work);
14512                 break;
14513
14514         case FENCE_FREE:
14515                 drm_atomic_state_put(&state->base);
14516                 break;
14517         }
14518
14519         return NOTIFY_DONE;
14520 }
14521
14522 static void intel_atomic_track_fbs(struct drm_atomic_state *state)
14523 {
14524         struct drm_plane_state *old_plane_state;
14525         struct drm_plane *plane;
14526         int i;
14527
14528         for_each_plane_in_state(state, plane, old_plane_state, i)
14529                 i915_gem_track_fb(intel_fb_obj(old_plane_state->fb),
14530                                   intel_fb_obj(plane->state->fb),
14531                                   to_intel_plane(plane)->frontbuffer_bit);
14532 }
14533
14534 /**
14535  * intel_atomic_commit - commit validated state object
14536  * @dev: DRM device
14537  * @state: the top-level driver state object
14538  * @nonblock: nonblocking commit
14539  *
14540  * This function commits a top-level state object that has been validated
14541  * with drm_atomic_helper_check().
14542  *
14543  * RETURNS
14544  * Zero for success or -errno.
14545  */
14546 static int intel_atomic_commit(struct drm_device *dev,
14547                                struct drm_atomic_state *state,
14548                                bool nonblock)
14549 {
14550         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
14551         struct drm_i915_private *dev_priv = to_i915(dev);
14552         int ret = 0;
14553
14554         ret = drm_atomic_helper_setup_commit(state, nonblock);
14555         if (ret)
14556                 return ret;
14557
14558         drm_atomic_state_get(state);
14559         i915_sw_fence_init(&intel_state->commit_ready,
14560                            intel_atomic_commit_ready);
14561
14562         ret = intel_atomic_prepare_commit(dev, state);
14563         if (ret) {
14564                 DRM_DEBUG_ATOMIC("Preparing state failed with %i\n", ret);
14565                 i915_sw_fence_commit(&intel_state->commit_ready);
14566                 return ret;
14567         }
14568
14569         drm_atomic_helper_swap_state(state, true);
14570         dev_priv->wm.distrust_bios_wm = false;
14571         intel_shared_dpll_commit(state);
14572         intel_atomic_track_fbs(state);
14573
14574         if (intel_state->modeset) {
14575                 memcpy(dev_priv->min_pixclk, intel_state->min_pixclk,
14576                        sizeof(intel_state->min_pixclk));
14577                 dev_priv->active_crtcs = intel_state->active_crtcs;
14578                 dev_priv->atomic_cdclk_freq = intel_state->cdclk;
14579         }
14580
14581         drm_atomic_state_get(state);
14582         INIT_WORK(&state->commit_work,
14583                   nonblock ? intel_atomic_commit_work : NULL);
14584
14585         i915_sw_fence_commit(&intel_state->commit_ready);
14586         if (!nonblock) {
14587                 i915_sw_fence_wait(&intel_state->commit_ready);
14588                 intel_atomic_commit_tail(state);
14589         }
14590
14591         return 0;
14592 }
14593
14594 void intel_crtc_restore_mode(struct drm_crtc *crtc)
14595 {
14596         struct drm_device *dev = crtc->dev;
14597         struct drm_atomic_state *state;
14598         struct drm_crtc_state *crtc_state;
14599         int ret;
14600
14601         state = drm_atomic_state_alloc(dev);
14602         if (!state) {
14603                 DRM_DEBUG_KMS("[CRTC:%d:%s] crtc restore failed, out of memory",
14604                               crtc->base.id, crtc->name);
14605                 return;
14606         }
14607
14608         state->acquire_ctx = drm_modeset_legacy_acquire_ctx(crtc);
14609
14610 retry:
14611         crtc_state = drm_atomic_get_crtc_state(state, crtc);
14612         ret = PTR_ERR_OR_ZERO(crtc_state);
14613         if (!ret) {
14614                 if (!crtc_state->active)
14615                         goto out;
14616
14617                 crtc_state->mode_changed = true;
14618                 ret = drm_atomic_commit(state);
14619         }
14620
14621         if (ret == -EDEADLK) {
14622                 drm_atomic_state_clear(state);
14623                 drm_modeset_backoff(state->acquire_ctx);
14624                 goto retry;
14625         }
14626
14627 out:
14628         drm_atomic_state_put(state);
14629 }
14630
14631 /*
14632  * FIXME: Remove this once i915 is fully DRIVER_ATOMIC by calling
14633  *        drm_atomic_helper_legacy_gamma_set() directly.
14634  */
14635 static int intel_atomic_legacy_gamma_set(struct drm_crtc *crtc,
14636                                          u16 *red, u16 *green, u16 *blue,
14637                                          uint32_t size)
14638 {
14639         struct drm_device *dev = crtc->dev;
14640         struct drm_mode_config *config = &dev->mode_config;
14641         struct drm_crtc_state *state;
14642         int ret;
14643
14644         ret = drm_atomic_helper_legacy_gamma_set(crtc, red, green, blue, size);
14645         if (ret)
14646                 return ret;
14647
14648         /*
14649          * Make sure we update the legacy properties so this works when
14650          * atomic is not enabled.
14651          */
14652
14653         state = crtc->state;
14654
14655         drm_object_property_set_value(&crtc->base,
14656                                       config->degamma_lut_property,
14657                                       (state->degamma_lut) ?
14658                                       state->degamma_lut->base.id : 0);
14659
14660         drm_object_property_set_value(&crtc->base,
14661                                       config->ctm_property,
14662                                       (state->ctm) ?
14663                                       state->ctm->base.id : 0);
14664
14665         drm_object_property_set_value(&crtc->base,
14666                                       config->gamma_lut_property,
14667                                       (state->gamma_lut) ?
14668                                       state->gamma_lut->base.id : 0);
14669
14670         return 0;
14671 }
14672
14673 static const struct drm_crtc_funcs intel_crtc_funcs = {
14674         .gamma_set = intel_atomic_legacy_gamma_set,
14675         .set_config = drm_atomic_helper_set_config,
14676         .set_property = drm_atomic_helper_crtc_set_property,
14677         .destroy = intel_crtc_destroy,
14678         .page_flip = intel_crtc_page_flip,
14679         .atomic_duplicate_state = intel_crtc_duplicate_state,
14680         .atomic_destroy_state = intel_crtc_destroy_state,
14681 };
14682
14683 /**
14684  * intel_prepare_plane_fb - Prepare fb for usage on plane
14685  * @plane: drm plane to prepare for
14686  * @fb: framebuffer to prepare for presentation
14687  *
14688  * Prepares a framebuffer for usage on a display plane.  Generally this
14689  * involves pinning the underlying object and updating the frontbuffer tracking
14690  * bits.  Some older platforms need special physical address handling for
14691  * cursor planes.
14692  *
14693  * Must be called with struct_mutex held.
14694  *
14695  * Returns 0 on success, negative error code on failure.
14696  */
14697 int
14698 intel_prepare_plane_fb(struct drm_plane *plane,
14699                        struct drm_plane_state *new_state)
14700 {
14701         struct intel_atomic_state *intel_state =
14702                 to_intel_atomic_state(new_state->state);
14703         struct drm_i915_private *dev_priv = to_i915(plane->dev);
14704         struct drm_framebuffer *fb = new_state->fb;
14705         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
14706         struct drm_i915_gem_object *old_obj = intel_fb_obj(plane->state->fb);
14707         int ret;
14708
14709         if (!obj && !old_obj)
14710                 return 0;
14711
14712         if (old_obj) {
14713                 struct drm_crtc_state *crtc_state =
14714                         drm_atomic_get_existing_crtc_state(new_state->state,
14715                                                            plane->state->crtc);
14716
14717                 /* Big Hammer, we also need to ensure that any pending
14718                  * MI_WAIT_FOR_EVENT inside a user batch buffer on the
14719                  * current scanout is retired before unpinning the old
14720                  * framebuffer. Note that we rely on userspace rendering
14721                  * into the buffer attached to the pipe they are waiting
14722                  * on. If not, userspace generates a GPU hang with IPEHR
14723                  * point to the MI_WAIT_FOR_EVENT.
14724                  *
14725                  * This should only fail upon a hung GPU, in which case we
14726                  * can safely continue.
14727                  */
14728                 if (needs_modeset(crtc_state)) {
14729                         ret = i915_sw_fence_await_reservation(&intel_state->commit_ready,
14730                                                               old_obj->resv, NULL,
14731                                                               false, 0,
14732                                                               GFP_KERNEL);
14733                         if (ret < 0)
14734                                 return ret;
14735                 }
14736         }
14737
14738         if (new_state->fence) { /* explicit fencing */
14739                 ret = i915_sw_fence_await_dma_fence(&intel_state->commit_ready,
14740                                                     new_state->fence,
14741                                                     I915_FENCE_TIMEOUT,
14742                                                     GFP_KERNEL);
14743                 if (ret < 0)
14744                         return ret;
14745         }
14746
14747         if (!obj)
14748                 return 0;
14749
14750         if (!new_state->fence) { /* implicit fencing */
14751                 ret = i915_sw_fence_await_reservation(&intel_state->commit_ready,
14752                                                       obj->resv, NULL,
14753                                                       false, I915_FENCE_TIMEOUT,
14754                                                       GFP_KERNEL);
14755                 if (ret < 0)
14756                         return ret;
14757
14758                 i915_gem_object_wait_priority(obj, 0, I915_PRIORITY_DISPLAY);
14759         }
14760
14761         if (plane->type == DRM_PLANE_TYPE_CURSOR &&
14762             INTEL_INFO(dev_priv)->cursor_needs_physical) {
14763                 int align = IS_I830(dev_priv) ? 16 * 1024 : 256;
14764                 ret = i915_gem_object_attach_phys(obj, align);
14765                 if (ret) {
14766                         DRM_DEBUG_KMS("failed to attach phys object\n");
14767                         return ret;
14768                 }
14769         } else {
14770                 struct i915_vma *vma;
14771
14772                 vma = intel_pin_and_fence_fb_obj(fb, new_state->rotation);
14773                 if (IS_ERR(vma)) {
14774                         DRM_DEBUG_KMS("failed to pin object\n");
14775                         return PTR_ERR(vma);
14776                 }
14777         }
14778
14779         return 0;
14780 }
14781
14782 /**
14783  * intel_cleanup_plane_fb - Cleans up an fb after plane use
14784  * @plane: drm plane to clean up for
14785  * @fb: old framebuffer that was on plane
14786  *
14787  * Cleans up a framebuffer that has just been removed from a plane.
14788  *
14789  * Must be called with struct_mutex held.
14790  */
14791 void
14792 intel_cleanup_plane_fb(struct drm_plane *plane,
14793                        struct drm_plane_state *old_state)
14794 {
14795         struct drm_i915_private *dev_priv = to_i915(plane->dev);
14796         struct intel_plane_state *old_intel_state;
14797         struct drm_i915_gem_object *old_obj = intel_fb_obj(old_state->fb);
14798         struct drm_i915_gem_object *obj = intel_fb_obj(plane->state->fb);
14799
14800         old_intel_state = to_intel_plane_state(old_state);
14801
14802         if (!obj && !old_obj)
14803                 return;
14804
14805         if (old_obj && (plane->type != DRM_PLANE_TYPE_CURSOR ||
14806             !INTEL_INFO(dev_priv)->cursor_needs_physical))
14807                 intel_unpin_fb_obj(old_state->fb, old_state->rotation);
14808 }
14809
14810 int
14811 skl_max_scale(struct intel_crtc *intel_crtc, struct intel_crtc_state *crtc_state)
14812 {
14813         int max_scale;
14814         int crtc_clock, cdclk;
14815
14816         if (!intel_crtc || !crtc_state->base.enable)
14817                 return DRM_PLANE_HELPER_NO_SCALING;
14818
14819         crtc_clock = crtc_state->base.adjusted_mode.crtc_clock;
14820         cdclk = to_intel_atomic_state(crtc_state->base.state)->cdclk;
14821
14822         if (WARN_ON_ONCE(!crtc_clock || cdclk < crtc_clock))
14823                 return DRM_PLANE_HELPER_NO_SCALING;
14824
14825         /*
14826          * skl max scale is lower of:
14827          *    close to 3 but not 3, -1 is for that purpose
14828          *            or
14829          *    cdclk/crtc_clock
14830          */
14831         max_scale = min((1 << 16) * 3 - 1, (1 << 8) * ((cdclk << 8) / crtc_clock));
14832
14833         return max_scale;
14834 }
14835
14836 static int
14837 intel_check_primary_plane(struct drm_plane *plane,
14838                           struct intel_crtc_state *crtc_state,
14839                           struct intel_plane_state *state)
14840 {
14841         struct drm_i915_private *dev_priv = to_i915(plane->dev);
14842         struct drm_crtc *crtc = state->base.crtc;
14843         int min_scale = DRM_PLANE_HELPER_NO_SCALING;
14844         int max_scale = DRM_PLANE_HELPER_NO_SCALING;
14845         bool can_position = false;
14846         int ret;
14847
14848         if (INTEL_GEN(dev_priv) >= 9) {
14849                 /* use scaler when colorkey is not required */
14850                 if (state->ckey.flags == I915_SET_COLORKEY_NONE) {
14851                         min_scale = 1;
14852                         max_scale = skl_max_scale(to_intel_crtc(crtc), crtc_state);
14853                 }
14854                 can_position = true;
14855         }
14856
14857         ret = drm_plane_helper_check_state(&state->base,
14858                                            &state->clip,
14859                                            min_scale, max_scale,
14860                                            can_position, true);
14861         if (ret)
14862                 return ret;
14863
14864         if (!state->base.fb)
14865                 return 0;
14866
14867         if (INTEL_GEN(dev_priv) >= 9) {
14868                 ret = skl_check_plane_surface(state);
14869                 if (ret)
14870                         return ret;
14871         }
14872
14873         return 0;
14874 }
14875
14876 static void intel_begin_crtc_commit(struct drm_crtc *crtc,
14877                                     struct drm_crtc_state *old_crtc_state)
14878 {
14879         struct drm_device *dev = crtc->dev;
14880         struct drm_i915_private *dev_priv = to_i915(dev);
14881         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
14882         struct intel_crtc_state *intel_cstate =
14883                 to_intel_crtc_state(crtc->state);
14884         struct intel_crtc_state *old_intel_cstate =
14885                 to_intel_crtc_state(old_crtc_state);
14886         struct intel_atomic_state *old_intel_state =
14887                 to_intel_atomic_state(old_crtc_state->state);
14888         bool modeset = needs_modeset(crtc->state);
14889
14890         /* Perform vblank evasion around commit operation */
14891         intel_pipe_update_start(intel_crtc);
14892
14893         if (modeset)
14894                 goto out;
14895
14896         if (crtc->state->color_mgmt_changed || to_intel_crtc_state(crtc->state)->update_pipe) {
14897                 intel_color_set_csc(crtc->state);
14898                 intel_color_load_luts(crtc->state);
14899         }
14900
14901         if (intel_cstate->update_pipe)
14902                 intel_update_pipe_config(intel_crtc, old_intel_cstate);
14903         else if (INTEL_GEN(dev_priv) >= 9)
14904                 skl_detach_scalers(intel_crtc);
14905
14906 out:
14907         if (dev_priv->display.atomic_update_watermarks)
14908                 dev_priv->display.atomic_update_watermarks(old_intel_state,
14909                                                            intel_cstate);
14910 }
14911
14912 static void intel_finish_crtc_commit(struct drm_crtc *crtc,
14913                                      struct drm_crtc_state *old_crtc_state)
14914 {
14915         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
14916
14917         intel_pipe_update_end(intel_crtc, NULL);
14918 }
14919
14920 /**
14921  * intel_plane_destroy - destroy a plane
14922  * @plane: plane to destroy
14923  *
14924  * Common destruction function for all types of planes (primary, cursor,
14925  * sprite).
14926  */
14927 void intel_plane_destroy(struct drm_plane *plane)
14928 {
14929         drm_plane_cleanup(plane);
14930         kfree(to_intel_plane(plane));
14931 }
14932
14933 const struct drm_plane_funcs intel_plane_funcs = {
14934         .update_plane = drm_atomic_helper_update_plane,
14935         .disable_plane = drm_atomic_helper_disable_plane,
14936         .destroy = intel_plane_destroy,
14937         .set_property = drm_atomic_helper_plane_set_property,
14938         .atomic_get_property = intel_plane_atomic_get_property,
14939         .atomic_set_property = intel_plane_atomic_set_property,
14940         .atomic_duplicate_state = intel_plane_duplicate_state,
14941         .atomic_destroy_state = intel_plane_destroy_state,
14942 };
14943
14944 static struct intel_plane *
14945 intel_primary_plane_create(struct drm_i915_private *dev_priv, enum pipe pipe)
14946 {
14947         struct intel_plane *primary = NULL;
14948         struct intel_plane_state *state = NULL;
14949         const uint32_t *intel_primary_formats;
14950         unsigned int supported_rotations;
14951         unsigned int num_formats;
14952         int ret;
14953
14954         primary = kzalloc(sizeof(*primary), GFP_KERNEL);
14955         if (!primary) {
14956                 ret = -ENOMEM;
14957                 goto fail;
14958         }
14959
14960         state = intel_create_plane_state(&primary->base);
14961         if (!state) {
14962                 ret = -ENOMEM;
14963                 goto fail;
14964         }
14965
14966         primary->base.state = &state->base;
14967
14968         primary->can_scale = false;
14969         primary->max_downscale = 1;
14970         if (INTEL_GEN(dev_priv) >= 9) {
14971                 primary->can_scale = true;
14972                 state->scaler_id = -1;
14973         }
14974         primary->pipe = pipe;
14975         /*
14976          * On gen2/3 only plane A can do FBC, but the panel fitter and LVDS
14977          * port is hooked to pipe B. Hence we want plane A feeding pipe B.
14978          */
14979         if (HAS_FBC(dev_priv) && INTEL_GEN(dev_priv) < 4)
14980                 primary->plane = (enum plane) !pipe;
14981         else
14982                 primary->plane = (enum plane) pipe;
14983         primary->frontbuffer_bit = INTEL_FRONTBUFFER_PRIMARY(pipe);
14984         primary->check_plane = intel_check_primary_plane;
14985
14986         if (INTEL_GEN(dev_priv) >= 9) {
14987                 intel_primary_formats = skl_primary_formats;
14988                 num_formats = ARRAY_SIZE(skl_primary_formats);
14989
14990                 primary->update_plane = skylake_update_primary_plane;
14991                 primary->disable_plane = skylake_disable_primary_plane;
14992         } else if (HAS_PCH_SPLIT(dev_priv)) {
14993                 intel_primary_formats = i965_primary_formats;
14994                 num_formats = ARRAY_SIZE(i965_primary_formats);
14995
14996                 primary->update_plane = ironlake_update_primary_plane;
14997                 primary->disable_plane = i9xx_disable_primary_plane;
14998         } else if (INTEL_GEN(dev_priv) >= 4) {
14999                 intel_primary_formats = i965_primary_formats;
15000                 num_formats = ARRAY_SIZE(i965_primary_formats);
15001
15002                 primary->update_plane = i9xx_update_primary_plane;
15003                 primary->disable_plane = i9xx_disable_primary_plane;
15004         } else {
15005                 intel_primary_formats = i8xx_primary_formats;
15006                 num_formats = ARRAY_SIZE(i8xx_primary_formats);
15007
15008                 primary->update_plane = i9xx_update_primary_plane;
15009                 primary->disable_plane = i9xx_disable_primary_plane;
15010         }
15011
15012         if (INTEL_GEN(dev_priv) >= 9)
15013                 ret = drm_universal_plane_init(&dev_priv->drm, &primary->base,
15014                                                0, &intel_plane_funcs,
15015                                                intel_primary_formats, num_formats,
15016                                                DRM_PLANE_TYPE_PRIMARY,
15017                                                "plane 1%c", pipe_name(pipe));
15018         else if (INTEL_GEN(dev_priv) >= 5 || IS_G4X(dev_priv))
15019                 ret = drm_universal_plane_init(&dev_priv->drm, &primary->base,
15020                                                0, &intel_plane_funcs,
15021                                                intel_primary_formats, num_formats,
15022                                                DRM_PLANE_TYPE_PRIMARY,
15023                                                "primary %c", pipe_name(pipe));
15024         else
15025                 ret = drm_universal_plane_init(&dev_priv->drm, &primary->base,
15026                                                0, &intel_plane_funcs,
15027                                                intel_primary_formats, num_formats,
15028                                                DRM_PLANE_TYPE_PRIMARY,
15029                                                "plane %c", plane_name(primary->plane));
15030         if (ret)
15031                 goto fail;
15032
15033         if (INTEL_GEN(dev_priv) >= 9) {
15034                 supported_rotations =
15035                         DRM_ROTATE_0 | DRM_ROTATE_90 |
15036                         DRM_ROTATE_180 | DRM_ROTATE_270;
15037         } else if (IS_CHERRYVIEW(dev_priv) && pipe == PIPE_B) {
15038                 supported_rotations =
15039                         DRM_ROTATE_0 | DRM_ROTATE_180 |
15040                         DRM_REFLECT_X;
15041         } else if (INTEL_GEN(dev_priv) >= 4) {
15042                 supported_rotations =
15043                         DRM_ROTATE_0 | DRM_ROTATE_180;
15044         } else {
15045                 supported_rotations = DRM_ROTATE_0;
15046         }
15047
15048         if (INTEL_GEN(dev_priv) >= 4)
15049                 drm_plane_create_rotation_property(&primary->base,
15050                                                    DRM_ROTATE_0,
15051                                                    supported_rotations);
15052
15053         drm_plane_helper_add(&primary->base, &intel_plane_helper_funcs);
15054
15055         return primary;
15056
15057 fail:
15058         kfree(state);
15059         kfree(primary);
15060
15061         return ERR_PTR(ret);
15062 }
15063
15064 static int
15065 intel_check_cursor_plane(struct drm_plane *plane,
15066                          struct intel_crtc_state *crtc_state,
15067                          struct intel_plane_state *state)
15068 {
15069         struct drm_framebuffer *fb = state->base.fb;
15070         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
15071         enum pipe pipe = to_intel_plane(plane)->pipe;
15072         unsigned stride;
15073         int ret;
15074
15075         ret = drm_plane_helper_check_state(&state->base,
15076                                            &state->clip,
15077                                            DRM_PLANE_HELPER_NO_SCALING,
15078                                            DRM_PLANE_HELPER_NO_SCALING,
15079                                            true, true);
15080         if (ret)
15081                 return ret;
15082
15083         /* if we want to turn off the cursor ignore width and height */
15084         if (!obj)
15085                 return 0;
15086
15087         /* Check for which cursor types we support */
15088         if (!cursor_size_ok(to_i915(plane->dev), state->base.crtc_w,
15089                             state->base.crtc_h)) {
15090                 DRM_DEBUG("Cursor dimension %dx%d not supported\n",
15091                           state->base.crtc_w, state->base.crtc_h);
15092                 return -EINVAL;
15093         }
15094
15095         stride = roundup_pow_of_two(state->base.crtc_w) * 4;
15096         if (obj->base.size < stride * state->base.crtc_h) {
15097                 DRM_DEBUG_KMS("buffer is too small\n");
15098                 return -ENOMEM;
15099         }
15100
15101         if (fb->modifier != DRM_FORMAT_MOD_NONE) {
15102                 DRM_DEBUG_KMS("cursor cannot be tiled\n");
15103                 return -EINVAL;
15104         }
15105
15106         /*
15107          * There's something wrong with the cursor on CHV pipe C.
15108          * If it straddles the left edge of the screen then
15109          * moving it away from the edge or disabling it often
15110          * results in a pipe underrun, and often that can lead to
15111          * dead pipe (constant underrun reported, and it scans
15112          * out just a solid color). To recover from that, the
15113          * display power well must be turned off and on again.
15114          * Refuse the put the cursor into that compromised position.
15115          */
15116         if (IS_CHERRYVIEW(to_i915(plane->dev)) && pipe == PIPE_C &&
15117             state->base.visible && state->base.crtc_x < 0) {
15118                 DRM_DEBUG_KMS("CHV cursor C not allowed to straddle the left screen edge\n");
15119                 return -EINVAL;
15120         }
15121
15122         return 0;
15123 }
15124
15125 static void
15126 intel_disable_cursor_plane(struct drm_plane *plane,
15127                            struct drm_crtc *crtc)
15128 {
15129         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
15130
15131         intel_crtc->cursor_addr = 0;
15132         intel_crtc_update_cursor(crtc, NULL);
15133 }
15134
15135 static void
15136 intel_update_cursor_plane(struct drm_plane *plane,
15137                           const struct intel_crtc_state *crtc_state,
15138                           const struct intel_plane_state *state)
15139 {
15140         struct drm_crtc *crtc = crtc_state->base.crtc;
15141         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
15142         struct drm_i915_private *dev_priv = to_i915(plane->dev);
15143         struct drm_i915_gem_object *obj = intel_fb_obj(state->base.fb);
15144         uint32_t addr;
15145
15146         if (!obj)
15147                 addr = 0;
15148         else if (!INTEL_INFO(dev_priv)->cursor_needs_physical)
15149                 addr = i915_gem_object_ggtt_offset(obj, NULL);
15150         else
15151                 addr = obj->phys_handle->busaddr;
15152
15153         intel_crtc->cursor_addr = addr;
15154         intel_crtc_update_cursor(crtc, state);
15155 }
15156
15157 static struct intel_plane *
15158 intel_cursor_plane_create(struct drm_i915_private *dev_priv, enum pipe pipe)
15159 {
15160         struct intel_plane *cursor = NULL;
15161         struct intel_plane_state *state = NULL;
15162         int ret;
15163
15164         cursor = kzalloc(sizeof(*cursor), GFP_KERNEL);
15165         if (!cursor) {
15166                 ret = -ENOMEM;
15167                 goto fail;
15168         }
15169
15170         state = intel_create_plane_state(&cursor->base);
15171         if (!state) {
15172                 ret = -ENOMEM;
15173                 goto fail;
15174         }
15175
15176         cursor->base.state = &state->base;
15177
15178         cursor->can_scale = false;
15179         cursor->max_downscale = 1;
15180         cursor->pipe = pipe;
15181         cursor->plane = pipe;
15182         cursor->frontbuffer_bit = INTEL_FRONTBUFFER_CURSOR(pipe);
15183         cursor->check_plane = intel_check_cursor_plane;
15184         cursor->update_plane = intel_update_cursor_plane;
15185         cursor->disable_plane = intel_disable_cursor_plane;
15186
15187         ret = drm_universal_plane_init(&dev_priv->drm, &cursor->base,
15188                                        0, &intel_plane_funcs,
15189                                        intel_cursor_formats,
15190                                        ARRAY_SIZE(intel_cursor_formats),
15191                                        DRM_PLANE_TYPE_CURSOR,
15192                                        "cursor %c", pipe_name(pipe));
15193         if (ret)
15194                 goto fail;
15195
15196         if (INTEL_GEN(dev_priv) >= 4)
15197                 drm_plane_create_rotation_property(&cursor->base,
15198                                                    DRM_ROTATE_0,
15199                                                    DRM_ROTATE_0 |
15200                                                    DRM_ROTATE_180);
15201
15202         if (INTEL_GEN(dev_priv) >= 9)
15203                 state->scaler_id = -1;
15204
15205         drm_plane_helper_add(&cursor->base, &intel_plane_helper_funcs);
15206
15207         return cursor;
15208
15209 fail:
15210         kfree(state);
15211         kfree(cursor);
15212
15213         return ERR_PTR(ret);
15214 }
15215
15216 static void skl_init_scalers(struct drm_i915_private *dev_priv,
15217                              struct intel_crtc *crtc,
15218                              struct intel_crtc_state *crtc_state)
15219 {
15220         struct intel_crtc_scaler_state *scaler_state =
15221                 &crtc_state->scaler_state;
15222         int i;
15223
15224         for (i = 0; i < crtc->num_scalers; i++) {
15225                 struct intel_scaler *scaler = &scaler_state->scalers[i];
15226
15227                 scaler->in_use = 0;
15228                 scaler->mode = PS_SCALER_MODE_DYN;
15229         }
15230
15231         scaler_state->scaler_id = -1;
15232 }
15233
15234 static int intel_crtc_init(struct drm_i915_private *dev_priv, enum pipe pipe)
15235 {
15236         struct intel_crtc *intel_crtc;
15237         struct intel_crtc_state *crtc_state = NULL;
15238         struct intel_plane *primary = NULL;
15239         struct intel_plane *cursor = NULL;
15240         int sprite, ret;
15241
15242         intel_crtc = kzalloc(sizeof(*intel_crtc), GFP_KERNEL);
15243         if (!intel_crtc)
15244                 return -ENOMEM;
15245
15246         crtc_state = kzalloc(sizeof(*crtc_state), GFP_KERNEL);
15247         if (!crtc_state) {
15248                 ret = -ENOMEM;
15249                 goto fail;
15250         }
15251         intel_crtc->config = crtc_state;
15252         intel_crtc->base.state = &crtc_state->base;
15253         crtc_state->base.crtc = &intel_crtc->base;
15254
15255         /* initialize shared scalers */
15256         if (INTEL_GEN(dev_priv) >= 9) {
15257                 if (pipe == PIPE_C)
15258                         intel_crtc->num_scalers = 1;
15259                 else
15260                         intel_crtc->num_scalers = SKL_NUM_SCALERS;
15261
15262                 skl_init_scalers(dev_priv, intel_crtc, crtc_state);
15263         }
15264
15265         primary = intel_primary_plane_create(dev_priv, pipe);
15266         if (IS_ERR(primary)) {
15267                 ret = PTR_ERR(primary);
15268                 goto fail;
15269         }
15270
15271         for_each_sprite(dev_priv, pipe, sprite) {
15272                 struct intel_plane *plane;
15273
15274                 plane = intel_sprite_plane_create(dev_priv, pipe, sprite);
15275                 if (IS_ERR(plane)) {
15276                         ret = PTR_ERR(plane);
15277                         goto fail;
15278                 }
15279         }
15280
15281         cursor = intel_cursor_plane_create(dev_priv, pipe);
15282         if (IS_ERR(cursor)) {
15283                 ret = PTR_ERR(cursor);
15284                 goto fail;
15285         }
15286
15287         ret = drm_crtc_init_with_planes(&dev_priv->drm, &intel_crtc->base,
15288                                         &primary->base, &cursor->base,
15289                                         &intel_crtc_funcs,
15290                                         "pipe %c", pipe_name(pipe));
15291         if (ret)
15292                 goto fail;
15293
15294         intel_crtc->pipe = pipe;
15295         intel_crtc->plane = primary->plane;
15296
15297         intel_crtc->cursor_base = ~0;
15298         intel_crtc->cursor_cntl = ~0;
15299         intel_crtc->cursor_size = ~0;
15300
15301         intel_crtc->wm.cxsr_allowed = true;
15302
15303         BUG_ON(pipe >= ARRAY_SIZE(dev_priv->plane_to_crtc_mapping) ||
15304                dev_priv->plane_to_crtc_mapping[intel_crtc->plane] != NULL);
15305         dev_priv->plane_to_crtc_mapping[intel_crtc->plane] = intel_crtc;
15306         dev_priv->pipe_to_crtc_mapping[intel_crtc->pipe] = intel_crtc;
15307
15308         drm_crtc_helper_add(&intel_crtc->base, &intel_helper_funcs);
15309
15310         intel_color_init(&intel_crtc->base);
15311
15312         WARN_ON(drm_crtc_index(&intel_crtc->base) != intel_crtc->pipe);
15313
15314         return 0;
15315
15316 fail:
15317         /*
15318          * drm_mode_config_cleanup() will free up any
15319          * crtcs/planes already initialized.
15320          */
15321         kfree(crtc_state);
15322         kfree(intel_crtc);
15323
15324         return ret;
15325 }
15326
15327 enum pipe intel_get_pipe_from_connector(struct intel_connector *connector)
15328 {
15329         struct drm_encoder *encoder = connector->base.encoder;
15330         struct drm_device *dev = connector->base.dev;
15331
15332         WARN_ON(!drm_modeset_is_locked(&dev->mode_config.connection_mutex));
15333
15334         if (!encoder || WARN_ON(!encoder->crtc))
15335                 return INVALID_PIPE;
15336
15337         return to_intel_crtc(encoder->crtc)->pipe;
15338 }
15339
15340 int intel_get_pipe_from_crtc_id(struct drm_device *dev, void *data,
15341                                 struct drm_file *file)
15342 {
15343         struct drm_i915_get_pipe_from_crtc_id *pipe_from_crtc_id = data;
15344         struct drm_crtc *drmmode_crtc;
15345         struct intel_crtc *crtc;
15346
15347         drmmode_crtc = drm_crtc_find(dev, pipe_from_crtc_id->crtc_id);
15348         if (!drmmode_crtc)
15349                 return -ENOENT;
15350
15351         crtc = to_intel_crtc(drmmode_crtc);
15352         pipe_from_crtc_id->pipe = crtc->pipe;
15353
15354         return 0;
15355 }
15356
15357 static int intel_encoder_clones(struct intel_encoder *encoder)
15358 {
15359         struct drm_device *dev = encoder->base.dev;
15360         struct intel_encoder *source_encoder;
15361         int index_mask = 0;
15362         int entry = 0;
15363
15364         for_each_intel_encoder(dev, source_encoder) {
15365                 if (encoders_cloneable(encoder, source_encoder))
15366                         index_mask |= (1 << entry);
15367
15368                 entry++;
15369         }
15370
15371         return index_mask;
15372 }
15373
15374 static bool has_edp_a(struct drm_i915_private *dev_priv)
15375 {
15376         if (!IS_MOBILE(dev_priv))
15377                 return false;
15378
15379         if ((I915_READ(DP_A) & DP_DETECTED) == 0)
15380                 return false;
15381
15382         if (IS_GEN5(dev_priv) && (I915_READ(FUSE_STRAP) & ILK_eDP_A_DISABLE))
15383                 return false;
15384
15385         return true;
15386 }
15387
15388 static bool intel_crt_present(struct drm_i915_private *dev_priv)
15389 {
15390         if (INTEL_GEN(dev_priv) >= 9)
15391                 return false;
15392
15393         if (IS_HSW_ULT(dev_priv) || IS_BDW_ULT(dev_priv))
15394                 return false;
15395
15396         if (IS_CHERRYVIEW(dev_priv))
15397                 return false;
15398
15399         if (HAS_PCH_LPT_H(dev_priv) &&
15400             I915_READ(SFUSE_STRAP) & SFUSE_STRAP_CRT_DISABLED)
15401                 return false;
15402
15403         /* DDI E can't be used if DDI A requires 4 lanes */
15404         if (HAS_DDI(dev_priv) && I915_READ(DDI_BUF_CTL(PORT_A)) & DDI_A_4_LANES)
15405                 return false;
15406
15407         if (!dev_priv->vbt.int_crt_support)
15408                 return false;
15409
15410         return true;
15411 }
15412
15413 void intel_pps_unlock_regs_wa(struct drm_i915_private *dev_priv)
15414 {
15415         int pps_num;
15416         int pps_idx;
15417
15418         if (HAS_DDI(dev_priv))
15419                 return;
15420         /*
15421          * This w/a is needed at least on CPT/PPT, but to be sure apply it
15422          * everywhere where registers can be write protected.
15423          */
15424         if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
15425                 pps_num = 2;
15426         else
15427                 pps_num = 1;
15428
15429         for (pps_idx = 0; pps_idx < pps_num; pps_idx++) {
15430                 u32 val = I915_READ(PP_CONTROL(pps_idx));
15431
15432                 val = (val & ~PANEL_UNLOCK_MASK) | PANEL_UNLOCK_REGS;
15433                 I915_WRITE(PP_CONTROL(pps_idx), val);
15434         }
15435 }
15436
15437 static void intel_pps_init(struct drm_i915_private *dev_priv)
15438 {
15439         if (HAS_PCH_SPLIT(dev_priv) || IS_BROXTON(dev_priv))
15440                 dev_priv->pps_mmio_base = PCH_PPS_BASE;
15441         else if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
15442                 dev_priv->pps_mmio_base = VLV_PPS_BASE;
15443         else
15444                 dev_priv->pps_mmio_base = PPS_BASE;
15445
15446         intel_pps_unlock_regs_wa(dev_priv);
15447 }
15448
15449 static void intel_setup_outputs(struct drm_device *dev)
15450 {
15451         struct drm_i915_private *dev_priv = to_i915(dev);
15452         struct intel_encoder *encoder;
15453         bool dpd_is_edp = false;
15454
15455         intel_pps_init(dev_priv);
15456
15457         /*
15458          * intel_edp_init_connector() depends on this completing first, to
15459          * prevent the registeration of both eDP and LVDS and the incorrect
15460          * sharing of the PPS.
15461          */
15462         intel_lvds_init(dev);
15463
15464         if (intel_crt_present(dev_priv))
15465                 intel_crt_init(dev);
15466
15467         if (IS_BROXTON(dev_priv)) {
15468                 /*
15469                  * FIXME: Broxton doesn't support port detection via the
15470                  * DDI_BUF_CTL_A or SFUSE_STRAP registers, find another way to
15471                  * detect the ports.
15472                  */
15473                 intel_ddi_init(dev, PORT_A);
15474                 intel_ddi_init(dev, PORT_B);
15475                 intel_ddi_init(dev, PORT_C);
15476
15477                 intel_dsi_init(dev);
15478         } else if (HAS_DDI(dev_priv)) {
15479                 int found;
15480
15481                 /*
15482                  * Haswell uses DDI functions to detect digital outputs.
15483                  * On SKL pre-D0 the strap isn't connected, so we assume
15484                  * it's there.
15485                  */
15486                 found = I915_READ(DDI_BUF_CTL(PORT_A)) & DDI_INIT_DISPLAY_DETECTED;
15487                 /* WaIgnoreDDIAStrap: skl */
15488                 if (found || IS_SKYLAKE(dev_priv) || IS_KABYLAKE(dev_priv))
15489                         intel_ddi_init(dev, PORT_A);
15490
15491                 /* DDI B, C and D detection is indicated by the SFUSE_STRAP
15492                  * register */
15493                 found = I915_READ(SFUSE_STRAP);
15494
15495                 if (found & SFUSE_STRAP_DDIB_DETECTED)
15496                         intel_ddi_init(dev, PORT_B);
15497                 if (found & SFUSE_STRAP_DDIC_DETECTED)
15498                         intel_ddi_init(dev, PORT_C);
15499                 if (found & SFUSE_STRAP_DDID_DETECTED)
15500                         intel_ddi_init(dev, PORT_D);
15501                 /*
15502                  * On SKL we don't have a way to detect DDI-E so we rely on VBT.
15503                  */
15504                 if ((IS_SKYLAKE(dev_priv) || IS_KABYLAKE(dev_priv)) &&
15505                     (dev_priv->vbt.ddi_port_info[PORT_E].supports_dp ||
15506                      dev_priv->vbt.ddi_port_info[PORT_E].supports_dvi ||
15507                      dev_priv->vbt.ddi_port_info[PORT_E].supports_hdmi))
15508                         intel_ddi_init(dev, PORT_E);
15509
15510         } else if (HAS_PCH_SPLIT(dev_priv)) {
15511                 int found;
15512                 dpd_is_edp = intel_dp_is_edp(dev_priv, PORT_D);
15513
15514                 if (has_edp_a(dev_priv))
15515                         intel_dp_init(dev, DP_A, PORT_A);
15516
15517                 if (I915_READ(PCH_HDMIB) & SDVO_DETECTED) {
15518                         /* PCH SDVOB multiplex with HDMIB */
15519                         found = intel_sdvo_init(dev, PCH_SDVOB, PORT_B);
15520                         if (!found)
15521                                 intel_hdmi_init(dev, PCH_HDMIB, PORT_B);
15522                         if (!found && (I915_READ(PCH_DP_B) & DP_DETECTED))
15523                                 intel_dp_init(dev, PCH_DP_B, PORT_B);
15524                 }
15525
15526                 if (I915_READ(PCH_HDMIC) & SDVO_DETECTED)
15527                         intel_hdmi_init(dev, PCH_HDMIC, PORT_C);
15528
15529                 if (!dpd_is_edp && I915_READ(PCH_HDMID) & SDVO_DETECTED)
15530                         intel_hdmi_init(dev, PCH_HDMID, PORT_D);
15531
15532                 if (I915_READ(PCH_DP_C) & DP_DETECTED)
15533                         intel_dp_init(dev, PCH_DP_C, PORT_C);
15534
15535                 if (I915_READ(PCH_DP_D) & DP_DETECTED)
15536                         intel_dp_init(dev, PCH_DP_D, PORT_D);
15537         } else if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv)) {
15538                 bool has_edp, has_port;
15539
15540                 /*
15541                  * The DP_DETECTED bit is the latched state of the DDC
15542                  * SDA pin at boot. However since eDP doesn't require DDC
15543                  * (no way to plug in a DP->HDMI dongle) the DDC pins for
15544                  * eDP ports may have been muxed to an alternate function.
15545                  * Thus we can't rely on the DP_DETECTED bit alone to detect
15546                  * eDP ports. Consult the VBT as well as DP_DETECTED to
15547                  * detect eDP ports.
15548                  *
15549                  * Sadly the straps seem to be missing sometimes even for HDMI
15550                  * ports (eg. on Voyo V3 - CHT x7-Z8700), so check both strap
15551                  * and VBT for the presence of the port. Additionally we can't
15552                  * trust the port type the VBT declares as we've seen at least
15553                  * HDMI ports that the VBT claim are DP or eDP.
15554                  */
15555                 has_edp = intel_dp_is_edp(dev_priv, PORT_B);
15556                 has_port = intel_bios_is_port_present(dev_priv, PORT_B);
15557                 if (I915_READ(VLV_DP_B) & DP_DETECTED || has_port)
15558                         has_edp &= intel_dp_init(dev, VLV_DP_B, PORT_B);
15559                 if ((I915_READ(VLV_HDMIB) & SDVO_DETECTED || has_port) && !has_edp)
15560                         intel_hdmi_init(dev, VLV_HDMIB, PORT_B);
15561
15562                 has_edp = intel_dp_is_edp(dev_priv, PORT_C);
15563                 has_port = intel_bios_is_port_present(dev_priv, PORT_C);
15564                 if (I915_READ(VLV_DP_C) & DP_DETECTED || has_port)
15565                         has_edp &= intel_dp_init(dev, VLV_DP_C, PORT_C);
15566                 if ((I915_READ(VLV_HDMIC) & SDVO_DETECTED || has_port) && !has_edp)
15567                         intel_hdmi_init(dev, VLV_HDMIC, PORT_C);
15568
15569                 if (IS_CHERRYVIEW(dev_priv)) {
15570                         /*
15571                          * eDP not supported on port D,
15572                          * so no need to worry about it
15573                          */
15574                         has_port = intel_bios_is_port_present(dev_priv, PORT_D);
15575                         if (I915_READ(CHV_DP_D) & DP_DETECTED || has_port)
15576                                 intel_dp_init(dev, CHV_DP_D, PORT_D);
15577                         if (I915_READ(CHV_HDMID) & SDVO_DETECTED || has_port)
15578                                 intel_hdmi_init(dev, CHV_HDMID, PORT_D);
15579                 }
15580
15581                 intel_dsi_init(dev);
15582         } else if (!IS_GEN2(dev_priv) && !IS_PINEVIEW(dev_priv)) {
15583                 bool found = false;
15584
15585                 if (I915_READ(GEN3_SDVOB) & SDVO_DETECTED) {
15586                         DRM_DEBUG_KMS("probing SDVOB\n");
15587                         found = intel_sdvo_init(dev, GEN3_SDVOB, PORT_B);
15588                         if (!found && IS_G4X(dev_priv)) {
15589                                 DRM_DEBUG_KMS("probing HDMI on SDVOB\n");
15590                                 intel_hdmi_init(dev, GEN4_HDMIB, PORT_B);
15591                         }
15592
15593                         if (!found && IS_G4X(dev_priv))
15594                                 intel_dp_init(dev, DP_B, PORT_B);
15595                 }
15596
15597                 /* Before G4X SDVOC doesn't have its own detect register */
15598
15599                 if (I915_READ(GEN3_SDVOB) & SDVO_DETECTED) {
15600                         DRM_DEBUG_KMS("probing SDVOC\n");
15601                         found = intel_sdvo_init(dev, GEN3_SDVOC, PORT_C);
15602                 }
15603
15604                 if (!found && (I915_READ(GEN3_SDVOC) & SDVO_DETECTED)) {
15605
15606                         if (IS_G4X(dev_priv)) {
15607                                 DRM_DEBUG_KMS("probing HDMI on SDVOC\n");
15608                                 intel_hdmi_init(dev, GEN4_HDMIC, PORT_C);
15609                         }
15610                         if (IS_G4X(dev_priv))
15611                                 intel_dp_init(dev, DP_C, PORT_C);
15612                 }
15613
15614                 if (IS_G4X(dev_priv) && (I915_READ(DP_D) & DP_DETECTED))
15615                         intel_dp_init(dev, DP_D, PORT_D);
15616         } else if (IS_GEN2(dev_priv))
15617                 intel_dvo_init(dev);
15618
15619         if (SUPPORTS_TV(dev_priv))
15620                 intel_tv_init(dev);
15621
15622         intel_psr_init(dev);
15623
15624         for_each_intel_encoder(dev, encoder) {
15625                 encoder->base.possible_crtcs = encoder->crtc_mask;
15626                 encoder->base.possible_clones =
15627                         intel_encoder_clones(encoder);
15628         }
15629
15630         intel_init_pch_refclk(dev);
15631
15632         drm_helper_move_panel_connectors_to_head(dev);
15633 }
15634
15635 static void intel_user_framebuffer_destroy(struct drm_framebuffer *fb)
15636 {
15637         struct drm_device *dev = fb->dev;
15638         struct intel_framebuffer *intel_fb = to_intel_framebuffer(fb);
15639
15640         drm_framebuffer_cleanup(fb);
15641         mutex_lock(&dev->struct_mutex);
15642         WARN_ON(!intel_fb->obj->framebuffer_references--);
15643         i915_gem_object_put(intel_fb->obj);
15644         mutex_unlock(&dev->struct_mutex);
15645         kfree(intel_fb);
15646 }
15647
15648 static int intel_user_framebuffer_create_handle(struct drm_framebuffer *fb,
15649                                                 struct drm_file *file,
15650                                                 unsigned int *handle)
15651 {
15652         struct intel_framebuffer *intel_fb = to_intel_framebuffer(fb);
15653         struct drm_i915_gem_object *obj = intel_fb->obj;
15654
15655         if (obj->userptr.mm) {
15656                 DRM_DEBUG("attempting to use a userptr for a framebuffer, denied\n");
15657                 return -EINVAL;
15658         }
15659
15660         return drm_gem_handle_create(file, &obj->base, handle);
15661 }
15662
15663 static int intel_user_framebuffer_dirty(struct drm_framebuffer *fb,
15664                                         struct drm_file *file,
15665                                         unsigned flags, unsigned color,
15666                                         struct drm_clip_rect *clips,
15667                                         unsigned num_clips)
15668 {
15669         struct drm_device *dev = fb->dev;
15670         struct intel_framebuffer *intel_fb = to_intel_framebuffer(fb);
15671         struct drm_i915_gem_object *obj = intel_fb->obj;
15672
15673         mutex_lock(&dev->struct_mutex);
15674         if (obj->pin_display && obj->cache_dirty)
15675                 i915_gem_clflush_object(obj, true);
15676         intel_fb_obj_flush(obj, false, ORIGIN_DIRTYFB);
15677         mutex_unlock(&dev->struct_mutex);
15678
15679         return 0;
15680 }
15681
15682 static const struct drm_framebuffer_funcs intel_fb_funcs = {
15683         .destroy = intel_user_framebuffer_destroy,
15684         .create_handle = intel_user_framebuffer_create_handle,
15685         .dirty = intel_user_framebuffer_dirty,
15686 };
15687
15688 static
15689 u32 intel_fb_pitch_limit(struct drm_i915_private *dev_priv,
15690                          uint64_t fb_modifier, uint32_t pixel_format)
15691 {
15692         u32 gen = INTEL_INFO(dev_priv)->gen;
15693
15694         if (gen >= 9) {
15695                 int cpp = drm_format_plane_cpp(pixel_format, 0);
15696
15697                 /* "The stride in bytes must not exceed the of the size of 8K
15698                  *  pixels and 32K bytes."
15699                  */
15700                 return min(8192 * cpp, 32768);
15701         } else if (gen >= 5 && !IS_VALLEYVIEW(dev_priv) &&
15702                    !IS_CHERRYVIEW(dev_priv)) {
15703                 return 32*1024;
15704         } else if (gen >= 4) {
15705                 if (fb_modifier == I915_FORMAT_MOD_X_TILED)
15706                         return 16*1024;
15707                 else
15708                         return 32*1024;
15709         } else if (gen >= 3) {
15710                 if (fb_modifier == I915_FORMAT_MOD_X_TILED)
15711                         return 8*1024;
15712                 else
15713                         return 16*1024;
15714         } else {
15715                 /* XXX DSPC is limited to 4k tiled */
15716                 return 8*1024;
15717         }
15718 }
15719
15720 static int intel_framebuffer_init(struct drm_device *dev,
15721                                   struct intel_framebuffer *intel_fb,
15722                                   struct drm_mode_fb_cmd2 *mode_cmd,
15723                                   struct drm_i915_gem_object *obj)
15724 {
15725         struct drm_i915_private *dev_priv = to_i915(dev);
15726         unsigned int tiling = i915_gem_object_get_tiling(obj);
15727         int ret;
15728         u32 pitch_limit, stride_alignment;
15729         struct drm_format_name_buf format_name;
15730
15731         WARN_ON(!mutex_is_locked(&dev->struct_mutex));
15732
15733         if (mode_cmd->flags & DRM_MODE_FB_MODIFIERS) {
15734                 /*
15735                  * If there's a fence, enforce that
15736                  * the fb modifier and tiling mode match.
15737                  */
15738                 if (tiling != I915_TILING_NONE &&
15739                     tiling != intel_fb_modifier_to_tiling(mode_cmd->modifier[0])) {
15740                         DRM_DEBUG("tiling_mode doesn't match fb modifier\n");
15741                         return -EINVAL;
15742                 }
15743         } else {
15744                 if (tiling == I915_TILING_X) {
15745                         mode_cmd->modifier[0] = I915_FORMAT_MOD_X_TILED;
15746                 } else if (tiling == I915_TILING_Y) {
15747                         DRM_DEBUG("No Y tiling for legacy addfb\n");
15748                         return -EINVAL;
15749                 }
15750         }
15751
15752         /* Passed in modifier sanity checking. */
15753         switch (mode_cmd->modifier[0]) {
15754         case I915_FORMAT_MOD_Y_TILED:
15755         case I915_FORMAT_MOD_Yf_TILED:
15756                 if (INTEL_GEN(dev_priv) < 9) {
15757                         DRM_DEBUG("Unsupported tiling 0x%llx!\n",
15758                                   mode_cmd->modifier[0]);
15759                         return -EINVAL;
15760                 }
15761         case DRM_FORMAT_MOD_NONE:
15762         case I915_FORMAT_MOD_X_TILED:
15763                 break;
15764         default:
15765                 DRM_DEBUG("Unsupported fb modifier 0x%llx!\n",
15766                           mode_cmd->modifier[0]);
15767                 return -EINVAL;
15768         }
15769
15770         /*
15771          * gen2/3 display engine uses the fence if present,
15772          * so the tiling mode must match the fb modifier exactly.
15773          */
15774         if (INTEL_INFO(dev_priv)->gen < 4 &&
15775             tiling != intel_fb_modifier_to_tiling(mode_cmd->modifier[0])) {
15776                 DRM_DEBUG("tiling_mode must match fb modifier exactly on gen2/3\n");
15777                 return -EINVAL;
15778         }
15779
15780         stride_alignment = intel_fb_stride_alignment(dev_priv,
15781                                                      mode_cmd->modifier[0],
15782                                                      mode_cmd->pixel_format);
15783         if (mode_cmd->pitches[0] & (stride_alignment - 1)) {
15784                 DRM_DEBUG("pitch (%d) must be at least %u byte aligned\n",
15785                           mode_cmd->pitches[0], stride_alignment);
15786                 return -EINVAL;
15787         }
15788
15789         pitch_limit = intel_fb_pitch_limit(dev_priv, mode_cmd->modifier[0],
15790                                            mode_cmd->pixel_format);
15791         if (mode_cmd->pitches[0] > pitch_limit) {
15792                 DRM_DEBUG("%s pitch (%u) must be at less than %d\n",
15793                           mode_cmd->modifier[0] != DRM_FORMAT_MOD_NONE ?
15794                           "tiled" : "linear",
15795                           mode_cmd->pitches[0], pitch_limit);
15796                 return -EINVAL;
15797         }
15798
15799         /*
15800          * If there's a fence, enforce that
15801          * the fb pitch and fence stride match.
15802          */
15803         if (tiling != I915_TILING_NONE &&
15804             mode_cmd->pitches[0] != i915_gem_object_get_stride(obj)) {
15805                 DRM_DEBUG("pitch (%d) must match tiling stride (%d)\n",
15806                           mode_cmd->pitches[0],
15807                           i915_gem_object_get_stride(obj));
15808                 return -EINVAL;
15809         }
15810
15811         /* Reject formats not supported by any plane early. */
15812         switch (mode_cmd->pixel_format) {
15813         case DRM_FORMAT_C8:
15814         case DRM_FORMAT_RGB565:
15815         case DRM_FORMAT_XRGB8888:
15816         case DRM_FORMAT_ARGB8888:
15817                 break;
15818         case DRM_FORMAT_XRGB1555:
15819                 if (INTEL_GEN(dev_priv) > 3) {
15820                         DRM_DEBUG("unsupported pixel format: %s\n",
15821                                   drm_get_format_name(mode_cmd->pixel_format, &format_name));
15822                         return -EINVAL;
15823                 }
15824                 break;
15825         case DRM_FORMAT_ABGR8888:
15826                 if (!IS_VALLEYVIEW(dev_priv) && !IS_CHERRYVIEW(dev_priv) &&
15827                     INTEL_GEN(dev_priv) < 9) {
15828                         DRM_DEBUG("unsupported pixel format: %s\n",
15829                                   drm_get_format_name(mode_cmd->pixel_format, &format_name));
15830                         return -EINVAL;
15831                 }
15832                 break;
15833         case DRM_FORMAT_XBGR8888:
15834         case DRM_FORMAT_XRGB2101010:
15835         case DRM_FORMAT_XBGR2101010:
15836                 if (INTEL_GEN(dev_priv) < 4) {
15837                         DRM_DEBUG("unsupported pixel format: %s\n",
15838                                   drm_get_format_name(mode_cmd->pixel_format, &format_name));
15839                         return -EINVAL;
15840                 }
15841                 break;
15842         case DRM_FORMAT_ABGR2101010:
15843                 if (!IS_VALLEYVIEW(dev_priv) && !IS_CHERRYVIEW(dev_priv)) {
15844                         DRM_DEBUG("unsupported pixel format: %s\n",
15845                                   drm_get_format_name(mode_cmd->pixel_format, &format_name));
15846                         return -EINVAL;
15847                 }
15848                 break;
15849         case DRM_FORMAT_YUYV:
15850         case DRM_FORMAT_UYVY:
15851         case DRM_FORMAT_YVYU:
15852         case DRM_FORMAT_VYUY:
15853                 if (INTEL_GEN(dev_priv) < 5) {
15854                         DRM_DEBUG("unsupported pixel format: %s\n",
15855                                   drm_get_format_name(mode_cmd->pixel_format, &format_name));
15856                         return -EINVAL;
15857                 }
15858                 break;
15859         default:
15860                 DRM_DEBUG("unsupported pixel format: %s\n",
15861                           drm_get_format_name(mode_cmd->pixel_format, &format_name));
15862                 return -EINVAL;
15863         }
15864
15865         /* FIXME need to adjust LINOFF/TILEOFF accordingly. */
15866         if (mode_cmd->offsets[0] != 0)
15867                 return -EINVAL;
15868
15869         drm_helper_mode_fill_fb_struct(&intel_fb->base, mode_cmd);
15870         intel_fb->obj = obj;
15871
15872         ret = intel_fill_fb_info(dev_priv, &intel_fb->base);
15873         if (ret)
15874                 return ret;
15875
15876         ret = drm_framebuffer_init(dev, &intel_fb->base, &intel_fb_funcs);
15877         if (ret) {
15878                 DRM_ERROR("framebuffer init failed %d\n", ret);
15879                 return ret;
15880         }
15881
15882         intel_fb->obj->framebuffer_references++;
15883
15884         return 0;
15885 }
15886
15887 static struct drm_framebuffer *
15888 intel_user_framebuffer_create(struct drm_device *dev,
15889                               struct drm_file *filp,
15890                               const struct drm_mode_fb_cmd2 *user_mode_cmd)
15891 {
15892         struct drm_framebuffer *fb;
15893         struct drm_i915_gem_object *obj;
15894         struct drm_mode_fb_cmd2 mode_cmd = *user_mode_cmd;
15895
15896         obj = i915_gem_object_lookup(filp, mode_cmd.handles[0]);
15897         if (!obj)
15898                 return ERR_PTR(-ENOENT);
15899
15900         fb = intel_framebuffer_create(dev, &mode_cmd, obj);
15901         if (IS_ERR(fb))
15902                 i915_gem_object_put(obj);
15903
15904         return fb;
15905 }
15906
15907 static const struct drm_mode_config_funcs intel_mode_funcs = {
15908         .fb_create = intel_user_framebuffer_create,
15909         .output_poll_changed = intel_fbdev_output_poll_changed,
15910         .atomic_check = intel_atomic_check,
15911         .atomic_commit = intel_atomic_commit,
15912         .atomic_state_alloc = intel_atomic_state_alloc,
15913         .atomic_state_clear = intel_atomic_state_clear,
15914 };
15915
15916 /**
15917  * intel_init_display_hooks - initialize the display modesetting hooks
15918  * @dev_priv: device private
15919  */
15920 void intel_init_display_hooks(struct drm_i915_private *dev_priv)
15921 {
15922         if (INTEL_INFO(dev_priv)->gen >= 9) {
15923                 dev_priv->display.get_pipe_config = haswell_get_pipe_config;
15924                 dev_priv->display.get_initial_plane_config =
15925                         skylake_get_initial_plane_config;
15926                 dev_priv->display.crtc_compute_clock =
15927                         haswell_crtc_compute_clock;
15928                 dev_priv->display.crtc_enable = haswell_crtc_enable;
15929                 dev_priv->display.crtc_disable = haswell_crtc_disable;
15930         } else if (HAS_DDI(dev_priv)) {
15931                 dev_priv->display.get_pipe_config = haswell_get_pipe_config;
15932                 dev_priv->display.get_initial_plane_config =
15933                         ironlake_get_initial_plane_config;
15934                 dev_priv->display.crtc_compute_clock =
15935                         haswell_crtc_compute_clock;
15936                 dev_priv->display.crtc_enable = haswell_crtc_enable;
15937                 dev_priv->display.crtc_disable = haswell_crtc_disable;
15938         } else if (HAS_PCH_SPLIT(dev_priv)) {
15939                 dev_priv->display.get_pipe_config = ironlake_get_pipe_config;
15940                 dev_priv->display.get_initial_plane_config =
15941                         ironlake_get_initial_plane_config;
15942                 dev_priv->display.crtc_compute_clock =
15943                         ironlake_crtc_compute_clock;
15944                 dev_priv->display.crtc_enable = ironlake_crtc_enable;
15945                 dev_priv->display.crtc_disable = ironlake_crtc_disable;
15946         } else if (IS_CHERRYVIEW(dev_priv)) {
15947                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
15948                 dev_priv->display.get_initial_plane_config =
15949                         i9xx_get_initial_plane_config;
15950                 dev_priv->display.crtc_compute_clock = chv_crtc_compute_clock;
15951                 dev_priv->display.crtc_enable = valleyview_crtc_enable;
15952                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
15953         } else if (IS_VALLEYVIEW(dev_priv)) {
15954                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
15955                 dev_priv->display.get_initial_plane_config =
15956                         i9xx_get_initial_plane_config;
15957                 dev_priv->display.crtc_compute_clock = vlv_crtc_compute_clock;
15958                 dev_priv->display.crtc_enable = valleyview_crtc_enable;
15959                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
15960         } else if (IS_G4X(dev_priv)) {
15961                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
15962                 dev_priv->display.get_initial_plane_config =
15963                         i9xx_get_initial_plane_config;
15964                 dev_priv->display.crtc_compute_clock = g4x_crtc_compute_clock;
15965                 dev_priv->display.crtc_enable = i9xx_crtc_enable;
15966                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
15967         } else if (IS_PINEVIEW(dev_priv)) {
15968                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
15969                 dev_priv->display.get_initial_plane_config =
15970                         i9xx_get_initial_plane_config;
15971                 dev_priv->display.crtc_compute_clock = pnv_crtc_compute_clock;
15972                 dev_priv->display.crtc_enable = i9xx_crtc_enable;
15973                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
15974         } else if (!IS_GEN2(dev_priv)) {
15975                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
15976                 dev_priv->display.get_initial_plane_config =
15977                         i9xx_get_initial_plane_config;
15978                 dev_priv->display.crtc_compute_clock = i9xx_crtc_compute_clock;
15979                 dev_priv->display.crtc_enable = i9xx_crtc_enable;
15980                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
15981         } else {
15982                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
15983                 dev_priv->display.get_initial_plane_config =
15984                         i9xx_get_initial_plane_config;
15985                 dev_priv->display.crtc_compute_clock = i8xx_crtc_compute_clock;
15986                 dev_priv->display.crtc_enable = i9xx_crtc_enable;
15987                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
15988         }
15989
15990         /* Returns the core display clock speed */
15991         if (IS_SKYLAKE(dev_priv) || IS_KABYLAKE(dev_priv))
15992                 dev_priv->display.get_display_clock_speed =
15993                         skylake_get_display_clock_speed;
15994         else if (IS_BROXTON(dev_priv))
15995                 dev_priv->display.get_display_clock_speed =
15996                         broxton_get_display_clock_speed;
15997         else if (IS_BROADWELL(dev_priv))
15998                 dev_priv->display.get_display_clock_speed =
15999                         broadwell_get_display_clock_speed;
16000         else if (IS_HASWELL(dev_priv))
16001                 dev_priv->display.get_display_clock_speed =
16002                         haswell_get_display_clock_speed;
16003         else if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
16004                 dev_priv->display.get_display_clock_speed =
16005                         valleyview_get_display_clock_speed;
16006         else if (IS_GEN5(dev_priv))
16007                 dev_priv->display.get_display_clock_speed =
16008                         ilk_get_display_clock_speed;
16009         else if (IS_I945G(dev_priv) || IS_BROADWATER(dev_priv) ||
16010                  IS_GEN6(dev_priv) || IS_IVYBRIDGE(dev_priv))
16011                 dev_priv->display.get_display_clock_speed =
16012                         i945_get_display_clock_speed;
16013         else if (IS_GM45(dev_priv))
16014                 dev_priv->display.get_display_clock_speed =
16015                         gm45_get_display_clock_speed;
16016         else if (IS_CRESTLINE(dev_priv))
16017                 dev_priv->display.get_display_clock_speed =
16018                         i965gm_get_display_clock_speed;
16019         else if (IS_PINEVIEW(dev_priv))
16020                 dev_priv->display.get_display_clock_speed =
16021                         pnv_get_display_clock_speed;
16022         else if (IS_G33(dev_priv) || IS_G4X(dev_priv))
16023                 dev_priv->display.get_display_clock_speed =
16024                         g33_get_display_clock_speed;
16025         else if (IS_I915G(dev_priv))
16026                 dev_priv->display.get_display_clock_speed =
16027                         i915_get_display_clock_speed;
16028         else if (IS_I945GM(dev_priv) || IS_845G(dev_priv))
16029                 dev_priv->display.get_display_clock_speed =
16030                         i9xx_misc_get_display_clock_speed;
16031         else if (IS_I915GM(dev_priv))
16032                 dev_priv->display.get_display_clock_speed =
16033                         i915gm_get_display_clock_speed;
16034         else if (IS_I865G(dev_priv))
16035                 dev_priv->display.get_display_clock_speed =
16036                         i865_get_display_clock_speed;
16037         else if (IS_I85X(dev_priv))
16038                 dev_priv->display.get_display_clock_speed =
16039                         i85x_get_display_clock_speed;
16040         else { /* 830 */
16041                 WARN(!IS_I830(dev_priv), "Unknown platform. Assuming 133 MHz CDCLK\n");
16042                 dev_priv->display.get_display_clock_speed =
16043                         i830_get_display_clock_speed;
16044         }
16045
16046         if (IS_GEN5(dev_priv)) {
16047                 dev_priv->display.fdi_link_train = ironlake_fdi_link_train;
16048         } else if (IS_GEN6(dev_priv)) {
16049                 dev_priv->display.fdi_link_train = gen6_fdi_link_train;
16050         } else if (IS_IVYBRIDGE(dev_priv)) {
16051                 /* FIXME: detect B0+ stepping and use auto training */
16052                 dev_priv->display.fdi_link_train = ivb_manual_fdi_link_train;
16053         } else if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv)) {
16054                 dev_priv->display.fdi_link_train = hsw_fdi_link_train;
16055         }
16056
16057         if (IS_BROADWELL(dev_priv)) {
16058                 dev_priv->display.modeset_commit_cdclk =
16059                         broadwell_modeset_commit_cdclk;
16060                 dev_priv->display.modeset_calc_cdclk =
16061                         broadwell_modeset_calc_cdclk;
16062         } else if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv)) {
16063                 dev_priv->display.modeset_commit_cdclk =
16064                         valleyview_modeset_commit_cdclk;
16065                 dev_priv->display.modeset_calc_cdclk =
16066                         valleyview_modeset_calc_cdclk;
16067         } else if (IS_BROXTON(dev_priv)) {
16068                 dev_priv->display.modeset_commit_cdclk =
16069                         bxt_modeset_commit_cdclk;
16070                 dev_priv->display.modeset_calc_cdclk =
16071                         bxt_modeset_calc_cdclk;
16072         } else if (IS_SKYLAKE(dev_priv) || IS_KABYLAKE(dev_priv)) {
16073                 dev_priv->display.modeset_commit_cdclk =
16074                         skl_modeset_commit_cdclk;
16075                 dev_priv->display.modeset_calc_cdclk =
16076                         skl_modeset_calc_cdclk;
16077         }
16078
16079         if (dev_priv->info.gen >= 9)
16080                 dev_priv->display.update_crtcs = skl_update_crtcs;
16081         else
16082                 dev_priv->display.update_crtcs = intel_update_crtcs;
16083
16084         switch (INTEL_INFO(dev_priv)->gen) {
16085         case 2:
16086                 dev_priv->display.queue_flip = intel_gen2_queue_flip;
16087                 break;
16088
16089         case 3:
16090                 dev_priv->display.queue_flip = intel_gen3_queue_flip;
16091                 break;
16092
16093         case 4:
16094         case 5:
16095                 dev_priv->display.queue_flip = intel_gen4_queue_flip;
16096                 break;
16097
16098         case 6:
16099                 dev_priv->display.queue_flip = intel_gen6_queue_flip;
16100                 break;
16101         case 7:
16102         case 8: /* FIXME(BDW): Check that the gen8 RCS flip works. */
16103                 dev_priv->display.queue_flip = intel_gen7_queue_flip;
16104                 break;
16105         case 9:
16106                 /* Drop through - unsupported since execlist only. */
16107         default:
16108                 /* Default just returns -ENODEV to indicate unsupported */
16109                 dev_priv->display.queue_flip = intel_default_queue_flip;
16110         }
16111 }
16112
16113 /*
16114  * Some BIOSes insist on assuming the GPU's pipe A is enabled at suspend,
16115  * resume, or other times.  This quirk makes sure that's the case for
16116  * affected systems.
16117  */
16118 static void quirk_pipea_force(struct drm_device *dev)
16119 {
16120         struct drm_i915_private *dev_priv = to_i915(dev);
16121
16122         dev_priv->quirks |= QUIRK_PIPEA_FORCE;
16123         DRM_INFO("applying pipe a force quirk\n");
16124 }
16125
16126 static void quirk_pipeb_force(struct drm_device *dev)
16127 {
16128         struct drm_i915_private *dev_priv = to_i915(dev);
16129
16130         dev_priv->quirks |= QUIRK_PIPEB_FORCE;
16131         DRM_INFO("applying pipe b force quirk\n");
16132 }
16133
16134 /*
16135  * Some machines (Lenovo U160) do not work with SSC on LVDS for some reason
16136  */
16137 static void quirk_ssc_force_disable(struct drm_device *dev)
16138 {
16139         struct drm_i915_private *dev_priv = to_i915(dev);
16140         dev_priv->quirks |= QUIRK_LVDS_SSC_DISABLE;
16141         DRM_INFO("applying lvds SSC disable quirk\n");
16142 }
16143
16144 /*
16145  * A machine (e.g. Acer Aspire 5734Z) may need to invert the panel backlight
16146  * brightness value
16147  */
16148 static void quirk_invert_brightness(struct drm_device *dev)
16149 {
16150         struct drm_i915_private *dev_priv = to_i915(dev);
16151         dev_priv->quirks |= QUIRK_INVERT_BRIGHTNESS;
16152         DRM_INFO("applying inverted panel brightness quirk\n");
16153 }
16154
16155 /* Some VBT's incorrectly indicate no backlight is present */
16156 static void quirk_backlight_present(struct drm_device *dev)
16157 {
16158         struct drm_i915_private *dev_priv = to_i915(dev);
16159         dev_priv->quirks |= QUIRK_BACKLIGHT_PRESENT;
16160         DRM_INFO("applying backlight present quirk\n");
16161 }
16162
16163 struct intel_quirk {
16164         int device;
16165         int subsystem_vendor;
16166         int subsystem_device;
16167         void (*hook)(struct drm_device *dev);
16168 };
16169
16170 /* For systems that don't have a meaningful PCI subdevice/subvendor ID */
16171 struct intel_dmi_quirk {
16172         void (*hook)(struct drm_device *dev);
16173         const struct dmi_system_id (*dmi_id_list)[];
16174 };
16175
16176 static int intel_dmi_reverse_brightness(const struct dmi_system_id *id)
16177 {
16178         DRM_INFO("Backlight polarity reversed on %s\n", id->ident);
16179         return 1;
16180 }
16181
16182 static const struct intel_dmi_quirk intel_dmi_quirks[] = {
16183         {
16184                 .dmi_id_list = &(const struct dmi_system_id[]) {
16185                         {
16186                                 .callback = intel_dmi_reverse_brightness,
16187                                 .ident = "NCR Corporation",
16188                                 .matches = {DMI_MATCH(DMI_SYS_VENDOR, "NCR Corporation"),
16189                                             DMI_MATCH(DMI_PRODUCT_NAME, ""),
16190                                 },
16191                         },
16192                         { }  /* terminating entry */
16193                 },
16194                 .hook = quirk_invert_brightness,
16195         },
16196 };
16197
16198 static struct intel_quirk intel_quirks[] = {
16199         /* Toshiba Protege R-205, S-209 needs pipe A force quirk */
16200         { 0x2592, 0x1179, 0x0001, quirk_pipea_force },
16201
16202         /* ThinkPad T60 needs pipe A force quirk (bug #16494) */
16203         { 0x2782, 0x17aa, 0x201a, quirk_pipea_force },
16204
16205         /* 830 needs to leave pipe A & dpll A up */
16206         { 0x3577, PCI_ANY_ID, PCI_ANY_ID, quirk_pipea_force },
16207
16208         /* 830 needs to leave pipe B & dpll B up */
16209         { 0x3577, PCI_ANY_ID, PCI_ANY_ID, quirk_pipeb_force },
16210
16211         /* Lenovo U160 cannot use SSC on LVDS */
16212         { 0x0046, 0x17aa, 0x3920, quirk_ssc_force_disable },
16213
16214         /* Sony Vaio Y cannot use SSC on LVDS */
16215         { 0x0046, 0x104d, 0x9076, quirk_ssc_force_disable },
16216
16217         /* Acer Aspire 5734Z must invert backlight brightness */
16218         { 0x2a42, 0x1025, 0x0459, quirk_invert_brightness },
16219
16220         /* Acer/eMachines G725 */
16221         { 0x2a42, 0x1025, 0x0210, quirk_invert_brightness },
16222
16223         /* Acer/eMachines e725 */
16224         { 0x2a42, 0x1025, 0x0212, quirk_invert_brightness },
16225
16226         /* Acer/Packard Bell NCL20 */
16227         { 0x2a42, 0x1025, 0x034b, quirk_invert_brightness },
16228
16229         /* Acer Aspire 4736Z */
16230         { 0x2a42, 0x1025, 0x0260, quirk_invert_brightness },
16231
16232         /* Acer Aspire 5336 */
16233         { 0x2a42, 0x1025, 0x048a, quirk_invert_brightness },
16234
16235         /* Acer C720 and C720P Chromebooks (Celeron 2955U) have backlights */
16236         { 0x0a06, 0x1025, 0x0a11, quirk_backlight_present },
16237
16238         /* Acer C720 Chromebook (Core i3 4005U) */
16239         { 0x0a16, 0x1025, 0x0a11, quirk_backlight_present },
16240
16241         /* Apple Macbook 2,1 (Core 2 T7400) */
16242         { 0x27a2, 0x8086, 0x7270, quirk_backlight_present },
16243
16244         /* Apple Macbook 4,1 */
16245         { 0x2a02, 0x106b, 0x00a1, quirk_backlight_present },
16246
16247         /* Toshiba CB35 Chromebook (Celeron 2955U) */
16248         { 0x0a06, 0x1179, 0x0a88, quirk_backlight_present },
16249
16250         /* HP Chromebook 14 (Celeron 2955U) */
16251         { 0x0a06, 0x103c, 0x21ed, quirk_backlight_present },
16252
16253         /* Dell Chromebook 11 */
16254         { 0x0a06, 0x1028, 0x0a35, quirk_backlight_present },
16255
16256         /* Dell Chromebook 11 (2015 version) */
16257         { 0x0a16, 0x1028, 0x0a35, quirk_backlight_present },
16258 };
16259
16260 static void intel_init_quirks(struct drm_device *dev)
16261 {
16262         struct pci_dev *d = dev->pdev;
16263         int i;
16264
16265         for (i = 0; i < ARRAY_SIZE(intel_quirks); i++) {
16266                 struct intel_quirk *q = &intel_quirks[i];
16267
16268                 if (d->device == q->device &&
16269                     (d->subsystem_vendor == q->subsystem_vendor ||
16270                      q->subsystem_vendor == PCI_ANY_ID) &&
16271                     (d->subsystem_device == q->subsystem_device ||
16272                      q->subsystem_device == PCI_ANY_ID))
16273                         q->hook(dev);
16274         }
16275         for (i = 0; i < ARRAY_SIZE(intel_dmi_quirks); i++) {
16276                 if (dmi_check_system(*intel_dmi_quirks[i].dmi_id_list) != 0)
16277                         intel_dmi_quirks[i].hook(dev);
16278         }
16279 }
16280
16281 /* Disable the VGA plane that we never use */
16282 static void i915_disable_vga(struct drm_i915_private *dev_priv)
16283 {
16284         struct pci_dev *pdev = dev_priv->drm.pdev;
16285         u8 sr1;
16286         i915_reg_t vga_reg = i915_vgacntrl_reg(dev_priv);
16287
16288         /* WaEnableVGAAccessThroughIOPort:ctg,elk,ilk,snb,ivb,vlv,hsw */
16289         vga_get_uninterruptible(pdev, VGA_RSRC_LEGACY_IO);
16290         outb(SR01, VGA_SR_INDEX);
16291         sr1 = inb(VGA_SR_DATA);
16292         outb(sr1 | 1<<5, VGA_SR_DATA);
16293         vga_put(pdev, VGA_RSRC_LEGACY_IO);
16294         udelay(300);
16295
16296         I915_WRITE(vga_reg, VGA_DISP_DISABLE);
16297         POSTING_READ(vga_reg);
16298 }
16299
16300 void intel_modeset_init_hw(struct drm_device *dev)
16301 {
16302         struct drm_i915_private *dev_priv = to_i915(dev);
16303
16304         intel_update_cdclk(dev_priv);
16305
16306         dev_priv->atomic_cdclk_freq = dev_priv->cdclk_freq;
16307
16308         intel_init_clock_gating(dev_priv);
16309 }
16310
16311 /*
16312  * Calculate what we think the watermarks should be for the state we've read
16313  * out of the hardware and then immediately program those watermarks so that
16314  * we ensure the hardware settings match our internal state.
16315  *
16316  * We can calculate what we think WM's should be by creating a duplicate of the
16317  * current state (which was constructed during hardware readout) and running it
16318  * through the atomic check code to calculate new watermark values in the
16319  * state object.
16320  */
16321 static void sanitize_watermarks(struct drm_device *dev)
16322 {
16323         struct drm_i915_private *dev_priv = to_i915(dev);
16324         struct drm_atomic_state *state;
16325         struct intel_atomic_state *intel_state;
16326         struct drm_crtc *crtc;
16327         struct drm_crtc_state *cstate;
16328         struct drm_modeset_acquire_ctx ctx;
16329         int ret;
16330         int i;
16331
16332         /* Only supported on platforms that use atomic watermark design */
16333         if (!dev_priv->display.optimize_watermarks)
16334                 return;
16335
16336         /*
16337          * We need to hold connection_mutex before calling duplicate_state so
16338          * that the connector loop is protected.
16339          */
16340         drm_modeset_acquire_init(&ctx, 0);
16341 retry:
16342         ret = drm_modeset_lock_all_ctx(dev, &ctx);
16343         if (ret == -EDEADLK) {
16344                 drm_modeset_backoff(&ctx);
16345                 goto retry;
16346         } else if (WARN_ON(ret)) {
16347                 goto fail;
16348         }
16349
16350         state = drm_atomic_helper_duplicate_state(dev, &ctx);
16351         if (WARN_ON(IS_ERR(state)))
16352                 goto fail;
16353
16354         intel_state = to_intel_atomic_state(state);
16355
16356         /*
16357          * Hardware readout is the only time we don't want to calculate
16358          * intermediate watermarks (since we don't trust the current
16359          * watermarks).
16360          */
16361         intel_state->skip_intermediate_wm = true;
16362
16363         ret = intel_atomic_check(dev, state);
16364         if (ret) {
16365                 /*
16366                  * If we fail here, it means that the hardware appears to be
16367                  * programmed in a way that shouldn't be possible, given our
16368                  * understanding of watermark requirements.  This might mean a
16369                  * mistake in the hardware readout code or a mistake in the
16370                  * watermark calculations for a given platform.  Raise a WARN
16371                  * so that this is noticeable.
16372                  *
16373                  * If this actually happens, we'll have to just leave the
16374                  * BIOS-programmed watermarks untouched and hope for the best.
16375                  */
16376                 WARN(true, "Could not determine valid watermarks for inherited state\n");
16377                 goto put_state;
16378         }
16379
16380         /* Write calculated watermark values back */
16381         for_each_crtc_in_state(state, crtc, cstate, i) {
16382                 struct intel_crtc_state *cs = to_intel_crtc_state(cstate);
16383
16384                 cs->wm.need_postvbl_update = true;
16385                 dev_priv->display.optimize_watermarks(intel_state, cs);
16386         }
16387
16388 put_state:
16389         drm_atomic_state_put(state);
16390 fail:
16391         drm_modeset_drop_locks(&ctx);
16392         drm_modeset_acquire_fini(&ctx);
16393 }
16394
16395 int intel_modeset_init(struct drm_device *dev)
16396 {
16397         struct drm_i915_private *dev_priv = to_i915(dev);
16398         struct i915_ggtt *ggtt = &dev_priv->ggtt;
16399         enum pipe pipe;
16400         struct intel_crtc *crtc;
16401
16402         drm_mode_config_init(dev);
16403
16404         dev->mode_config.min_width = 0;
16405         dev->mode_config.min_height = 0;
16406
16407         dev->mode_config.preferred_depth = 24;
16408         dev->mode_config.prefer_shadow = 1;
16409
16410         dev->mode_config.allow_fb_modifiers = true;
16411
16412         dev->mode_config.funcs = &intel_mode_funcs;
16413
16414         intel_init_quirks(dev);
16415
16416         intel_init_pm(dev_priv);
16417
16418         if (INTEL_INFO(dev_priv)->num_pipes == 0)
16419                 return 0;
16420
16421         /*
16422          * There may be no VBT; and if the BIOS enabled SSC we can
16423          * just keep using it to avoid unnecessary flicker.  Whereas if the
16424          * BIOS isn't using it, don't assume it will work even if the VBT
16425          * indicates as much.
16426          */
16427         if (HAS_PCH_IBX(dev_priv) || HAS_PCH_CPT(dev_priv)) {
16428                 bool bios_lvds_use_ssc = !!(I915_READ(PCH_DREF_CONTROL) &
16429                                             DREF_SSC1_ENABLE);
16430
16431                 if (dev_priv->vbt.lvds_use_ssc != bios_lvds_use_ssc) {
16432                         DRM_DEBUG_KMS("SSC %sabled by BIOS, overriding VBT which says %sabled\n",
16433                                      bios_lvds_use_ssc ? "en" : "dis",
16434                                      dev_priv->vbt.lvds_use_ssc ? "en" : "dis");
16435                         dev_priv->vbt.lvds_use_ssc = bios_lvds_use_ssc;
16436                 }
16437         }
16438
16439         if (IS_GEN2(dev_priv)) {
16440                 dev->mode_config.max_width = 2048;
16441                 dev->mode_config.max_height = 2048;
16442         } else if (IS_GEN3(dev_priv)) {
16443                 dev->mode_config.max_width = 4096;
16444                 dev->mode_config.max_height = 4096;
16445         } else {
16446                 dev->mode_config.max_width = 8192;
16447                 dev->mode_config.max_height = 8192;
16448         }
16449
16450         if (IS_845G(dev_priv) || IS_I865G(dev_priv)) {
16451                 dev->mode_config.cursor_width = IS_845G(dev_priv) ? 64 : 512;
16452                 dev->mode_config.cursor_height = 1023;
16453         } else if (IS_GEN2(dev_priv)) {
16454                 dev->mode_config.cursor_width = GEN2_CURSOR_WIDTH;
16455                 dev->mode_config.cursor_height = GEN2_CURSOR_HEIGHT;
16456         } else {
16457                 dev->mode_config.cursor_width = MAX_CURSOR_WIDTH;
16458                 dev->mode_config.cursor_height = MAX_CURSOR_HEIGHT;
16459         }
16460
16461         dev->mode_config.fb_base = ggtt->mappable_base;
16462
16463         DRM_DEBUG_KMS("%d display pipe%s available.\n",
16464                       INTEL_INFO(dev_priv)->num_pipes,
16465                       INTEL_INFO(dev_priv)->num_pipes > 1 ? "s" : "");
16466
16467         for_each_pipe(dev_priv, pipe) {
16468                 int ret;
16469
16470                 ret = intel_crtc_init(dev_priv, pipe);
16471                 if (ret) {
16472                         drm_mode_config_cleanup(dev);
16473                         return ret;
16474                 }
16475         }
16476
16477         intel_update_czclk(dev_priv);
16478         intel_update_cdclk(dev_priv);
16479         dev_priv->atomic_cdclk_freq = dev_priv->cdclk_freq;
16480
16481         intel_shared_dpll_init(dev);
16482
16483         if (dev_priv->max_cdclk_freq == 0)
16484                 intel_update_max_cdclk(dev_priv);
16485
16486         /* Just disable it once at startup */
16487         i915_disable_vga(dev_priv);
16488         intel_setup_outputs(dev);
16489
16490         drm_modeset_lock_all(dev);
16491         intel_modeset_setup_hw_state(dev);
16492         drm_modeset_unlock_all(dev);
16493
16494         for_each_intel_crtc(dev, crtc) {
16495                 struct intel_initial_plane_config plane_config = {};
16496
16497                 if (!crtc->active)
16498                         continue;
16499
16500                 /*
16501                  * Note that reserving the BIOS fb up front prevents us
16502                  * from stuffing other stolen allocations like the ring
16503                  * on top.  This prevents some ugliness at boot time, and
16504                  * can even allow for smooth boot transitions if the BIOS
16505                  * fb is large enough for the active pipe configuration.
16506                  */
16507                 dev_priv->display.get_initial_plane_config(crtc,
16508                                                            &plane_config);
16509
16510                 /*
16511                  * If the fb is shared between multiple heads, we'll
16512                  * just get the first one.
16513                  */
16514                 intel_find_initial_plane_obj(crtc, &plane_config);
16515         }
16516
16517         /*
16518          * Make sure hardware watermarks really match the state we read out.
16519          * Note that we need to do this after reconstructing the BIOS fb's
16520          * since the watermark calculation done here will use pstate->fb.
16521          */
16522         sanitize_watermarks(dev);
16523
16524         return 0;
16525 }
16526
16527 static void intel_enable_pipe_a(struct drm_device *dev)
16528 {
16529         struct intel_connector *connector;
16530         struct drm_connector *crt = NULL;
16531         struct intel_load_detect_pipe load_detect_temp;
16532         struct drm_modeset_acquire_ctx *ctx = dev->mode_config.acquire_ctx;
16533
16534         /* We can't just switch on the pipe A, we need to set things up with a
16535          * proper mode and output configuration. As a gross hack, enable pipe A
16536          * by enabling the load detect pipe once. */
16537         for_each_intel_connector(dev, connector) {
16538                 if (connector->encoder->type == INTEL_OUTPUT_ANALOG) {
16539                         crt = &connector->base;
16540                         break;
16541                 }
16542         }
16543
16544         if (!crt)
16545                 return;
16546
16547         if (intel_get_load_detect_pipe(crt, NULL, &load_detect_temp, ctx))
16548                 intel_release_load_detect_pipe(crt, &load_detect_temp, ctx);
16549 }
16550
16551 static bool
16552 intel_check_plane_mapping(struct intel_crtc *crtc)
16553 {
16554         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
16555         u32 val;
16556
16557         if (INTEL_INFO(dev_priv)->num_pipes == 1)
16558                 return true;
16559
16560         val = I915_READ(DSPCNTR(!crtc->plane));
16561
16562         if ((val & DISPLAY_PLANE_ENABLE) &&
16563             (!!(val & DISPPLANE_SEL_PIPE_MASK) == crtc->pipe))
16564                 return false;
16565
16566         return true;
16567 }
16568
16569 static bool intel_crtc_has_encoders(struct intel_crtc *crtc)
16570 {
16571         struct drm_device *dev = crtc->base.dev;
16572         struct intel_encoder *encoder;
16573
16574         for_each_encoder_on_crtc(dev, &crtc->base, encoder)
16575                 return true;
16576
16577         return false;
16578 }
16579
16580 static struct intel_connector *intel_encoder_find_connector(struct intel_encoder *encoder)
16581 {
16582         struct drm_device *dev = encoder->base.dev;
16583         struct intel_connector *connector;
16584
16585         for_each_connector_on_encoder(dev, &encoder->base, connector)
16586                 return connector;
16587
16588         return NULL;
16589 }
16590
16591 static bool has_pch_trancoder(struct drm_i915_private *dev_priv,
16592                               enum transcoder pch_transcoder)
16593 {
16594         return HAS_PCH_IBX(dev_priv) || HAS_PCH_CPT(dev_priv) ||
16595                 (HAS_PCH_LPT_H(dev_priv) && pch_transcoder == TRANSCODER_A);
16596 }
16597
16598 static void intel_sanitize_crtc(struct intel_crtc *crtc)
16599 {
16600         struct drm_device *dev = crtc->base.dev;
16601         struct drm_i915_private *dev_priv = to_i915(dev);
16602         enum transcoder cpu_transcoder = crtc->config->cpu_transcoder;
16603
16604         /* Clear any frame start delays used for debugging left by the BIOS */
16605         if (!transcoder_is_dsi(cpu_transcoder)) {
16606                 i915_reg_t reg = PIPECONF(cpu_transcoder);
16607
16608                 I915_WRITE(reg,
16609                            I915_READ(reg) & ~PIPECONF_FRAME_START_DELAY_MASK);
16610         }
16611
16612         /* restore vblank interrupts to correct state */
16613         drm_crtc_vblank_reset(&crtc->base);
16614         if (crtc->active) {
16615                 struct intel_plane *plane;
16616
16617                 drm_crtc_vblank_on(&crtc->base);
16618
16619                 /* Disable everything but the primary plane */
16620                 for_each_intel_plane_on_crtc(dev, crtc, plane) {
16621                         if (plane->base.type == DRM_PLANE_TYPE_PRIMARY)
16622                                 continue;
16623
16624                         plane->disable_plane(&plane->base, &crtc->base);
16625                 }
16626         }
16627
16628         /* We need to sanitize the plane -> pipe mapping first because this will
16629          * disable the crtc (and hence change the state) if it is wrong. Note
16630          * that gen4+ has a fixed plane -> pipe mapping.  */
16631         if (INTEL_GEN(dev_priv) < 4 && !intel_check_plane_mapping(crtc)) {
16632                 bool plane;
16633
16634                 DRM_DEBUG_KMS("[CRTC:%d:%s] wrong plane connection detected!\n",
16635                               crtc->base.base.id, crtc->base.name);
16636
16637                 /* Pipe has the wrong plane attached and the plane is active.
16638                  * Temporarily change the plane mapping and disable everything
16639                  * ...  */
16640                 plane = crtc->plane;
16641                 to_intel_plane_state(crtc->base.primary->state)->base.visible = true;
16642                 crtc->plane = !plane;
16643                 intel_crtc_disable_noatomic(&crtc->base);
16644                 crtc->plane = plane;
16645         }
16646
16647         if (dev_priv->quirks & QUIRK_PIPEA_FORCE &&
16648             crtc->pipe == PIPE_A && !crtc->active) {
16649                 /* BIOS forgot to enable pipe A, this mostly happens after
16650                  * resume. Force-enable the pipe to fix this, the update_dpms
16651                  * call below we restore the pipe to the right state, but leave
16652                  * the required bits on. */
16653                 intel_enable_pipe_a(dev);
16654         }
16655
16656         /* Adjust the state of the output pipe according to whether we
16657          * have active connectors/encoders. */
16658         if (crtc->active && !intel_crtc_has_encoders(crtc))
16659                 intel_crtc_disable_noatomic(&crtc->base);
16660
16661         if (crtc->active || HAS_GMCH_DISPLAY(dev_priv)) {
16662                 /*
16663                  * We start out with underrun reporting disabled to avoid races.
16664                  * For correct bookkeeping mark this on active crtcs.
16665                  *
16666                  * Also on gmch platforms we dont have any hardware bits to
16667                  * disable the underrun reporting. Which means we need to start
16668                  * out with underrun reporting disabled also on inactive pipes,
16669                  * since otherwise we'll complain about the garbage we read when
16670                  * e.g. coming up after runtime pm.
16671                  *
16672                  * No protection against concurrent access is required - at
16673                  * worst a fifo underrun happens which also sets this to false.
16674                  */
16675                 crtc->cpu_fifo_underrun_disabled = true;
16676                 /*
16677                  * We track the PCH trancoder underrun reporting state
16678                  * within the crtc. With crtc for pipe A housing the underrun
16679                  * reporting state for PCH transcoder A, crtc for pipe B housing
16680                  * it for PCH transcoder B, etc. LPT-H has only PCH transcoder A,
16681                  * and marking underrun reporting as disabled for the non-existing
16682                  * PCH transcoders B and C would prevent enabling the south
16683                  * error interrupt (see cpt_can_enable_serr_int()).
16684                  */
16685                 if (has_pch_trancoder(dev_priv, (enum transcoder)crtc->pipe))
16686                         crtc->pch_fifo_underrun_disabled = true;
16687         }
16688 }
16689
16690 static void intel_sanitize_encoder(struct intel_encoder *encoder)
16691 {
16692         struct intel_connector *connector;
16693
16694         /* We need to check both for a crtc link (meaning that the
16695          * encoder is active and trying to read from a pipe) and the
16696          * pipe itself being active. */
16697         bool has_active_crtc = encoder->base.crtc &&
16698                 to_intel_crtc(encoder->base.crtc)->active;
16699
16700         connector = intel_encoder_find_connector(encoder);
16701         if (connector && !has_active_crtc) {
16702                 DRM_DEBUG_KMS("[ENCODER:%d:%s] has active connectors but no active pipe!\n",
16703                               encoder->base.base.id,
16704                               encoder->base.name);
16705
16706                 /* Connector is active, but has no active pipe. This is
16707                  * fallout from our resume register restoring. Disable
16708                  * the encoder manually again. */
16709                 if (encoder->base.crtc) {
16710                         struct drm_crtc_state *crtc_state = encoder->base.crtc->state;
16711
16712                         DRM_DEBUG_KMS("[ENCODER:%d:%s] manually disabled\n",
16713                                       encoder->base.base.id,
16714                                       encoder->base.name);
16715                         encoder->disable(encoder, to_intel_crtc_state(crtc_state), connector->base.state);
16716                         if (encoder->post_disable)
16717                                 encoder->post_disable(encoder, to_intel_crtc_state(crtc_state), connector->base.state);
16718                 }
16719                 encoder->base.crtc = NULL;
16720
16721                 /* Inconsistent output/port/pipe state happens presumably due to
16722                  * a bug in one of the get_hw_state functions. Or someplace else
16723                  * in our code, like the register restore mess on resume. Clamp
16724                  * things to off as a safer default. */
16725
16726                 connector->base.dpms = DRM_MODE_DPMS_OFF;
16727                 connector->base.encoder = NULL;
16728         }
16729         /* Enabled encoders without active connectors will be fixed in
16730          * the crtc fixup. */
16731 }
16732
16733 void i915_redisable_vga_power_on(struct drm_i915_private *dev_priv)
16734 {
16735         i915_reg_t vga_reg = i915_vgacntrl_reg(dev_priv);
16736
16737         if (!(I915_READ(vga_reg) & VGA_DISP_DISABLE)) {
16738                 DRM_DEBUG_KMS("Something enabled VGA plane, disabling it\n");
16739                 i915_disable_vga(dev_priv);
16740         }
16741 }
16742
16743 void i915_redisable_vga(struct drm_i915_private *dev_priv)
16744 {
16745         /* This function can be called both from intel_modeset_setup_hw_state or
16746          * at a very early point in our resume sequence, where the power well
16747          * structures are not yet restored. Since this function is at a very
16748          * paranoid "someone might have enabled VGA while we were not looking"
16749          * level, just check if the power well is enabled instead of trying to
16750          * follow the "don't touch the power well if we don't need it" policy
16751          * the rest of the driver uses. */
16752         if (!intel_display_power_get_if_enabled(dev_priv, POWER_DOMAIN_VGA))
16753                 return;
16754
16755         i915_redisable_vga_power_on(dev_priv);
16756
16757         intel_display_power_put(dev_priv, POWER_DOMAIN_VGA);
16758 }
16759
16760 static bool primary_get_hw_state(struct intel_plane *plane)
16761 {
16762         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
16763
16764         return I915_READ(DSPCNTR(plane->plane)) & DISPLAY_PLANE_ENABLE;
16765 }
16766
16767 /* FIXME read out full plane state for all planes */
16768 static void readout_plane_state(struct intel_crtc *crtc)
16769 {
16770         struct drm_plane *primary = crtc->base.primary;
16771         struct intel_plane_state *plane_state =
16772                 to_intel_plane_state(primary->state);
16773
16774         plane_state->base.visible = crtc->active &&
16775                 primary_get_hw_state(to_intel_plane(primary));
16776
16777         if (plane_state->base.visible)
16778                 crtc->base.state->plane_mask |= 1 << drm_plane_index(primary);
16779 }
16780
16781 static void intel_modeset_readout_hw_state(struct drm_device *dev)
16782 {
16783         struct drm_i915_private *dev_priv = to_i915(dev);
16784         enum pipe pipe;
16785         struct intel_crtc *crtc;
16786         struct intel_encoder *encoder;
16787         struct intel_connector *connector;
16788         int i;
16789
16790         dev_priv->active_crtcs = 0;
16791
16792         for_each_intel_crtc(dev, crtc) {
16793                 struct intel_crtc_state *crtc_state = crtc->config;
16794                 int pixclk = 0;
16795
16796                 __drm_atomic_helper_crtc_destroy_state(&crtc_state->base);
16797                 memset(crtc_state, 0, sizeof(*crtc_state));
16798                 crtc_state->base.crtc = &crtc->base;
16799
16800                 crtc_state->base.active = crtc_state->base.enable =
16801                         dev_priv->display.get_pipe_config(crtc, crtc_state);
16802
16803                 crtc->base.enabled = crtc_state->base.enable;
16804                 crtc->active = crtc_state->base.active;
16805
16806                 if (crtc_state->base.active) {
16807                         dev_priv->active_crtcs |= 1 << crtc->pipe;
16808
16809                         if (INTEL_GEN(dev_priv) >= 9 || IS_BROADWELL(dev_priv))
16810                                 pixclk = ilk_pipe_pixel_rate(crtc_state);
16811                         else if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
16812                                 pixclk = crtc_state->base.adjusted_mode.crtc_clock;
16813                         else
16814                                 WARN_ON(dev_priv->display.modeset_calc_cdclk);
16815
16816                         /* pixel rate mustn't exceed 95% of cdclk with IPS on BDW */
16817                         if (IS_BROADWELL(dev_priv) && crtc_state->ips_enabled)
16818                                 pixclk = DIV_ROUND_UP(pixclk * 100, 95);
16819                 }
16820
16821                 dev_priv->min_pixclk[crtc->pipe] = pixclk;
16822
16823                 readout_plane_state(crtc);
16824
16825                 DRM_DEBUG_KMS("[CRTC:%d:%s] hw state readout: %s\n",
16826                               crtc->base.base.id, crtc->base.name,
16827                               enableddisabled(crtc->active));
16828         }
16829
16830         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
16831                 struct intel_shared_dpll *pll = &dev_priv->shared_dplls[i];
16832
16833                 pll->on = pll->funcs.get_hw_state(dev_priv, pll,
16834                                                   &pll->config.hw_state);
16835                 pll->config.crtc_mask = 0;
16836                 for_each_intel_crtc(dev, crtc) {
16837                         if (crtc->active && crtc->config->shared_dpll == pll)
16838                                 pll->config.crtc_mask |= 1 << crtc->pipe;
16839                 }
16840                 pll->active_mask = pll->config.crtc_mask;
16841
16842                 DRM_DEBUG_KMS("%s hw state readout: crtc_mask 0x%08x, on %i\n",
16843                               pll->name, pll->config.crtc_mask, pll->on);
16844         }
16845
16846         for_each_intel_encoder(dev, encoder) {
16847                 pipe = 0;
16848
16849                 if (encoder->get_hw_state(encoder, &pipe)) {
16850                         crtc = intel_get_crtc_for_pipe(dev_priv, pipe);
16851
16852                         encoder->base.crtc = &crtc->base;
16853                         crtc->config->output_types |= 1 << encoder->type;
16854                         encoder->get_config(encoder, crtc->config);
16855                 } else {
16856                         encoder->base.crtc = NULL;
16857                 }
16858
16859                 DRM_DEBUG_KMS("[ENCODER:%d:%s] hw state readout: %s, pipe %c\n",
16860                               encoder->base.base.id, encoder->base.name,
16861                               enableddisabled(encoder->base.crtc),
16862                               pipe_name(pipe));
16863         }
16864
16865         for_each_intel_connector(dev, connector) {
16866                 if (connector->get_hw_state(connector)) {
16867                         connector->base.dpms = DRM_MODE_DPMS_ON;
16868
16869                         encoder = connector->encoder;
16870                         connector->base.encoder = &encoder->base;
16871
16872                         if (encoder->base.crtc &&
16873                             encoder->base.crtc->state->active) {
16874                                 /*
16875                                  * This has to be done during hardware readout
16876                                  * because anything calling .crtc_disable may
16877                                  * rely on the connector_mask being accurate.
16878                                  */
16879                                 encoder->base.crtc->state->connector_mask |=
16880                                         1 << drm_connector_index(&connector->base);
16881                                 encoder->base.crtc->state->encoder_mask |=
16882                                         1 << drm_encoder_index(&encoder->base);
16883                         }
16884
16885                 } else {
16886                         connector->base.dpms = DRM_MODE_DPMS_OFF;
16887                         connector->base.encoder = NULL;
16888                 }
16889                 DRM_DEBUG_KMS("[CONNECTOR:%d:%s] hw state readout: %s\n",
16890                               connector->base.base.id, connector->base.name,
16891                               enableddisabled(connector->base.encoder));
16892         }
16893
16894         for_each_intel_crtc(dev, crtc) {
16895                 crtc->base.hwmode = crtc->config->base.adjusted_mode;
16896
16897                 memset(&crtc->base.mode, 0, sizeof(crtc->base.mode));
16898                 if (crtc->base.state->active) {
16899                         intel_mode_from_pipe_config(&crtc->base.mode, crtc->config);
16900                         intel_mode_from_pipe_config(&crtc->base.state->adjusted_mode, crtc->config);
16901                         WARN_ON(drm_atomic_set_mode_for_crtc(crtc->base.state, &crtc->base.mode));
16902
16903                         /*
16904                          * The initial mode needs to be set in order to keep
16905                          * the atomic core happy. It wants a valid mode if the
16906                          * crtc's enabled, so we do the above call.
16907                          *
16908                          * At this point some state updated by the connectors
16909                          * in their ->detect() callback has not run yet, so
16910                          * no recalculation can be done yet.
16911                          *
16912                          * Even if we could do a recalculation and modeset
16913                          * right now it would cause a double modeset if
16914                          * fbdev or userspace chooses a different initial mode.
16915                          *
16916                          * If that happens, someone indicated they wanted a
16917                          * mode change, which means it's safe to do a full
16918                          * recalculation.
16919                          */
16920                         crtc->base.state->mode.private_flags = I915_MODE_FLAG_INHERITED;
16921
16922                         drm_calc_timestamping_constants(&crtc->base, &crtc->base.hwmode);
16923                         update_scanline_offset(crtc);
16924                 }
16925
16926                 intel_pipe_config_sanity_check(dev_priv, crtc->config);
16927         }
16928 }
16929
16930 /* Scan out the current hw modeset state,
16931  * and sanitizes it to the current state
16932  */
16933 static void
16934 intel_modeset_setup_hw_state(struct drm_device *dev)
16935 {
16936         struct drm_i915_private *dev_priv = to_i915(dev);
16937         enum pipe pipe;
16938         struct intel_crtc *crtc;
16939         struct intel_encoder *encoder;
16940         int i;
16941
16942         intel_modeset_readout_hw_state(dev);
16943
16944         /* HW state is read out, now we need to sanitize this mess. */
16945         for_each_intel_encoder(dev, encoder) {
16946                 intel_sanitize_encoder(encoder);
16947         }
16948
16949         for_each_pipe(dev_priv, pipe) {
16950                 crtc = intel_get_crtc_for_pipe(dev_priv, pipe);
16951
16952                 intel_sanitize_crtc(crtc);
16953                 intel_dump_pipe_config(crtc, crtc->config,
16954                                        "[setup_hw_state]");
16955         }
16956
16957         intel_modeset_update_connector_atomic_state(dev);
16958
16959         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
16960                 struct intel_shared_dpll *pll = &dev_priv->shared_dplls[i];
16961
16962                 if (!pll->on || pll->active_mask)
16963                         continue;
16964
16965                 DRM_DEBUG_KMS("%s enabled but not in use, disabling\n", pll->name);
16966
16967                 pll->funcs.disable(dev_priv, pll);
16968                 pll->on = false;
16969         }
16970
16971         if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
16972                 vlv_wm_get_hw_state(dev);
16973         else if (IS_GEN9(dev_priv))
16974                 skl_wm_get_hw_state(dev);
16975         else if (HAS_PCH_SPLIT(dev_priv))
16976                 ilk_wm_get_hw_state(dev);
16977
16978         for_each_intel_crtc(dev, crtc) {
16979                 unsigned long put_domains;
16980
16981                 put_domains = modeset_get_crtc_power_domains(&crtc->base, crtc->config);
16982                 if (WARN_ON(put_domains))
16983                         modeset_put_power_domains(dev_priv, put_domains);
16984         }
16985         intel_display_set_init_power(dev_priv, false);
16986
16987         intel_fbc_init_pipe_state(dev_priv);
16988 }
16989
16990 void intel_display_resume(struct drm_device *dev)
16991 {
16992         struct drm_i915_private *dev_priv = to_i915(dev);
16993         struct drm_atomic_state *state = dev_priv->modeset_restore_state;
16994         struct drm_modeset_acquire_ctx ctx;
16995         int ret;
16996
16997         dev_priv->modeset_restore_state = NULL;
16998         if (state)
16999                 state->acquire_ctx = &ctx;
17000
17001         /*
17002          * This is a cludge because with real atomic modeset mode_config.mutex
17003          * won't be taken. Unfortunately some probed state like
17004          * audio_codec_enable is still protected by mode_config.mutex, so lock
17005          * it here for now.
17006          */
17007         mutex_lock(&dev->mode_config.mutex);
17008         drm_modeset_acquire_init(&ctx, 0);
17009
17010         while (1) {
17011                 ret = drm_modeset_lock_all_ctx(dev, &ctx);
17012                 if (ret != -EDEADLK)
17013                         break;
17014
17015                 drm_modeset_backoff(&ctx);
17016         }
17017
17018         if (!ret)
17019                 ret = __intel_display_resume(dev, state);
17020
17021         drm_modeset_drop_locks(&ctx);
17022         drm_modeset_acquire_fini(&ctx);
17023         mutex_unlock(&dev->mode_config.mutex);
17024
17025         if (ret)
17026                 DRM_ERROR("Restoring old state failed with %i\n", ret);
17027         drm_atomic_state_put(state);
17028 }
17029
17030 void intel_modeset_gem_init(struct drm_device *dev)
17031 {
17032         struct drm_i915_private *dev_priv = to_i915(dev);
17033         struct drm_crtc *c;
17034         struct drm_i915_gem_object *obj;
17035
17036         intel_init_gt_powersave(dev_priv);
17037
17038         intel_modeset_init_hw(dev);
17039
17040         intel_setup_overlay(dev_priv);
17041
17042         /*
17043          * Make sure any fbs we allocated at startup are properly
17044          * pinned & fenced.  When we do the allocation it's too early
17045          * for this.
17046          */
17047         for_each_crtc(dev, c) {
17048                 struct i915_vma *vma;
17049
17050                 obj = intel_fb_obj(c->primary->fb);
17051                 if (obj == NULL)
17052                         continue;
17053
17054                 mutex_lock(&dev->struct_mutex);
17055                 vma = intel_pin_and_fence_fb_obj(c->primary->fb,
17056                                                  c->primary->state->rotation);
17057                 mutex_unlock(&dev->struct_mutex);
17058                 if (IS_ERR(vma)) {
17059                         DRM_ERROR("failed to pin boot fb on pipe %d\n",
17060                                   to_intel_crtc(c)->pipe);
17061                         drm_framebuffer_unreference(c->primary->fb);
17062                         c->primary->fb = NULL;
17063                         c->primary->crtc = c->primary->state->crtc = NULL;
17064                         update_state_fb(c->primary);
17065                         c->state->plane_mask &= ~(1 << drm_plane_index(c->primary));
17066                 }
17067         }
17068 }
17069
17070 int intel_connector_register(struct drm_connector *connector)
17071 {
17072         struct intel_connector *intel_connector = to_intel_connector(connector);
17073         int ret;
17074
17075         ret = intel_backlight_device_register(intel_connector);
17076         if (ret)
17077                 goto err;
17078
17079         return 0;
17080
17081 err:
17082         return ret;
17083 }
17084
17085 void intel_connector_unregister(struct drm_connector *connector)
17086 {
17087         struct intel_connector *intel_connector = to_intel_connector(connector);
17088
17089         intel_backlight_device_unregister(intel_connector);
17090         intel_panel_destroy_backlight(connector);
17091 }
17092
17093 void intel_modeset_cleanup(struct drm_device *dev)
17094 {
17095         struct drm_i915_private *dev_priv = to_i915(dev);
17096
17097         intel_disable_gt_powersave(dev_priv);
17098
17099         /*
17100          * Interrupts and polling as the first thing to avoid creating havoc.
17101          * Too much stuff here (turning of connectors, ...) would
17102          * experience fancy races otherwise.
17103          */
17104         intel_irq_uninstall(dev_priv);
17105
17106         /*
17107          * Due to the hpd irq storm handling the hotplug work can re-arm the
17108          * poll handlers. Hence disable polling after hpd handling is shut down.
17109          */
17110         drm_kms_helper_poll_fini(dev);
17111
17112         intel_unregister_dsm_handler();
17113
17114         intel_fbc_global_disable(dev_priv);
17115
17116         /* flush any delayed tasks or pending work */
17117         flush_scheduled_work();
17118
17119         drm_mode_config_cleanup(dev);
17120
17121         intel_cleanup_overlay(dev_priv);
17122
17123         intel_cleanup_gt_powersave(dev_priv);
17124
17125         intel_teardown_gmbus(dev);
17126 }
17127
17128 void intel_connector_attach_encoder(struct intel_connector *connector,
17129                                     struct intel_encoder *encoder)
17130 {
17131         connector->encoder = encoder;
17132         drm_mode_connector_attach_encoder(&connector->base,
17133                                           &encoder->base);
17134 }
17135
17136 /*
17137  * set vga decode state - true == enable VGA decode
17138  */
17139 int intel_modeset_vga_set_state(struct drm_i915_private *dev_priv, bool state)
17140 {
17141         unsigned reg = INTEL_GEN(dev_priv) >= 6 ? SNB_GMCH_CTRL : INTEL_GMCH_CTRL;
17142         u16 gmch_ctrl;
17143
17144         if (pci_read_config_word(dev_priv->bridge_dev, reg, &gmch_ctrl)) {
17145                 DRM_ERROR("failed to read control word\n");
17146                 return -EIO;
17147         }
17148
17149         if (!!(gmch_ctrl & INTEL_GMCH_VGA_DISABLE) == !state)
17150                 return 0;
17151
17152         if (state)
17153                 gmch_ctrl &= ~INTEL_GMCH_VGA_DISABLE;
17154         else
17155                 gmch_ctrl |= INTEL_GMCH_VGA_DISABLE;
17156
17157         if (pci_write_config_word(dev_priv->bridge_dev, reg, gmch_ctrl)) {
17158                 DRM_ERROR("failed to write control word\n");
17159                 return -EIO;
17160         }
17161
17162         return 0;
17163 }
17164
17165 #if IS_ENABLED(CONFIG_DRM_I915_CAPTURE_ERROR)
17166
17167 struct intel_display_error_state {
17168
17169         u32 power_well_driver;
17170
17171         int num_transcoders;
17172
17173         struct intel_cursor_error_state {
17174                 u32 control;
17175                 u32 position;
17176                 u32 base;
17177                 u32 size;
17178         } cursor[I915_MAX_PIPES];
17179
17180         struct intel_pipe_error_state {
17181                 bool power_domain_on;
17182                 u32 source;
17183                 u32 stat;
17184         } pipe[I915_MAX_PIPES];
17185
17186         struct intel_plane_error_state {
17187                 u32 control;
17188                 u32 stride;
17189                 u32 size;
17190                 u32 pos;
17191                 u32 addr;
17192                 u32 surface;
17193                 u32 tile_offset;
17194         } plane[I915_MAX_PIPES];
17195
17196         struct intel_transcoder_error_state {
17197                 bool power_domain_on;
17198                 enum transcoder cpu_transcoder;
17199
17200                 u32 conf;
17201
17202                 u32 htotal;
17203                 u32 hblank;
17204                 u32 hsync;
17205                 u32 vtotal;
17206                 u32 vblank;
17207                 u32 vsync;
17208         } transcoder[4];
17209 };
17210
17211 struct intel_display_error_state *
17212 intel_display_capture_error_state(struct drm_i915_private *dev_priv)
17213 {
17214         struct intel_display_error_state *error;
17215         int transcoders[] = {
17216                 TRANSCODER_A,
17217                 TRANSCODER_B,
17218                 TRANSCODER_C,
17219                 TRANSCODER_EDP,
17220         };
17221         int i;
17222
17223         if (INTEL_INFO(dev_priv)->num_pipes == 0)
17224                 return NULL;
17225
17226         error = kzalloc(sizeof(*error), GFP_ATOMIC);
17227         if (error == NULL)
17228                 return NULL;
17229
17230         if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv))
17231                 error->power_well_driver = I915_READ(HSW_PWR_WELL_DRIVER);
17232
17233         for_each_pipe(dev_priv, i) {
17234                 error->pipe[i].power_domain_on =
17235                         __intel_display_power_is_enabled(dev_priv,
17236                                                          POWER_DOMAIN_PIPE(i));
17237                 if (!error->pipe[i].power_domain_on)
17238                         continue;
17239
17240                 error->cursor[i].control = I915_READ(CURCNTR(i));
17241                 error->cursor[i].position = I915_READ(CURPOS(i));
17242                 error->cursor[i].base = I915_READ(CURBASE(i));
17243
17244                 error->plane[i].control = I915_READ(DSPCNTR(i));
17245                 error->plane[i].stride = I915_READ(DSPSTRIDE(i));
17246                 if (INTEL_GEN(dev_priv) <= 3) {
17247                         error->plane[i].size = I915_READ(DSPSIZE(i));
17248                         error->plane[i].pos = I915_READ(DSPPOS(i));
17249                 }
17250                 if (INTEL_GEN(dev_priv) <= 7 && !IS_HASWELL(dev_priv))
17251                         error->plane[i].addr = I915_READ(DSPADDR(i));
17252                 if (INTEL_GEN(dev_priv) >= 4) {
17253                         error->plane[i].surface = I915_READ(DSPSURF(i));
17254                         error->plane[i].tile_offset = I915_READ(DSPTILEOFF(i));
17255                 }
17256
17257                 error->pipe[i].source = I915_READ(PIPESRC(i));
17258
17259                 if (HAS_GMCH_DISPLAY(dev_priv))
17260                         error->pipe[i].stat = I915_READ(PIPESTAT(i));
17261         }
17262
17263         /* Note: this does not include DSI transcoders. */
17264         error->num_transcoders = INTEL_INFO(dev_priv)->num_pipes;
17265         if (HAS_DDI(dev_priv))
17266                 error->num_transcoders++; /* Account for eDP. */
17267
17268         for (i = 0; i < error->num_transcoders; i++) {
17269                 enum transcoder cpu_transcoder = transcoders[i];
17270
17271                 error->transcoder[i].power_domain_on =
17272                         __intel_display_power_is_enabled(dev_priv,
17273                                 POWER_DOMAIN_TRANSCODER(cpu_transcoder));
17274                 if (!error->transcoder[i].power_domain_on)
17275                         continue;
17276
17277                 error->transcoder[i].cpu_transcoder = cpu_transcoder;
17278
17279                 error->transcoder[i].conf = I915_READ(PIPECONF(cpu_transcoder));
17280                 error->transcoder[i].htotal = I915_READ(HTOTAL(cpu_transcoder));
17281                 error->transcoder[i].hblank = I915_READ(HBLANK(cpu_transcoder));
17282                 error->transcoder[i].hsync = I915_READ(HSYNC(cpu_transcoder));
17283                 error->transcoder[i].vtotal = I915_READ(VTOTAL(cpu_transcoder));
17284                 error->transcoder[i].vblank = I915_READ(VBLANK(cpu_transcoder));
17285                 error->transcoder[i].vsync = I915_READ(VSYNC(cpu_transcoder));
17286         }
17287
17288         return error;
17289 }
17290
17291 #define err_printf(e, ...) i915_error_printf(e, __VA_ARGS__)
17292
17293 void
17294 intel_display_print_error_state(struct drm_i915_error_state_buf *m,
17295                                 struct drm_i915_private *dev_priv,
17296                                 struct intel_display_error_state *error)
17297 {
17298         int i;
17299
17300         if (!error)
17301                 return;
17302
17303         err_printf(m, "Num Pipes: %d\n", INTEL_INFO(dev_priv)->num_pipes);
17304         if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv))
17305                 err_printf(m, "PWR_WELL_CTL2: %08x\n",
17306                            error->power_well_driver);
17307         for_each_pipe(dev_priv, i) {
17308                 err_printf(m, "Pipe [%d]:\n", i);
17309                 err_printf(m, "  Power: %s\n",
17310                            onoff(error->pipe[i].power_domain_on));
17311                 err_printf(m, "  SRC: %08x\n", error->pipe[i].source);
17312                 err_printf(m, "  STAT: %08x\n", error->pipe[i].stat);
17313
17314                 err_printf(m, "Plane [%d]:\n", i);
17315                 err_printf(m, "  CNTR: %08x\n", error->plane[i].control);
17316                 err_printf(m, "  STRIDE: %08x\n", error->plane[i].stride);
17317                 if (INTEL_GEN(dev_priv) <= 3) {
17318                         err_printf(m, "  SIZE: %08x\n", error->plane[i].size);
17319                         err_printf(m, "  POS: %08x\n", error->plane[i].pos);
17320                 }
17321                 if (INTEL_GEN(dev_priv) <= 7 && !IS_HASWELL(dev_priv))
17322                         err_printf(m, "  ADDR: %08x\n", error->plane[i].addr);
17323                 if (INTEL_GEN(dev_priv) >= 4) {
17324                         err_printf(m, "  SURF: %08x\n", error->plane[i].surface);
17325                         err_printf(m, "  TILEOFF: %08x\n", error->plane[i].tile_offset);
17326                 }
17327
17328                 err_printf(m, "Cursor [%d]:\n", i);
17329                 err_printf(m, "  CNTR: %08x\n", error->cursor[i].control);
17330                 err_printf(m, "  POS: %08x\n", error->cursor[i].position);
17331                 err_printf(m, "  BASE: %08x\n", error->cursor[i].base);
17332         }
17333
17334         for (i = 0; i < error->num_transcoders; i++) {
17335                 err_printf(m, "CPU transcoder: %s\n",
17336                            transcoder_name(error->transcoder[i].cpu_transcoder));
17337                 err_printf(m, "  Power: %s\n",
17338                            onoff(error->transcoder[i].power_domain_on));
17339                 err_printf(m, "  CONF: %08x\n", error->transcoder[i].conf);
17340                 err_printf(m, "  HTOTAL: %08x\n", error->transcoder[i].htotal);
17341                 err_printf(m, "  HBLANK: %08x\n", error->transcoder[i].hblank);
17342                 err_printf(m, "  HSYNC: %08x\n", error->transcoder[i].hsync);
17343                 err_printf(m, "  VTOTAL: %08x\n", error->transcoder[i].vtotal);
17344                 err_printf(m, "  VBLANK: %08x\n", error->transcoder[i].vblank);
17345                 err_printf(m, "  VSYNC: %08x\n", error->transcoder[i].vsync);
17346         }
17347 }
17348
17349 #endif