GNU Linux-libre 4.9.283-gnu1
[releases.git] / drivers / gpu / drm / i915 / intel_display.c
1 /*
2  * Copyright © 2006-2007 Intel Corporation
3  *
4  * Permission is hereby granted, free of charge, to any person obtaining a
5  * copy of this software and associated documentation files (the "Software"),
6  * to deal in the Software without restriction, including without limitation
7  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
8  * and/or sell copies of the Software, and to permit persons to whom the
9  * Software is furnished to do so, subject to the following conditions:
10  *
11  * The above copyright notice and this permission notice (including the next
12  * paragraph) shall be included in all copies or substantial portions of the
13  * Software.
14  *
15  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
18  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
21  * DEALINGS IN THE SOFTWARE.
22  *
23  * Authors:
24  *      Eric Anholt <eric@anholt.net>
25  */
26
27 #include <linux/dmi.h>
28 #include <linux/module.h>
29 #include <linux/input.h>
30 #include <linux/i2c.h>
31 #include <linux/kernel.h>
32 #include <linux/slab.h>
33 #include <linux/vgaarb.h>
34 #include <drm/drm_edid.h>
35 #include <drm/drmP.h>
36 #include "intel_drv.h"
37 #include "intel_frontbuffer.h"
38 #include <drm/i915_drm.h>
39 #include "i915_drv.h"
40 #include "i915_gem_dmabuf.h"
41 #include "intel_dsi.h"
42 #include "i915_trace.h"
43 #include <drm/drm_atomic.h>
44 #include <drm/drm_atomic_helper.h>
45 #include <drm/drm_dp_helper.h>
46 #include <drm/drm_crtc_helper.h>
47 #include <drm/drm_plane_helper.h>
48 #include <drm/drm_rect.h>
49 #include <linux/dma_remapping.h>
50 #include <linux/reservation.h>
51
52 static bool is_mmio_work(struct intel_flip_work *work)
53 {
54         return work->mmio_work.func;
55 }
56
57 /* Primary plane formats for gen <= 3 */
58 static const uint32_t i8xx_primary_formats[] = {
59         DRM_FORMAT_C8,
60         DRM_FORMAT_RGB565,
61         DRM_FORMAT_XRGB1555,
62         DRM_FORMAT_XRGB8888,
63 };
64
65 /* Primary plane formats for gen >= 4 */
66 static const uint32_t i965_primary_formats[] = {
67         DRM_FORMAT_C8,
68         DRM_FORMAT_RGB565,
69         DRM_FORMAT_XRGB8888,
70         DRM_FORMAT_XBGR8888,
71         DRM_FORMAT_XRGB2101010,
72         DRM_FORMAT_XBGR2101010,
73 };
74
75 static const uint32_t skl_primary_formats[] = {
76         DRM_FORMAT_C8,
77         DRM_FORMAT_RGB565,
78         DRM_FORMAT_XRGB8888,
79         DRM_FORMAT_XBGR8888,
80         DRM_FORMAT_ARGB8888,
81         DRM_FORMAT_ABGR8888,
82         DRM_FORMAT_XRGB2101010,
83         DRM_FORMAT_XBGR2101010,
84         DRM_FORMAT_YUYV,
85         DRM_FORMAT_YVYU,
86         DRM_FORMAT_UYVY,
87         DRM_FORMAT_VYUY,
88 };
89
90 /* Cursor formats */
91 static const uint32_t intel_cursor_formats[] = {
92         DRM_FORMAT_ARGB8888,
93 };
94
95 static void i9xx_crtc_clock_get(struct intel_crtc *crtc,
96                                 struct intel_crtc_state *pipe_config);
97 static void ironlake_pch_clock_get(struct intel_crtc *crtc,
98                                    struct intel_crtc_state *pipe_config);
99
100 static int intel_framebuffer_init(struct drm_device *dev,
101                                   struct intel_framebuffer *ifb,
102                                   struct drm_mode_fb_cmd2 *mode_cmd,
103                                   struct drm_i915_gem_object *obj);
104 static void i9xx_set_pipeconf(struct intel_crtc *intel_crtc);
105 static void intel_set_pipe_timings(struct intel_crtc *intel_crtc);
106 static void intel_set_pipe_src_size(struct intel_crtc *intel_crtc);
107 static void intel_cpu_transcoder_set_m_n(struct intel_crtc *crtc,
108                                          struct intel_link_m_n *m_n,
109                                          struct intel_link_m_n *m2_n2);
110 static void ironlake_set_pipeconf(struct drm_crtc *crtc);
111 static void haswell_set_pipeconf(struct drm_crtc *crtc);
112 static void haswell_set_pipemisc(struct drm_crtc *crtc);
113 static void vlv_prepare_pll(struct intel_crtc *crtc,
114                             const struct intel_crtc_state *pipe_config);
115 static void chv_prepare_pll(struct intel_crtc *crtc,
116                             const struct intel_crtc_state *pipe_config);
117 static void intel_begin_crtc_commit(struct drm_crtc *, struct drm_crtc_state *);
118 static void intel_finish_crtc_commit(struct drm_crtc *, struct drm_crtc_state *);
119 static void skl_init_scalers(struct drm_device *dev, struct intel_crtc *intel_crtc,
120         struct intel_crtc_state *crtc_state);
121 static void skylake_pfit_enable(struct intel_crtc *crtc);
122 static void ironlake_pfit_disable(struct intel_crtc *crtc, bool force);
123 static void ironlake_pfit_enable(struct intel_crtc *crtc);
124 static void intel_modeset_setup_hw_state(struct drm_device *dev);
125 static void intel_pre_disable_primary_noatomic(struct drm_crtc *crtc);
126 static int ilk_max_pixel_rate(struct drm_atomic_state *state);
127 static int bxt_calc_cdclk(int max_pixclk);
128
129 struct intel_limit {
130         struct {
131                 int min, max;
132         } dot, vco, n, m, m1, m2, p, p1;
133
134         struct {
135                 int dot_limit;
136                 int p2_slow, p2_fast;
137         } p2;
138 };
139
140 /* returns HPLL frequency in kHz */
141 static int valleyview_get_vco(struct drm_i915_private *dev_priv)
142 {
143         int hpll_freq, vco_freq[] = { 800, 1600, 2000, 2400 };
144
145         /* Obtain SKU information */
146         mutex_lock(&dev_priv->sb_lock);
147         hpll_freq = vlv_cck_read(dev_priv, CCK_FUSE_REG) &
148                 CCK_FUSE_HPLL_FREQ_MASK;
149         mutex_unlock(&dev_priv->sb_lock);
150
151         return vco_freq[hpll_freq] * 1000;
152 }
153
154 int vlv_get_cck_clock(struct drm_i915_private *dev_priv,
155                       const char *name, u32 reg, int ref_freq)
156 {
157         u32 val;
158         int divider;
159
160         mutex_lock(&dev_priv->sb_lock);
161         val = vlv_cck_read(dev_priv, reg);
162         mutex_unlock(&dev_priv->sb_lock);
163
164         divider = val & CCK_FREQUENCY_VALUES;
165
166         WARN((val & CCK_FREQUENCY_STATUS) !=
167              (divider << CCK_FREQUENCY_STATUS_SHIFT),
168              "%s change in progress\n", name);
169
170         return DIV_ROUND_CLOSEST(ref_freq << 1, divider + 1);
171 }
172
173 static int vlv_get_cck_clock_hpll(struct drm_i915_private *dev_priv,
174                                   const char *name, u32 reg)
175 {
176         if (dev_priv->hpll_freq == 0)
177                 dev_priv->hpll_freq = valleyview_get_vco(dev_priv);
178
179         return vlv_get_cck_clock(dev_priv, name, reg,
180                                  dev_priv->hpll_freq);
181 }
182
183 static int
184 intel_pch_rawclk(struct drm_i915_private *dev_priv)
185 {
186         return (I915_READ(PCH_RAWCLK_FREQ) & RAWCLK_FREQ_MASK) * 1000;
187 }
188
189 static int
190 intel_vlv_hrawclk(struct drm_i915_private *dev_priv)
191 {
192         /* RAWCLK_FREQ_VLV register updated from power well code */
193         return vlv_get_cck_clock_hpll(dev_priv, "hrawclk",
194                                       CCK_DISPLAY_REF_CLOCK_CONTROL);
195 }
196
197 static int
198 intel_g4x_hrawclk(struct drm_i915_private *dev_priv)
199 {
200         uint32_t clkcfg;
201
202         /* hrawclock is 1/4 the FSB frequency */
203         clkcfg = I915_READ(CLKCFG);
204         switch (clkcfg & CLKCFG_FSB_MASK) {
205         case CLKCFG_FSB_400:
206                 return 100000;
207         case CLKCFG_FSB_533:
208                 return 133333;
209         case CLKCFG_FSB_667:
210                 return 166667;
211         case CLKCFG_FSB_800:
212                 return 200000;
213         case CLKCFG_FSB_1067:
214                 return 266667;
215         case CLKCFG_FSB_1333:
216                 return 333333;
217         /* these two are just a guess; one of them might be right */
218         case CLKCFG_FSB_1600:
219         case CLKCFG_FSB_1600_ALT:
220                 return 400000;
221         default:
222                 return 133333;
223         }
224 }
225
226 void intel_update_rawclk(struct drm_i915_private *dev_priv)
227 {
228         if (HAS_PCH_SPLIT(dev_priv))
229                 dev_priv->rawclk_freq = intel_pch_rawclk(dev_priv);
230         else if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
231                 dev_priv->rawclk_freq = intel_vlv_hrawclk(dev_priv);
232         else if (IS_G4X(dev_priv) || IS_PINEVIEW(dev_priv))
233                 dev_priv->rawclk_freq = intel_g4x_hrawclk(dev_priv);
234         else
235                 return; /* no rawclk on other platforms, or no need to know it */
236
237         DRM_DEBUG_DRIVER("rawclk rate: %d kHz\n", dev_priv->rawclk_freq);
238 }
239
240 static void intel_update_czclk(struct drm_i915_private *dev_priv)
241 {
242         if (!(IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv)))
243                 return;
244
245         dev_priv->czclk_freq = vlv_get_cck_clock_hpll(dev_priv, "czclk",
246                                                       CCK_CZ_CLOCK_CONTROL);
247
248         DRM_DEBUG_DRIVER("CZ clock rate: %d kHz\n", dev_priv->czclk_freq);
249 }
250
251 static inline u32 /* units of 100MHz */
252 intel_fdi_link_freq(struct drm_i915_private *dev_priv,
253                     const struct intel_crtc_state *pipe_config)
254 {
255         if (HAS_DDI(dev_priv))
256                 return pipe_config->port_clock; /* SPLL */
257         else if (IS_GEN5(dev_priv))
258                 return ((I915_READ(FDI_PLL_BIOS_0) & FDI_PLL_FB_CLOCK_MASK) + 2) * 10000;
259         else
260                 return 270000;
261 }
262
263 static const struct intel_limit intel_limits_i8xx_dac = {
264         .dot = { .min = 25000, .max = 350000 },
265         .vco = { .min = 908000, .max = 1512000 },
266         .n = { .min = 2, .max = 16 },
267         .m = { .min = 96, .max = 140 },
268         .m1 = { .min = 18, .max = 26 },
269         .m2 = { .min = 6, .max = 16 },
270         .p = { .min = 4, .max = 128 },
271         .p1 = { .min = 2, .max = 33 },
272         .p2 = { .dot_limit = 165000,
273                 .p2_slow = 4, .p2_fast = 2 },
274 };
275
276 static const struct intel_limit intel_limits_i8xx_dvo = {
277         .dot = { .min = 25000, .max = 350000 },
278         .vco = { .min = 908000, .max = 1512000 },
279         .n = { .min = 2, .max = 16 },
280         .m = { .min = 96, .max = 140 },
281         .m1 = { .min = 18, .max = 26 },
282         .m2 = { .min = 6, .max = 16 },
283         .p = { .min = 4, .max = 128 },
284         .p1 = { .min = 2, .max = 33 },
285         .p2 = { .dot_limit = 165000,
286                 .p2_slow = 4, .p2_fast = 4 },
287 };
288
289 static const struct intel_limit intel_limits_i8xx_lvds = {
290         .dot = { .min = 25000, .max = 350000 },
291         .vco = { .min = 908000, .max = 1512000 },
292         .n = { .min = 2, .max = 16 },
293         .m = { .min = 96, .max = 140 },
294         .m1 = { .min = 18, .max = 26 },
295         .m2 = { .min = 6, .max = 16 },
296         .p = { .min = 4, .max = 128 },
297         .p1 = { .min = 1, .max = 6 },
298         .p2 = { .dot_limit = 165000,
299                 .p2_slow = 14, .p2_fast = 7 },
300 };
301
302 static const struct intel_limit intel_limits_i9xx_sdvo = {
303         .dot = { .min = 20000, .max = 400000 },
304         .vco = { .min = 1400000, .max = 2800000 },
305         .n = { .min = 1, .max = 6 },
306         .m = { .min = 70, .max = 120 },
307         .m1 = { .min = 8, .max = 18 },
308         .m2 = { .min = 3, .max = 7 },
309         .p = { .min = 5, .max = 80 },
310         .p1 = { .min = 1, .max = 8 },
311         .p2 = { .dot_limit = 200000,
312                 .p2_slow = 10, .p2_fast = 5 },
313 };
314
315 static const struct intel_limit intel_limits_i9xx_lvds = {
316         .dot = { .min = 20000, .max = 400000 },
317         .vco = { .min = 1400000, .max = 2800000 },
318         .n = { .min = 1, .max = 6 },
319         .m = { .min = 70, .max = 120 },
320         .m1 = { .min = 8, .max = 18 },
321         .m2 = { .min = 3, .max = 7 },
322         .p = { .min = 7, .max = 98 },
323         .p1 = { .min = 1, .max = 8 },
324         .p2 = { .dot_limit = 112000,
325                 .p2_slow = 14, .p2_fast = 7 },
326 };
327
328
329 static const struct intel_limit intel_limits_g4x_sdvo = {
330         .dot = { .min = 25000, .max = 270000 },
331         .vco = { .min = 1750000, .max = 3500000},
332         .n = { .min = 1, .max = 4 },
333         .m = { .min = 104, .max = 138 },
334         .m1 = { .min = 17, .max = 23 },
335         .m2 = { .min = 5, .max = 11 },
336         .p = { .min = 10, .max = 30 },
337         .p1 = { .min = 1, .max = 3},
338         .p2 = { .dot_limit = 270000,
339                 .p2_slow = 10,
340                 .p2_fast = 10
341         },
342 };
343
344 static const struct intel_limit intel_limits_g4x_hdmi = {
345         .dot = { .min = 22000, .max = 400000 },
346         .vco = { .min = 1750000, .max = 3500000},
347         .n = { .min = 1, .max = 4 },
348         .m = { .min = 104, .max = 138 },
349         .m1 = { .min = 16, .max = 23 },
350         .m2 = { .min = 5, .max = 11 },
351         .p = { .min = 5, .max = 80 },
352         .p1 = { .min = 1, .max = 8},
353         .p2 = { .dot_limit = 165000,
354                 .p2_slow = 10, .p2_fast = 5 },
355 };
356
357 static const struct intel_limit intel_limits_g4x_single_channel_lvds = {
358         .dot = { .min = 20000, .max = 115000 },
359         .vco = { .min = 1750000, .max = 3500000 },
360         .n = { .min = 1, .max = 3 },
361         .m = { .min = 104, .max = 138 },
362         .m1 = { .min = 17, .max = 23 },
363         .m2 = { .min = 5, .max = 11 },
364         .p = { .min = 28, .max = 112 },
365         .p1 = { .min = 2, .max = 8 },
366         .p2 = { .dot_limit = 0,
367                 .p2_slow = 14, .p2_fast = 14
368         },
369 };
370
371 static const struct intel_limit intel_limits_g4x_dual_channel_lvds = {
372         .dot = { .min = 80000, .max = 224000 },
373         .vco = { .min = 1750000, .max = 3500000 },
374         .n = { .min = 1, .max = 3 },
375         .m = { .min = 104, .max = 138 },
376         .m1 = { .min = 17, .max = 23 },
377         .m2 = { .min = 5, .max = 11 },
378         .p = { .min = 14, .max = 42 },
379         .p1 = { .min = 2, .max = 6 },
380         .p2 = { .dot_limit = 0,
381                 .p2_slow = 7, .p2_fast = 7
382         },
383 };
384
385 static const struct intel_limit intel_limits_pineview_sdvo = {
386         .dot = { .min = 20000, .max = 400000},
387         .vco = { .min = 1700000, .max = 3500000 },
388         /* Pineview's Ncounter is a ring counter */
389         .n = { .min = 3, .max = 6 },
390         .m = { .min = 2, .max = 256 },
391         /* Pineview only has one combined m divider, which we treat as m2. */
392         .m1 = { .min = 0, .max = 0 },
393         .m2 = { .min = 0, .max = 254 },
394         .p = { .min = 5, .max = 80 },
395         .p1 = { .min = 1, .max = 8 },
396         .p2 = { .dot_limit = 200000,
397                 .p2_slow = 10, .p2_fast = 5 },
398 };
399
400 static const struct intel_limit intel_limits_pineview_lvds = {
401         .dot = { .min = 20000, .max = 400000 },
402         .vco = { .min = 1700000, .max = 3500000 },
403         .n = { .min = 3, .max = 6 },
404         .m = { .min = 2, .max = 256 },
405         .m1 = { .min = 0, .max = 0 },
406         .m2 = { .min = 0, .max = 254 },
407         .p = { .min = 7, .max = 112 },
408         .p1 = { .min = 1, .max = 8 },
409         .p2 = { .dot_limit = 112000,
410                 .p2_slow = 14, .p2_fast = 14 },
411 };
412
413 /* Ironlake / Sandybridge
414  *
415  * We calculate clock using (register_value + 2) for N/M1/M2, so here
416  * the range value for them is (actual_value - 2).
417  */
418 static const struct intel_limit intel_limits_ironlake_dac = {
419         .dot = { .min = 25000, .max = 350000 },
420         .vco = { .min = 1760000, .max = 3510000 },
421         .n = { .min = 1, .max = 5 },
422         .m = { .min = 79, .max = 127 },
423         .m1 = { .min = 12, .max = 22 },
424         .m2 = { .min = 5, .max = 9 },
425         .p = { .min = 5, .max = 80 },
426         .p1 = { .min = 1, .max = 8 },
427         .p2 = { .dot_limit = 225000,
428                 .p2_slow = 10, .p2_fast = 5 },
429 };
430
431 static const struct intel_limit intel_limits_ironlake_single_lvds = {
432         .dot = { .min = 25000, .max = 350000 },
433         .vco = { .min = 1760000, .max = 3510000 },
434         .n = { .min = 1, .max = 3 },
435         .m = { .min = 79, .max = 118 },
436         .m1 = { .min = 12, .max = 22 },
437         .m2 = { .min = 5, .max = 9 },
438         .p = { .min = 28, .max = 112 },
439         .p1 = { .min = 2, .max = 8 },
440         .p2 = { .dot_limit = 225000,
441                 .p2_slow = 14, .p2_fast = 14 },
442 };
443
444 static const struct intel_limit intel_limits_ironlake_dual_lvds = {
445         .dot = { .min = 25000, .max = 350000 },
446         .vco = { .min = 1760000, .max = 3510000 },
447         .n = { .min = 1, .max = 3 },
448         .m = { .min = 79, .max = 127 },
449         .m1 = { .min = 12, .max = 22 },
450         .m2 = { .min = 5, .max = 9 },
451         .p = { .min = 14, .max = 56 },
452         .p1 = { .min = 2, .max = 8 },
453         .p2 = { .dot_limit = 225000,
454                 .p2_slow = 7, .p2_fast = 7 },
455 };
456
457 /* LVDS 100mhz refclk limits. */
458 static const struct intel_limit intel_limits_ironlake_single_lvds_100m = {
459         .dot = { .min = 25000, .max = 350000 },
460         .vco = { .min = 1760000, .max = 3510000 },
461         .n = { .min = 1, .max = 2 },
462         .m = { .min = 79, .max = 126 },
463         .m1 = { .min = 12, .max = 22 },
464         .m2 = { .min = 5, .max = 9 },
465         .p = { .min = 28, .max = 112 },
466         .p1 = { .min = 2, .max = 8 },
467         .p2 = { .dot_limit = 225000,
468                 .p2_slow = 14, .p2_fast = 14 },
469 };
470
471 static const struct intel_limit intel_limits_ironlake_dual_lvds_100m = {
472         .dot = { .min = 25000, .max = 350000 },
473         .vco = { .min = 1760000, .max = 3510000 },
474         .n = { .min = 1, .max = 3 },
475         .m = { .min = 79, .max = 126 },
476         .m1 = { .min = 12, .max = 22 },
477         .m2 = { .min = 5, .max = 9 },
478         .p = { .min = 14, .max = 42 },
479         .p1 = { .min = 2, .max = 6 },
480         .p2 = { .dot_limit = 225000,
481                 .p2_slow = 7, .p2_fast = 7 },
482 };
483
484 static const struct intel_limit intel_limits_vlv = {
485          /*
486           * These are the data rate limits (measured in fast clocks)
487           * since those are the strictest limits we have. The fast
488           * clock and actual rate limits are more relaxed, so checking
489           * them would make no difference.
490           */
491         .dot = { .min = 25000 * 5, .max = 270000 * 5 },
492         .vco = { .min = 4000000, .max = 6000000 },
493         .n = { .min = 1, .max = 7 },
494         .m1 = { .min = 2, .max = 3 },
495         .m2 = { .min = 11, .max = 156 },
496         .p1 = { .min = 2, .max = 3 },
497         .p2 = { .p2_slow = 2, .p2_fast = 20 }, /* slow=min, fast=max */
498 };
499
500 static const struct intel_limit intel_limits_chv = {
501         /*
502          * These are the data rate limits (measured in fast clocks)
503          * since those are the strictest limits we have.  The fast
504          * clock and actual rate limits are more relaxed, so checking
505          * them would make no difference.
506          */
507         .dot = { .min = 25000 * 5, .max = 540000 * 5},
508         .vco = { .min = 4800000, .max = 6480000 },
509         .n = { .min = 1, .max = 1 },
510         .m1 = { .min = 2, .max = 2 },
511         .m2 = { .min = 24 << 22, .max = 175 << 22 },
512         .p1 = { .min = 2, .max = 4 },
513         .p2 = { .p2_slow = 1, .p2_fast = 14 },
514 };
515
516 static const struct intel_limit intel_limits_bxt = {
517         /* FIXME: find real dot limits */
518         .dot = { .min = 0, .max = INT_MAX },
519         .vco = { .min = 4800000, .max = 6700000 },
520         .n = { .min = 1, .max = 1 },
521         .m1 = { .min = 2, .max = 2 },
522         /* FIXME: find real m2 limits */
523         .m2 = { .min = 2 << 22, .max = 255 << 22 },
524         .p1 = { .min = 2, .max = 4 },
525         .p2 = { .p2_slow = 1, .p2_fast = 20 },
526 };
527
528 static bool
529 needs_modeset(struct drm_crtc_state *state)
530 {
531         return drm_atomic_crtc_needs_modeset(state);
532 }
533
534 /*
535  * Platform specific helpers to calculate the port PLL loopback- (clock.m),
536  * and post-divider (clock.p) values, pre- (clock.vco) and post-divided fast
537  * (clock.dot) clock rates. This fast dot clock is fed to the port's IO logic.
538  * The helpers' return value is the rate of the clock that is fed to the
539  * display engine's pipe which can be the above fast dot clock rate or a
540  * divided-down version of it.
541  */
542 /* m1 is reserved as 0 in Pineview, n is a ring counter */
543 static int pnv_calc_dpll_params(int refclk, struct dpll *clock)
544 {
545         clock->m = clock->m2 + 2;
546         clock->p = clock->p1 * clock->p2;
547         if (WARN_ON(clock->n == 0 || clock->p == 0))
548                 return 0;
549         clock->vco = DIV_ROUND_CLOSEST(refclk * clock->m, clock->n);
550         clock->dot = DIV_ROUND_CLOSEST(clock->vco, clock->p);
551
552         return clock->dot;
553 }
554
555 static uint32_t i9xx_dpll_compute_m(struct dpll *dpll)
556 {
557         return 5 * (dpll->m1 + 2) + (dpll->m2 + 2);
558 }
559
560 static int i9xx_calc_dpll_params(int refclk, struct dpll *clock)
561 {
562         clock->m = i9xx_dpll_compute_m(clock);
563         clock->p = clock->p1 * clock->p2;
564         if (WARN_ON(clock->n + 2 == 0 || clock->p == 0))
565                 return 0;
566         clock->vco = DIV_ROUND_CLOSEST(refclk * clock->m, clock->n + 2);
567         clock->dot = DIV_ROUND_CLOSEST(clock->vco, clock->p);
568
569         return clock->dot;
570 }
571
572 static int vlv_calc_dpll_params(int refclk, struct dpll *clock)
573 {
574         clock->m = clock->m1 * clock->m2;
575         clock->p = clock->p1 * clock->p2;
576         if (WARN_ON(clock->n == 0 || clock->p == 0))
577                 return 0;
578         clock->vco = DIV_ROUND_CLOSEST(refclk * clock->m, clock->n);
579         clock->dot = DIV_ROUND_CLOSEST(clock->vco, clock->p);
580
581         return clock->dot / 5;
582 }
583
584 int chv_calc_dpll_params(int refclk, struct dpll *clock)
585 {
586         clock->m = clock->m1 * clock->m2;
587         clock->p = clock->p1 * clock->p2;
588         if (WARN_ON(clock->n == 0 || clock->p == 0))
589                 return 0;
590         clock->vco = DIV_ROUND_CLOSEST_ULL((uint64_t)refclk * clock->m,
591                         clock->n << 22);
592         clock->dot = DIV_ROUND_CLOSEST(clock->vco, clock->p);
593
594         return clock->dot / 5;
595 }
596
597 #define INTELPllInvalid(s)   do { /* DRM_DEBUG(s); */ return false; } while (0)
598 /**
599  * Returns whether the given set of divisors are valid for a given refclk with
600  * the given connectors.
601  */
602
603 static bool intel_PLL_is_valid(struct drm_device *dev,
604                                const struct intel_limit *limit,
605                                const struct dpll *clock)
606 {
607         if (clock->n   < limit->n.min   || limit->n.max   < clock->n)
608                 INTELPllInvalid("n out of range\n");
609         if (clock->p1  < limit->p1.min  || limit->p1.max  < clock->p1)
610                 INTELPllInvalid("p1 out of range\n");
611         if (clock->m2  < limit->m2.min  || limit->m2.max  < clock->m2)
612                 INTELPllInvalid("m2 out of range\n");
613         if (clock->m1  < limit->m1.min  || limit->m1.max  < clock->m1)
614                 INTELPllInvalid("m1 out of range\n");
615
616         if (!IS_PINEVIEW(dev) && !IS_VALLEYVIEW(dev) &&
617             !IS_CHERRYVIEW(dev) && !IS_BROXTON(dev))
618                 if (clock->m1 <= clock->m2)
619                         INTELPllInvalid("m1 <= m2\n");
620
621         if (!IS_VALLEYVIEW(dev) && !IS_CHERRYVIEW(dev) && !IS_BROXTON(dev)) {
622                 if (clock->p < limit->p.min || limit->p.max < clock->p)
623                         INTELPllInvalid("p out of range\n");
624                 if (clock->m < limit->m.min || limit->m.max < clock->m)
625                         INTELPllInvalid("m out of range\n");
626         }
627
628         if (clock->vco < limit->vco.min || limit->vco.max < clock->vco)
629                 INTELPllInvalid("vco out of range\n");
630         /* XXX: We may need to be checking "Dot clock" depending on the multiplier,
631          * connector, etc., rather than just a single range.
632          */
633         if (clock->dot < limit->dot.min || limit->dot.max < clock->dot)
634                 INTELPllInvalid("dot out of range\n");
635
636         return true;
637 }
638
639 static int
640 i9xx_select_p2_div(const struct intel_limit *limit,
641                    const struct intel_crtc_state *crtc_state,
642                    int target)
643 {
644         struct drm_device *dev = crtc_state->base.crtc->dev;
645
646         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
647                 /*
648                  * For LVDS just rely on its current settings for dual-channel.
649                  * We haven't figured out how to reliably set up different
650                  * single/dual channel state, if we even can.
651                  */
652                 if (intel_is_dual_link_lvds(dev))
653                         return limit->p2.p2_fast;
654                 else
655                         return limit->p2.p2_slow;
656         } else {
657                 if (target < limit->p2.dot_limit)
658                         return limit->p2.p2_slow;
659                 else
660                         return limit->p2.p2_fast;
661         }
662 }
663
664 /*
665  * Returns a set of divisors for the desired target clock with the given
666  * refclk, or FALSE.  The returned values represent the clock equation:
667  * reflck * (5 * (m1 + 2) + (m2 + 2)) / (n + 2) / p1 / p2.
668  *
669  * Target and reference clocks are specified in kHz.
670  *
671  * If match_clock is provided, then best_clock P divider must match the P
672  * divider from @match_clock used for LVDS downclocking.
673  */
674 static bool
675 i9xx_find_best_dpll(const struct intel_limit *limit,
676                     struct intel_crtc_state *crtc_state,
677                     int target, int refclk, struct dpll *match_clock,
678                     struct dpll *best_clock)
679 {
680         struct drm_device *dev = crtc_state->base.crtc->dev;
681         struct dpll clock;
682         int err = target;
683
684         memset(best_clock, 0, sizeof(*best_clock));
685
686         clock.p2 = i9xx_select_p2_div(limit, crtc_state, target);
687
688         for (clock.m1 = limit->m1.min; clock.m1 <= limit->m1.max;
689              clock.m1++) {
690                 for (clock.m2 = limit->m2.min;
691                      clock.m2 <= limit->m2.max; clock.m2++) {
692                         if (clock.m2 >= clock.m1)
693                                 break;
694                         for (clock.n = limit->n.min;
695                              clock.n <= limit->n.max; clock.n++) {
696                                 for (clock.p1 = limit->p1.min;
697                                         clock.p1 <= limit->p1.max; clock.p1++) {
698                                         int this_err;
699
700                                         i9xx_calc_dpll_params(refclk, &clock);
701                                         if (!intel_PLL_is_valid(dev, limit,
702                                                                 &clock))
703                                                 continue;
704                                         if (match_clock &&
705                                             clock.p != match_clock->p)
706                                                 continue;
707
708                                         this_err = abs(clock.dot - target);
709                                         if (this_err < err) {
710                                                 *best_clock = clock;
711                                                 err = this_err;
712                                         }
713                                 }
714                         }
715                 }
716         }
717
718         return (err != target);
719 }
720
721 /*
722  * Returns a set of divisors for the desired target clock with the given
723  * refclk, or FALSE.  The returned values represent the clock equation:
724  * reflck * (5 * (m1 + 2) + (m2 + 2)) / (n + 2) / p1 / p2.
725  *
726  * Target and reference clocks are specified in kHz.
727  *
728  * If match_clock is provided, then best_clock P divider must match the P
729  * divider from @match_clock used for LVDS downclocking.
730  */
731 static bool
732 pnv_find_best_dpll(const struct intel_limit *limit,
733                    struct intel_crtc_state *crtc_state,
734                    int target, int refclk, struct dpll *match_clock,
735                    struct dpll *best_clock)
736 {
737         struct drm_device *dev = crtc_state->base.crtc->dev;
738         struct dpll clock;
739         int err = target;
740
741         memset(best_clock, 0, sizeof(*best_clock));
742
743         clock.p2 = i9xx_select_p2_div(limit, crtc_state, target);
744
745         for (clock.m1 = limit->m1.min; clock.m1 <= limit->m1.max;
746              clock.m1++) {
747                 for (clock.m2 = limit->m2.min;
748                      clock.m2 <= limit->m2.max; clock.m2++) {
749                         for (clock.n = limit->n.min;
750                              clock.n <= limit->n.max; clock.n++) {
751                                 for (clock.p1 = limit->p1.min;
752                                         clock.p1 <= limit->p1.max; clock.p1++) {
753                                         int this_err;
754
755                                         pnv_calc_dpll_params(refclk, &clock);
756                                         if (!intel_PLL_is_valid(dev, limit,
757                                                                 &clock))
758                                                 continue;
759                                         if (match_clock &&
760                                             clock.p != match_clock->p)
761                                                 continue;
762
763                                         this_err = abs(clock.dot - target);
764                                         if (this_err < err) {
765                                                 *best_clock = clock;
766                                                 err = this_err;
767                                         }
768                                 }
769                         }
770                 }
771         }
772
773         return (err != target);
774 }
775
776 /*
777  * Returns a set of divisors for the desired target clock with the given
778  * refclk, or FALSE.  The returned values represent the clock equation:
779  * reflck * (5 * (m1 + 2) + (m2 + 2)) / (n + 2) / p1 / p2.
780  *
781  * Target and reference clocks are specified in kHz.
782  *
783  * If match_clock is provided, then best_clock P divider must match the P
784  * divider from @match_clock used for LVDS downclocking.
785  */
786 static bool
787 g4x_find_best_dpll(const struct intel_limit *limit,
788                    struct intel_crtc_state *crtc_state,
789                    int target, int refclk, struct dpll *match_clock,
790                    struct dpll *best_clock)
791 {
792         struct drm_device *dev = crtc_state->base.crtc->dev;
793         struct dpll clock;
794         int max_n;
795         bool found = false;
796         /* approximately equals target * 0.00585 */
797         int err_most = (target >> 8) + (target >> 9);
798
799         memset(best_clock, 0, sizeof(*best_clock));
800
801         clock.p2 = i9xx_select_p2_div(limit, crtc_state, target);
802
803         max_n = limit->n.max;
804         /* based on hardware requirement, prefer smaller n to precision */
805         for (clock.n = limit->n.min; clock.n <= max_n; clock.n++) {
806                 /* based on hardware requirement, prefere larger m1,m2 */
807                 for (clock.m1 = limit->m1.max;
808                      clock.m1 >= limit->m1.min; clock.m1--) {
809                         for (clock.m2 = limit->m2.max;
810                              clock.m2 >= limit->m2.min; clock.m2--) {
811                                 for (clock.p1 = limit->p1.max;
812                                      clock.p1 >= limit->p1.min; clock.p1--) {
813                                         int this_err;
814
815                                         i9xx_calc_dpll_params(refclk, &clock);
816                                         if (!intel_PLL_is_valid(dev, limit,
817                                                                 &clock))
818                                                 continue;
819
820                                         this_err = abs(clock.dot - target);
821                                         if (this_err < err_most) {
822                                                 *best_clock = clock;
823                                                 err_most = this_err;
824                                                 max_n = clock.n;
825                                                 found = true;
826                                         }
827                                 }
828                         }
829                 }
830         }
831         return found;
832 }
833
834 /*
835  * Check if the calculated PLL configuration is more optimal compared to the
836  * best configuration and error found so far. Return the calculated error.
837  */
838 static bool vlv_PLL_is_optimal(struct drm_device *dev, int target_freq,
839                                const struct dpll *calculated_clock,
840                                const struct dpll *best_clock,
841                                unsigned int best_error_ppm,
842                                unsigned int *error_ppm)
843 {
844         /*
845          * For CHV ignore the error and consider only the P value.
846          * Prefer a bigger P value based on HW requirements.
847          */
848         if (IS_CHERRYVIEW(dev)) {
849                 *error_ppm = 0;
850
851                 return calculated_clock->p > best_clock->p;
852         }
853
854         if (WARN_ON_ONCE(!target_freq))
855                 return false;
856
857         *error_ppm = div_u64(1000000ULL *
858                                 abs(target_freq - calculated_clock->dot),
859                              target_freq);
860         /*
861          * Prefer a better P value over a better (smaller) error if the error
862          * is small. Ensure this preference for future configurations too by
863          * setting the error to 0.
864          */
865         if (*error_ppm < 100 && calculated_clock->p > best_clock->p) {
866                 *error_ppm = 0;
867
868                 return true;
869         }
870
871         return *error_ppm + 10 < best_error_ppm;
872 }
873
874 /*
875  * Returns a set of divisors for the desired target clock with the given
876  * refclk, or FALSE.  The returned values represent the clock equation:
877  * reflck * (5 * (m1 + 2) + (m2 + 2)) / (n + 2) / p1 / p2.
878  */
879 static bool
880 vlv_find_best_dpll(const struct intel_limit *limit,
881                    struct intel_crtc_state *crtc_state,
882                    int target, int refclk, struct dpll *match_clock,
883                    struct dpll *best_clock)
884 {
885         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
886         struct drm_device *dev = crtc->base.dev;
887         struct dpll clock;
888         unsigned int bestppm = 1000000;
889         /* min update 19.2 MHz */
890         int max_n = min(limit->n.max, refclk / 19200);
891         bool found = false;
892
893         target *= 5; /* fast clock */
894
895         memset(best_clock, 0, sizeof(*best_clock));
896
897         /* based on hardware requirement, prefer smaller n to precision */
898         for (clock.n = limit->n.min; clock.n <= max_n; clock.n++) {
899                 for (clock.p1 = limit->p1.max; clock.p1 >= limit->p1.min; clock.p1--) {
900                         for (clock.p2 = limit->p2.p2_fast; clock.p2 >= limit->p2.p2_slow;
901                              clock.p2 -= clock.p2 > 10 ? 2 : 1) {
902                                 clock.p = clock.p1 * clock.p2;
903                                 /* based on hardware requirement, prefer bigger m1,m2 values */
904                                 for (clock.m1 = limit->m1.min; clock.m1 <= limit->m1.max; clock.m1++) {
905                                         unsigned int ppm;
906
907                                         clock.m2 = DIV_ROUND_CLOSEST(target * clock.p * clock.n,
908                                                                      refclk * clock.m1);
909
910                                         vlv_calc_dpll_params(refclk, &clock);
911
912                                         if (!intel_PLL_is_valid(dev, limit,
913                                                                 &clock))
914                                                 continue;
915
916                                         if (!vlv_PLL_is_optimal(dev, target,
917                                                                 &clock,
918                                                                 best_clock,
919                                                                 bestppm, &ppm))
920                                                 continue;
921
922                                         *best_clock = clock;
923                                         bestppm = ppm;
924                                         found = true;
925                                 }
926                         }
927                 }
928         }
929
930         return found;
931 }
932
933 /*
934  * Returns a set of divisors for the desired target clock with the given
935  * refclk, or FALSE.  The returned values represent the clock equation:
936  * reflck * (5 * (m1 + 2) + (m2 + 2)) / (n + 2) / p1 / p2.
937  */
938 static bool
939 chv_find_best_dpll(const struct intel_limit *limit,
940                    struct intel_crtc_state *crtc_state,
941                    int target, int refclk, struct dpll *match_clock,
942                    struct dpll *best_clock)
943 {
944         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
945         struct drm_device *dev = crtc->base.dev;
946         unsigned int best_error_ppm;
947         struct dpll clock;
948         uint64_t m2;
949         int found = false;
950
951         memset(best_clock, 0, sizeof(*best_clock));
952         best_error_ppm = 1000000;
953
954         /*
955          * Based on hardware doc, the n always set to 1, and m1 always
956          * set to 2.  If requires to support 200Mhz refclk, we need to
957          * revisit this because n may not 1 anymore.
958          */
959         clock.n = 1, clock.m1 = 2;
960         target *= 5;    /* fast clock */
961
962         for (clock.p1 = limit->p1.max; clock.p1 >= limit->p1.min; clock.p1--) {
963                 for (clock.p2 = limit->p2.p2_fast;
964                                 clock.p2 >= limit->p2.p2_slow;
965                                 clock.p2 -= clock.p2 > 10 ? 2 : 1) {
966                         unsigned int error_ppm;
967
968                         clock.p = clock.p1 * clock.p2;
969
970                         m2 = DIV_ROUND_CLOSEST_ULL(((uint64_t)target * clock.p *
971                                         clock.n) << 22, refclk * clock.m1);
972
973                         if (m2 > INT_MAX/clock.m1)
974                                 continue;
975
976                         clock.m2 = m2;
977
978                         chv_calc_dpll_params(refclk, &clock);
979
980                         if (!intel_PLL_is_valid(dev, limit, &clock))
981                                 continue;
982
983                         if (!vlv_PLL_is_optimal(dev, target, &clock, best_clock,
984                                                 best_error_ppm, &error_ppm))
985                                 continue;
986
987                         *best_clock = clock;
988                         best_error_ppm = error_ppm;
989                         found = true;
990                 }
991         }
992
993         return found;
994 }
995
996 bool bxt_find_best_dpll(struct intel_crtc_state *crtc_state, int target_clock,
997                         struct dpll *best_clock)
998 {
999         int refclk = 100000;
1000         const struct intel_limit *limit = &intel_limits_bxt;
1001
1002         return chv_find_best_dpll(limit, crtc_state,
1003                                   target_clock, refclk, NULL, best_clock);
1004 }
1005
1006 bool intel_crtc_active(struct drm_crtc *crtc)
1007 {
1008         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
1009
1010         /* Be paranoid as we can arrive here with only partial
1011          * state retrieved from the hardware during setup.
1012          *
1013          * We can ditch the adjusted_mode.crtc_clock check as soon
1014          * as Haswell has gained clock readout/fastboot support.
1015          *
1016          * We can ditch the crtc->primary->fb check as soon as we can
1017          * properly reconstruct framebuffers.
1018          *
1019          * FIXME: The intel_crtc->active here should be switched to
1020          * crtc->state->active once we have proper CRTC states wired up
1021          * for atomic.
1022          */
1023         return intel_crtc->active && crtc->primary->state->fb &&
1024                 intel_crtc->config->base.adjusted_mode.crtc_clock;
1025 }
1026
1027 enum transcoder intel_pipe_to_cpu_transcoder(struct drm_i915_private *dev_priv,
1028                                              enum pipe pipe)
1029 {
1030         struct drm_crtc *crtc = dev_priv->pipe_to_crtc_mapping[pipe];
1031         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
1032
1033         return intel_crtc->config->cpu_transcoder;
1034 }
1035
1036 static bool pipe_dsl_stopped(struct drm_device *dev, enum pipe pipe)
1037 {
1038         struct drm_i915_private *dev_priv = to_i915(dev);
1039         i915_reg_t reg = PIPEDSL(pipe);
1040         u32 line1, line2;
1041         u32 line_mask;
1042
1043         if (IS_GEN2(dev))
1044                 line_mask = DSL_LINEMASK_GEN2;
1045         else
1046                 line_mask = DSL_LINEMASK_GEN3;
1047
1048         line1 = I915_READ(reg) & line_mask;
1049         msleep(5);
1050         line2 = I915_READ(reg) & line_mask;
1051
1052         return line1 == line2;
1053 }
1054
1055 /*
1056  * intel_wait_for_pipe_off - wait for pipe to turn off
1057  * @crtc: crtc whose pipe to wait for
1058  *
1059  * After disabling a pipe, we can't wait for vblank in the usual way,
1060  * spinning on the vblank interrupt status bit, since we won't actually
1061  * see an interrupt when the pipe is disabled.
1062  *
1063  * On Gen4 and above:
1064  *   wait for the pipe register state bit to turn off
1065  *
1066  * Otherwise:
1067  *   wait for the display line value to settle (it usually
1068  *   ends up stopping at the start of the next frame).
1069  *
1070  */
1071 static void intel_wait_for_pipe_off(struct intel_crtc *crtc)
1072 {
1073         struct drm_device *dev = crtc->base.dev;
1074         struct drm_i915_private *dev_priv = to_i915(dev);
1075         enum transcoder cpu_transcoder = crtc->config->cpu_transcoder;
1076         enum pipe pipe = crtc->pipe;
1077
1078         if (INTEL_INFO(dev)->gen >= 4) {
1079                 i915_reg_t reg = PIPECONF(cpu_transcoder);
1080
1081                 /* Wait for the Pipe State to go off */
1082                 if (intel_wait_for_register(dev_priv,
1083                                             reg, I965_PIPECONF_ACTIVE, 0,
1084                                             100))
1085                         WARN(1, "pipe_off wait timed out\n");
1086         } else {
1087                 /* Wait for the display line to settle */
1088                 if (wait_for(pipe_dsl_stopped(dev, pipe), 100))
1089                         WARN(1, "pipe_off wait timed out\n");
1090         }
1091 }
1092
1093 /* Only for pre-ILK configs */
1094 void assert_pll(struct drm_i915_private *dev_priv,
1095                 enum pipe pipe, bool state)
1096 {
1097         u32 val;
1098         bool cur_state;
1099
1100         val = I915_READ(DPLL(pipe));
1101         cur_state = !!(val & DPLL_VCO_ENABLE);
1102         I915_STATE_WARN(cur_state != state,
1103              "PLL state assertion failure (expected %s, current %s)\n",
1104                         onoff(state), onoff(cur_state));
1105 }
1106
1107 /* XXX: the dsi pll is shared between MIPI DSI ports */
1108 void assert_dsi_pll(struct drm_i915_private *dev_priv, bool state)
1109 {
1110         u32 val;
1111         bool cur_state;
1112
1113         mutex_lock(&dev_priv->sb_lock);
1114         val = vlv_cck_read(dev_priv, CCK_REG_DSI_PLL_CONTROL);
1115         mutex_unlock(&dev_priv->sb_lock);
1116
1117         cur_state = val & DSI_PLL_VCO_EN;
1118         I915_STATE_WARN(cur_state != state,
1119              "DSI PLL state assertion failure (expected %s, current %s)\n",
1120                         onoff(state), onoff(cur_state));
1121 }
1122
1123 static void assert_fdi_tx(struct drm_i915_private *dev_priv,
1124                           enum pipe pipe, bool state)
1125 {
1126         bool cur_state;
1127         enum transcoder cpu_transcoder = intel_pipe_to_cpu_transcoder(dev_priv,
1128                                                                       pipe);
1129
1130         if (HAS_DDI(dev_priv)) {
1131                 /* DDI does not have a specific FDI_TX register */
1132                 u32 val = I915_READ(TRANS_DDI_FUNC_CTL(cpu_transcoder));
1133                 cur_state = !!(val & TRANS_DDI_FUNC_ENABLE);
1134         } else {
1135                 u32 val = I915_READ(FDI_TX_CTL(pipe));
1136                 cur_state = !!(val & FDI_TX_ENABLE);
1137         }
1138         I915_STATE_WARN(cur_state != state,
1139              "FDI TX state assertion failure (expected %s, current %s)\n",
1140                         onoff(state), onoff(cur_state));
1141 }
1142 #define assert_fdi_tx_enabled(d, p) assert_fdi_tx(d, p, true)
1143 #define assert_fdi_tx_disabled(d, p) assert_fdi_tx(d, p, false)
1144
1145 static void assert_fdi_rx(struct drm_i915_private *dev_priv,
1146                           enum pipe pipe, bool state)
1147 {
1148         u32 val;
1149         bool cur_state;
1150
1151         val = I915_READ(FDI_RX_CTL(pipe));
1152         cur_state = !!(val & FDI_RX_ENABLE);
1153         I915_STATE_WARN(cur_state != state,
1154              "FDI RX state assertion failure (expected %s, current %s)\n",
1155                         onoff(state), onoff(cur_state));
1156 }
1157 #define assert_fdi_rx_enabled(d, p) assert_fdi_rx(d, p, true)
1158 #define assert_fdi_rx_disabled(d, p) assert_fdi_rx(d, p, false)
1159
1160 static void assert_fdi_tx_pll_enabled(struct drm_i915_private *dev_priv,
1161                                       enum pipe pipe)
1162 {
1163         u32 val;
1164
1165         /* ILK FDI PLL is always enabled */
1166         if (IS_GEN5(dev_priv))
1167                 return;
1168
1169         /* On Haswell, DDI ports are responsible for the FDI PLL setup */
1170         if (HAS_DDI(dev_priv))
1171                 return;
1172
1173         val = I915_READ(FDI_TX_CTL(pipe));
1174         I915_STATE_WARN(!(val & FDI_TX_PLL_ENABLE), "FDI TX PLL assertion failure, should be active but is disabled\n");
1175 }
1176
1177 void assert_fdi_rx_pll(struct drm_i915_private *dev_priv,
1178                        enum pipe pipe, bool state)
1179 {
1180         u32 val;
1181         bool cur_state;
1182
1183         val = I915_READ(FDI_RX_CTL(pipe));
1184         cur_state = !!(val & FDI_RX_PLL_ENABLE);
1185         I915_STATE_WARN(cur_state != state,
1186              "FDI RX PLL assertion failure (expected %s, current %s)\n",
1187                         onoff(state), onoff(cur_state));
1188 }
1189
1190 void assert_panel_unlocked(struct drm_i915_private *dev_priv,
1191                            enum pipe pipe)
1192 {
1193         struct drm_device *dev = &dev_priv->drm;
1194         i915_reg_t pp_reg;
1195         u32 val;
1196         enum pipe panel_pipe = PIPE_A;
1197         bool locked = true;
1198
1199         if (WARN_ON(HAS_DDI(dev)))
1200                 return;
1201
1202         if (HAS_PCH_SPLIT(dev)) {
1203                 u32 port_sel;
1204
1205                 pp_reg = PP_CONTROL(0);
1206                 port_sel = I915_READ(PP_ON_DELAYS(0)) & PANEL_PORT_SELECT_MASK;
1207
1208                 if (port_sel == PANEL_PORT_SELECT_LVDS &&
1209                     I915_READ(PCH_LVDS) & LVDS_PIPEB_SELECT)
1210                         panel_pipe = PIPE_B;
1211                 /* XXX: else fix for eDP */
1212         } else if (IS_VALLEYVIEW(dev) || IS_CHERRYVIEW(dev)) {
1213                 /* presumably write lock depends on pipe, not port select */
1214                 pp_reg = PP_CONTROL(pipe);
1215                 panel_pipe = pipe;
1216         } else {
1217                 pp_reg = PP_CONTROL(0);
1218                 if (I915_READ(LVDS) & LVDS_PIPEB_SELECT)
1219                         panel_pipe = PIPE_B;
1220         }
1221
1222         val = I915_READ(pp_reg);
1223         if (!(val & PANEL_POWER_ON) ||
1224             ((val & PANEL_UNLOCK_MASK) == PANEL_UNLOCK_REGS))
1225                 locked = false;
1226
1227         I915_STATE_WARN(panel_pipe == pipe && locked,
1228              "panel assertion failure, pipe %c regs locked\n",
1229              pipe_name(pipe));
1230 }
1231
1232 static void assert_cursor(struct drm_i915_private *dev_priv,
1233                           enum pipe pipe, bool state)
1234 {
1235         struct drm_device *dev = &dev_priv->drm;
1236         bool cur_state;
1237
1238         if (IS_845G(dev) || IS_I865G(dev))
1239                 cur_state = I915_READ(CURCNTR(PIPE_A)) & CURSOR_ENABLE;
1240         else
1241                 cur_state = I915_READ(CURCNTR(pipe)) & CURSOR_MODE;
1242
1243         I915_STATE_WARN(cur_state != state,
1244              "cursor on pipe %c assertion failure (expected %s, current %s)\n",
1245                         pipe_name(pipe), onoff(state), onoff(cur_state));
1246 }
1247 #define assert_cursor_enabled(d, p) assert_cursor(d, p, true)
1248 #define assert_cursor_disabled(d, p) assert_cursor(d, p, false)
1249
1250 void assert_pipe(struct drm_i915_private *dev_priv,
1251                  enum pipe pipe, bool state)
1252 {
1253         bool cur_state;
1254         enum transcoder cpu_transcoder = intel_pipe_to_cpu_transcoder(dev_priv,
1255                                                                       pipe);
1256         enum intel_display_power_domain power_domain;
1257
1258         /* if we need the pipe quirk it must be always on */
1259         if ((pipe == PIPE_A && dev_priv->quirks & QUIRK_PIPEA_FORCE) ||
1260             (pipe == PIPE_B && dev_priv->quirks & QUIRK_PIPEB_FORCE))
1261                 state = true;
1262
1263         power_domain = POWER_DOMAIN_TRANSCODER(cpu_transcoder);
1264         if (intel_display_power_get_if_enabled(dev_priv, power_domain)) {
1265                 u32 val = I915_READ(PIPECONF(cpu_transcoder));
1266                 cur_state = !!(val & PIPECONF_ENABLE);
1267
1268                 intel_display_power_put(dev_priv, power_domain);
1269         } else {
1270                 cur_state = false;
1271         }
1272
1273         I915_STATE_WARN(cur_state != state,
1274              "pipe %c assertion failure (expected %s, current %s)\n",
1275                         pipe_name(pipe), onoff(state), onoff(cur_state));
1276 }
1277
1278 static void assert_plane(struct drm_i915_private *dev_priv,
1279                          enum plane plane, bool state)
1280 {
1281         u32 val;
1282         bool cur_state;
1283
1284         val = I915_READ(DSPCNTR(plane));
1285         cur_state = !!(val & DISPLAY_PLANE_ENABLE);
1286         I915_STATE_WARN(cur_state != state,
1287              "plane %c assertion failure (expected %s, current %s)\n",
1288                         plane_name(plane), onoff(state), onoff(cur_state));
1289 }
1290
1291 #define assert_plane_enabled(d, p) assert_plane(d, p, true)
1292 #define assert_plane_disabled(d, p) assert_plane(d, p, false)
1293
1294 static void assert_planes_disabled(struct drm_i915_private *dev_priv,
1295                                    enum pipe pipe)
1296 {
1297         struct drm_device *dev = &dev_priv->drm;
1298         int i;
1299
1300         /* Primary planes are fixed to pipes on gen4+ */
1301         if (INTEL_INFO(dev)->gen >= 4) {
1302                 u32 val = I915_READ(DSPCNTR(pipe));
1303                 I915_STATE_WARN(val & DISPLAY_PLANE_ENABLE,
1304                      "plane %c assertion failure, should be disabled but not\n",
1305                      plane_name(pipe));
1306                 return;
1307         }
1308
1309         /* Need to check both planes against the pipe */
1310         for_each_pipe(dev_priv, i) {
1311                 u32 val = I915_READ(DSPCNTR(i));
1312                 enum pipe cur_pipe = (val & DISPPLANE_SEL_PIPE_MASK) >>
1313                         DISPPLANE_SEL_PIPE_SHIFT;
1314                 I915_STATE_WARN((val & DISPLAY_PLANE_ENABLE) && pipe == cur_pipe,
1315                      "plane %c assertion failure, should be off on pipe %c but is still active\n",
1316                      plane_name(i), pipe_name(pipe));
1317         }
1318 }
1319
1320 static void assert_sprites_disabled(struct drm_i915_private *dev_priv,
1321                                     enum pipe pipe)
1322 {
1323         struct drm_device *dev = &dev_priv->drm;
1324         int sprite;
1325
1326         if (INTEL_INFO(dev)->gen >= 9) {
1327                 for_each_sprite(dev_priv, pipe, sprite) {
1328                         u32 val = I915_READ(PLANE_CTL(pipe, sprite));
1329                         I915_STATE_WARN(val & PLANE_CTL_ENABLE,
1330                              "plane %d assertion failure, should be off on pipe %c but is still active\n",
1331                              sprite, pipe_name(pipe));
1332                 }
1333         } else if (IS_VALLEYVIEW(dev) || IS_CHERRYVIEW(dev)) {
1334                 for_each_sprite(dev_priv, pipe, sprite) {
1335                         u32 val = I915_READ(SPCNTR(pipe, sprite));
1336                         I915_STATE_WARN(val & SP_ENABLE,
1337                              "sprite %c assertion failure, should be off on pipe %c but is still active\n",
1338                              sprite_name(pipe, sprite), pipe_name(pipe));
1339                 }
1340         } else if (INTEL_INFO(dev)->gen >= 7) {
1341                 u32 val = I915_READ(SPRCTL(pipe));
1342                 I915_STATE_WARN(val & SPRITE_ENABLE,
1343                      "sprite %c assertion failure, should be off on pipe %c but is still active\n",
1344                      plane_name(pipe), pipe_name(pipe));
1345         } else if (INTEL_INFO(dev)->gen >= 5) {
1346                 u32 val = I915_READ(DVSCNTR(pipe));
1347                 I915_STATE_WARN(val & DVS_ENABLE,
1348                      "sprite %c assertion failure, should be off on pipe %c but is still active\n",
1349                      plane_name(pipe), pipe_name(pipe));
1350         }
1351 }
1352
1353 static void assert_vblank_disabled(struct drm_crtc *crtc)
1354 {
1355         if (I915_STATE_WARN_ON(drm_crtc_vblank_get(crtc) == 0))
1356                 drm_crtc_vblank_put(crtc);
1357 }
1358
1359 void assert_pch_transcoder_disabled(struct drm_i915_private *dev_priv,
1360                                     enum pipe pipe)
1361 {
1362         u32 val;
1363         bool enabled;
1364
1365         val = I915_READ(PCH_TRANSCONF(pipe));
1366         enabled = !!(val & TRANS_ENABLE);
1367         I915_STATE_WARN(enabled,
1368              "transcoder assertion failed, should be off on pipe %c but is still active\n",
1369              pipe_name(pipe));
1370 }
1371
1372 static bool dp_pipe_enabled(struct drm_i915_private *dev_priv,
1373                             enum pipe pipe, u32 port_sel, u32 val)
1374 {
1375         if ((val & DP_PORT_EN) == 0)
1376                 return false;
1377
1378         if (HAS_PCH_CPT(dev_priv)) {
1379                 u32 trans_dp_ctl = I915_READ(TRANS_DP_CTL(pipe));
1380                 if ((trans_dp_ctl & TRANS_DP_PORT_SEL_MASK) != port_sel)
1381                         return false;
1382         } else if (IS_CHERRYVIEW(dev_priv)) {
1383                 if ((val & DP_PIPE_MASK_CHV) != DP_PIPE_SELECT_CHV(pipe))
1384                         return false;
1385         } else {
1386                 if ((val & DP_PIPE_MASK) != (pipe << 30))
1387                         return false;
1388         }
1389         return true;
1390 }
1391
1392 static bool hdmi_pipe_enabled(struct drm_i915_private *dev_priv,
1393                               enum pipe pipe, u32 val)
1394 {
1395         if ((val & SDVO_ENABLE) == 0)
1396                 return false;
1397
1398         if (HAS_PCH_CPT(dev_priv)) {
1399                 if ((val & SDVO_PIPE_SEL_MASK_CPT) != SDVO_PIPE_SEL_CPT(pipe))
1400                         return false;
1401         } else if (IS_CHERRYVIEW(dev_priv)) {
1402                 if ((val & SDVO_PIPE_SEL_MASK_CHV) != SDVO_PIPE_SEL_CHV(pipe))
1403                         return false;
1404         } else {
1405                 if ((val & SDVO_PIPE_SEL_MASK) != SDVO_PIPE_SEL(pipe))
1406                         return false;
1407         }
1408         return true;
1409 }
1410
1411 static bool lvds_pipe_enabled(struct drm_i915_private *dev_priv,
1412                               enum pipe pipe, u32 val)
1413 {
1414         if ((val & LVDS_PORT_EN) == 0)
1415                 return false;
1416
1417         if (HAS_PCH_CPT(dev_priv)) {
1418                 if ((val & PORT_TRANS_SEL_MASK) != PORT_TRANS_SEL_CPT(pipe))
1419                         return false;
1420         } else {
1421                 if ((val & LVDS_PIPE_MASK) != LVDS_PIPE(pipe))
1422                         return false;
1423         }
1424         return true;
1425 }
1426
1427 static bool adpa_pipe_enabled(struct drm_i915_private *dev_priv,
1428                               enum pipe pipe, u32 val)
1429 {
1430         if ((val & ADPA_DAC_ENABLE) == 0)
1431                 return false;
1432         if (HAS_PCH_CPT(dev_priv)) {
1433                 if ((val & PORT_TRANS_SEL_MASK) != PORT_TRANS_SEL_CPT(pipe))
1434                         return false;
1435         } else {
1436                 if ((val & ADPA_PIPE_SELECT_MASK) != ADPA_PIPE_SELECT(pipe))
1437                         return false;
1438         }
1439         return true;
1440 }
1441
1442 static void assert_pch_dp_disabled(struct drm_i915_private *dev_priv,
1443                                    enum pipe pipe, i915_reg_t reg,
1444                                    u32 port_sel)
1445 {
1446         u32 val = I915_READ(reg);
1447         I915_STATE_WARN(dp_pipe_enabled(dev_priv, pipe, port_sel, val),
1448              "PCH DP (0x%08x) enabled on transcoder %c, should be disabled\n",
1449              i915_mmio_reg_offset(reg), pipe_name(pipe));
1450
1451         I915_STATE_WARN(HAS_PCH_IBX(dev_priv) && (val & DP_PORT_EN) == 0
1452              && (val & DP_PIPEB_SELECT),
1453              "IBX PCH dp port still using transcoder B\n");
1454 }
1455
1456 static void assert_pch_hdmi_disabled(struct drm_i915_private *dev_priv,
1457                                      enum pipe pipe, i915_reg_t reg)
1458 {
1459         u32 val = I915_READ(reg);
1460         I915_STATE_WARN(hdmi_pipe_enabled(dev_priv, pipe, val),
1461              "PCH HDMI (0x%08x) enabled on transcoder %c, should be disabled\n",
1462              i915_mmio_reg_offset(reg), pipe_name(pipe));
1463
1464         I915_STATE_WARN(HAS_PCH_IBX(dev_priv) && (val & SDVO_ENABLE) == 0
1465              && (val & SDVO_PIPE_B_SELECT),
1466              "IBX PCH hdmi port still using transcoder B\n");
1467 }
1468
1469 static void assert_pch_ports_disabled(struct drm_i915_private *dev_priv,
1470                                       enum pipe pipe)
1471 {
1472         u32 val;
1473
1474         assert_pch_dp_disabled(dev_priv, pipe, PCH_DP_B, TRANS_DP_PORT_SEL_B);
1475         assert_pch_dp_disabled(dev_priv, pipe, PCH_DP_C, TRANS_DP_PORT_SEL_C);
1476         assert_pch_dp_disabled(dev_priv, pipe, PCH_DP_D, TRANS_DP_PORT_SEL_D);
1477
1478         val = I915_READ(PCH_ADPA);
1479         I915_STATE_WARN(adpa_pipe_enabled(dev_priv, pipe, val),
1480              "PCH VGA enabled on transcoder %c, should be disabled\n",
1481              pipe_name(pipe));
1482
1483         val = I915_READ(PCH_LVDS);
1484         I915_STATE_WARN(lvds_pipe_enabled(dev_priv, pipe, val),
1485              "PCH LVDS enabled on transcoder %c, should be disabled\n",
1486              pipe_name(pipe));
1487
1488         assert_pch_hdmi_disabled(dev_priv, pipe, PCH_HDMIB);
1489         assert_pch_hdmi_disabled(dev_priv, pipe, PCH_HDMIC);
1490         assert_pch_hdmi_disabled(dev_priv, pipe, PCH_HDMID);
1491 }
1492
1493 static void _vlv_enable_pll(struct intel_crtc *crtc,
1494                             const struct intel_crtc_state *pipe_config)
1495 {
1496         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1497         enum pipe pipe = crtc->pipe;
1498
1499         I915_WRITE(DPLL(pipe), pipe_config->dpll_hw_state.dpll);
1500         POSTING_READ(DPLL(pipe));
1501         udelay(150);
1502
1503         if (intel_wait_for_register(dev_priv,
1504                                     DPLL(pipe),
1505                                     DPLL_LOCK_VLV,
1506                                     DPLL_LOCK_VLV,
1507                                     1))
1508                 DRM_ERROR("DPLL %d failed to lock\n", pipe);
1509 }
1510
1511 static void vlv_enable_pll(struct intel_crtc *crtc,
1512                            const struct intel_crtc_state *pipe_config)
1513 {
1514         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1515         enum pipe pipe = crtc->pipe;
1516
1517         assert_pipe_disabled(dev_priv, pipe);
1518
1519         /* PLL is protected by panel, make sure we can write it */
1520         assert_panel_unlocked(dev_priv, pipe);
1521
1522         if (pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE)
1523                 _vlv_enable_pll(crtc, pipe_config);
1524
1525         I915_WRITE(DPLL_MD(pipe), pipe_config->dpll_hw_state.dpll_md);
1526         POSTING_READ(DPLL_MD(pipe));
1527 }
1528
1529
1530 static void _chv_enable_pll(struct intel_crtc *crtc,
1531                             const struct intel_crtc_state *pipe_config)
1532 {
1533         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1534         enum pipe pipe = crtc->pipe;
1535         enum dpio_channel port = vlv_pipe_to_channel(pipe);
1536         u32 tmp;
1537
1538         mutex_lock(&dev_priv->sb_lock);
1539
1540         /* Enable back the 10bit clock to display controller */
1541         tmp = vlv_dpio_read(dev_priv, pipe, CHV_CMN_DW14(port));
1542         tmp |= DPIO_DCLKP_EN;
1543         vlv_dpio_write(dev_priv, pipe, CHV_CMN_DW14(port), tmp);
1544
1545         mutex_unlock(&dev_priv->sb_lock);
1546
1547         /*
1548          * Need to wait > 100ns between dclkp clock enable bit and PLL enable.
1549          */
1550         udelay(1);
1551
1552         /* Enable PLL */
1553         I915_WRITE(DPLL(pipe), pipe_config->dpll_hw_state.dpll);
1554
1555         /* Check PLL is locked */
1556         if (intel_wait_for_register(dev_priv,
1557                                     DPLL(pipe), DPLL_LOCK_VLV, DPLL_LOCK_VLV,
1558                                     1))
1559                 DRM_ERROR("PLL %d failed to lock\n", pipe);
1560 }
1561
1562 static void chv_enable_pll(struct intel_crtc *crtc,
1563                            const struct intel_crtc_state *pipe_config)
1564 {
1565         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1566         enum pipe pipe = crtc->pipe;
1567
1568         assert_pipe_disabled(dev_priv, pipe);
1569
1570         /* PLL is protected by panel, make sure we can write it */
1571         assert_panel_unlocked(dev_priv, pipe);
1572
1573         if (pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE)
1574                 _chv_enable_pll(crtc, pipe_config);
1575
1576         if (pipe != PIPE_A) {
1577                 /*
1578                  * WaPixelRepeatModeFixForC0:chv
1579                  *
1580                  * DPLLCMD is AWOL. Use chicken bits to propagate
1581                  * the value from DPLLBMD to either pipe B or C.
1582                  */
1583                 I915_WRITE(CBR4_VLV, pipe == PIPE_B ? CBR_DPLLBMD_PIPE_B : CBR_DPLLBMD_PIPE_C);
1584                 I915_WRITE(DPLL_MD(PIPE_B), pipe_config->dpll_hw_state.dpll_md);
1585                 I915_WRITE(CBR4_VLV, 0);
1586                 dev_priv->chv_dpll_md[pipe] = pipe_config->dpll_hw_state.dpll_md;
1587
1588                 /*
1589                  * DPLLB VGA mode also seems to cause problems.
1590                  * We should always have it disabled.
1591                  */
1592                 WARN_ON((I915_READ(DPLL(PIPE_B)) & DPLL_VGA_MODE_DIS) == 0);
1593         } else {
1594                 I915_WRITE(DPLL_MD(pipe), pipe_config->dpll_hw_state.dpll_md);
1595                 POSTING_READ(DPLL_MD(pipe));
1596         }
1597 }
1598
1599 static int intel_num_dvo_pipes(struct drm_device *dev)
1600 {
1601         struct intel_crtc *crtc;
1602         int count = 0;
1603
1604         for_each_intel_crtc(dev, crtc) {
1605                 count += crtc->base.state->active &&
1606                         intel_crtc_has_type(crtc->config, INTEL_OUTPUT_DVO);
1607         }
1608
1609         return count;
1610 }
1611
1612 static void i9xx_enable_pll(struct intel_crtc *crtc)
1613 {
1614         struct drm_device *dev = crtc->base.dev;
1615         struct drm_i915_private *dev_priv = to_i915(dev);
1616         i915_reg_t reg = DPLL(crtc->pipe);
1617         u32 dpll = crtc->config->dpll_hw_state.dpll;
1618
1619         assert_pipe_disabled(dev_priv, crtc->pipe);
1620
1621         /* PLL is protected by panel, make sure we can write it */
1622         if (IS_MOBILE(dev) && !IS_I830(dev))
1623                 assert_panel_unlocked(dev_priv, crtc->pipe);
1624
1625         /* Enable DVO 2x clock on both PLLs if necessary */
1626         if (IS_I830(dev) && intel_num_dvo_pipes(dev) > 0) {
1627                 /*
1628                  * It appears to be important that we don't enable this
1629                  * for the current pipe before otherwise configuring the
1630                  * PLL. No idea how this should be handled if multiple
1631                  * DVO outputs are enabled simultaneosly.
1632                  */
1633                 dpll |= DPLL_DVO_2X_MODE;
1634                 I915_WRITE(DPLL(!crtc->pipe),
1635                            I915_READ(DPLL(!crtc->pipe)) | DPLL_DVO_2X_MODE);
1636         }
1637
1638         /*
1639          * Apparently we need to have VGA mode enabled prior to changing
1640          * the P1/P2 dividers. Otherwise the DPLL will keep using the old
1641          * dividers, even though the register value does change.
1642          */
1643         I915_WRITE(reg, 0);
1644
1645         I915_WRITE(reg, dpll);
1646
1647         /* Wait for the clocks to stabilize. */
1648         POSTING_READ(reg);
1649         udelay(150);
1650
1651         if (INTEL_INFO(dev)->gen >= 4) {
1652                 I915_WRITE(DPLL_MD(crtc->pipe),
1653                            crtc->config->dpll_hw_state.dpll_md);
1654         } else {
1655                 /* The pixel multiplier can only be updated once the
1656                  * DPLL is enabled and the clocks are stable.
1657                  *
1658                  * So write it again.
1659                  */
1660                 I915_WRITE(reg, dpll);
1661         }
1662
1663         /* We do this three times for luck */
1664         I915_WRITE(reg, dpll);
1665         POSTING_READ(reg);
1666         udelay(150); /* wait for warmup */
1667         I915_WRITE(reg, dpll);
1668         POSTING_READ(reg);
1669         udelay(150); /* wait for warmup */
1670         I915_WRITE(reg, dpll);
1671         POSTING_READ(reg);
1672         udelay(150); /* wait for warmup */
1673 }
1674
1675 /**
1676  * i9xx_disable_pll - disable a PLL
1677  * @dev_priv: i915 private structure
1678  * @pipe: pipe PLL to disable
1679  *
1680  * Disable the PLL for @pipe, making sure the pipe is off first.
1681  *
1682  * Note!  This is for pre-ILK only.
1683  */
1684 static void i9xx_disable_pll(struct intel_crtc *crtc)
1685 {
1686         struct drm_device *dev = crtc->base.dev;
1687         struct drm_i915_private *dev_priv = to_i915(dev);
1688         enum pipe pipe = crtc->pipe;
1689
1690         /* Disable DVO 2x clock on both PLLs if necessary */
1691         if (IS_I830(dev) &&
1692             intel_crtc_has_type(crtc->config, INTEL_OUTPUT_DVO) &&
1693             !intel_num_dvo_pipes(dev)) {
1694                 I915_WRITE(DPLL(PIPE_B),
1695                            I915_READ(DPLL(PIPE_B)) & ~DPLL_DVO_2X_MODE);
1696                 I915_WRITE(DPLL(PIPE_A),
1697                            I915_READ(DPLL(PIPE_A)) & ~DPLL_DVO_2X_MODE);
1698         }
1699
1700         /* Don't disable pipe or pipe PLLs if needed */
1701         if ((pipe == PIPE_A && dev_priv->quirks & QUIRK_PIPEA_FORCE) ||
1702             (pipe == PIPE_B && dev_priv->quirks & QUIRK_PIPEB_FORCE))
1703                 return;
1704
1705         /* Make sure the pipe isn't still relying on us */
1706         assert_pipe_disabled(dev_priv, pipe);
1707
1708         I915_WRITE(DPLL(pipe), DPLL_VGA_MODE_DIS);
1709         POSTING_READ(DPLL(pipe));
1710 }
1711
1712 static void vlv_disable_pll(struct drm_i915_private *dev_priv, enum pipe pipe)
1713 {
1714         u32 val;
1715
1716         /* Make sure the pipe isn't still relying on us */
1717         assert_pipe_disabled(dev_priv, pipe);
1718
1719         val = DPLL_INTEGRATED_REF_CLK_VLV |
1720                 DPLL_REF_CLK_ENABLE_VLV | DPLL_VGA_MODE_DIS;
1721         if (pipe != PIPE_A)
1722                 val |= DPLL_INTEGRATED_CRI_CLK_VLV;
1723
1724         I915_WRITE(DPLL(pipe), val);
1725         POSTING_READ(DPLL(pipe));
1726 }
1727
1728 static void chv_disable_pll(struct drm_i915_private *dev_priv, enum pipe pipe)
1729 {
1730         enum dpio_channel port = vlv_pipe_to_channel(pipe);
1731         u32 val;
1732
1733         /* Make sure the pipe isn't still relying on us */
1734         assert_pipe_disabled(dev_priv, pipe);
1735
1736         val = DPLL_SSC_REF_CLK_CHV |
1737                 DPLL_REF_CLK_ENABLE_VLV | DPLL_VGA_MODE_DIS;
1738         if (pipe != PIPE_A)
1739                 val |= DPLL_INTEGRATED_CRI_CLK_VLV;
1740
1741         I915_WRITE(DPLL(pipe), val);
1742         POSTING_READ(DPLL(pipe));
1743
1744         mutex_lock(&dev_priv->sb_lock);
1745
1746         /* Disable 10bit clock to display controller */
1747         val = vlv_dpio_read(dev_priv, pipe, CHV_CMN_DW14(port));
1748         val &= ~DPIO_DCLKP_EN;
1749         vlv_dpio_write(dev_priv, pipe, CHV_CMN_DW14(port), val);
1750
1751         mutex_unlock(&dev_priv->sb_lock);
1752 }
1753
1754 void vlv_wait_port_ready(struct drm_i915_private *dev_priv,
1755                          struct intel_digital_port *dport,
1756                          unsigned int expected_mask)
1757 {
1758         u32 port_mask;
1759         i915_reg_t dpll_reg;
1760
1761         switch (dport->port) {
1762         case PORT_B:
1763                 port_mask = DPLL_PORTB_READY_MASK;
1764                 dpll_reg = DPLL(0);
1765                 break;
1766         case PORT_C:
1767                 port_mask = DPLL_PORTC_READY_MASK;
1768                 dpll_reg = DPLL(0);
1769                 expected_mask <<= 4;
1770                 break;
1771         case PORT_D:
1772                 port_mask = DPLL_PORTD_READY_MASK;
1773                 dpll_reg = DPIO_PHY_STATUS;
1774                 break;
1775         default:
1776                 BUG();
1777         }
1778
1779         if (intel_wait_for_register(dev_priv,
1780                                     dpll_reg, port_mask, expected_mask,
1781                                     1000))
1782                 WARN(1, "timed out waiting for port %c ready: got 0x%x, expected 0x%x\n",
1783                      port_name(dport->port), I915_READ(dpll_reg) & port_mask, expected_mask);
1784 }
1785
1786 static void ironlake_enable_pch_transcoder(struct drm_i915_private *dev_priv,
1787                                            enum pipe pipe)
1788 {
1789         struct drm_device *dev = &dev_priv->drm;
1790         struct drm_crtc *crtc = dev_priv->pipe_to_crtc_mapping[pipe];
1791         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
1792         i915_reg_t reg;
1793         uint32_t val, pipeconf_val;
1794
1795         /* Make sure PCH DPLL is enabled */
1796         assert_shared_dpll_enabled(dev_priv, intel_crtc->config->shared_dpll);
1797
1798         /* FDI must be feeding us bits for PCH ports */
1799         assert_fdi_tx_enabled(dev_priv, pipe);
1800         assert_fdi_rx_enabled(dev_priv, pipe);
1801
1802         if (HAS_PCH_CPT(dev)) {
1803                 /* Workaround: Set the timing override bit before enabling the
1804                  * pch transcoder. */
1805                 reg = TRANS_CHICKEN2(pipe);
1806                 val = I915_READ(reg);
1807                 val |= TRANS_CHICKEN2_TIMING_OVERRIDE;
1808                 I915_WRITE(reg, val);
1809         }
1810
1811         reg = PCH_TRANSCONF(pipe);
1812         val = I915_READ(reg);
1813         pipeconf_val = I915_READ(PIPECONF(pipe));
1814
1815         if (HAS_PCH_IBX(dev_priv)) {
1816                 /*
1817                  * Make the BPC in transcoder be consistent with
1818                  * that in pipeconf reg. For HDMI we must use 8bpc
1819                  * here for both 8bpc and 12bpc.
1820                  */
1821                 val &= ~PIPECONF_BPC_MASK;
1822                 if (intel_crtc_has_type(intel_crtc->config, INTEL_OUTPUT_HDMI))
1823                         val |= PIPECONF_8BPC;
1824                 else
1825                         val |= pipeconf_val & PIPECONF_BPC_MASK;
1826         }
1827
1828         val &= ~TRANS_INTERLACE_MASK;
1829         if ((pipeconf_val & PIPECONF_INTERLACE_MASK) == PIPECONF_INTERLACED_ILK)
1830                 if (HAS_PCH_IBX(dev_priv) &&
1831                     intel_crtc_has_type(intel_crtc->config, INTEL_OUTPUT_SDVO))
1832                         val |= TRANS_LEGACY_INTERLACED_ILK;
1833                 else
1834                         val |= TRANS_INTERLACED;
1835         else
1836                 val |= TRANS_PROGRESSIVE;
1837
1838         I915_WRITE(reg, val | TRANS_ENABLE);
1839         if (intel_wait_for_register(dev_priv,
1840                                     reg, TRANS_STATE_ENABLE, TRANS_STATE_ENABLE,
1841                                     100))
1842                 DRM_ERROR("failed to enable transcoder %c\n", pipe_name(pipe));
1843 }
1844
1845 static void lpt_enable_pch_transcoder(struct drm_i915_private *dev_priv,
1846                                       enum transcoder cpu_transcoder)
1847 {
1848         u32 val, pipeconf_val;
1849
1850         /* FDI must be feeding us bits for PCH ports */
1851         assert_fdi_tx_enabled(dev_priv, (enum pipe) cpu_transcoder);
1852         assert_fdi_rx_enabled(dev_priv, PIPE_A);
1853
1854         /* Workaround: set timing override bit. */
1855         val = I915_READ(TRANS_CHICKEN2(PIPE_A));
1856         val |= TRANS_CHICKEN2_TIMING_OVERRIDE;
1857         I915_WRITE(TRANS_CHICKEN2(PIPE_A), val);
1858
1859         val = TRANS_ENABLE;
1860         pipeconf_val = I915_READ(PIPECONF(cpu_transcoder));
1861
1862         if ((pipeconf_val & PIPECONF_INTERLACE_MASK_HSW) ==
1863             PIPECONF_INTERLACED_ILK)
1864                 val |= TRANS_INTERLACED;
1865         else
1866                 val |= TRANS_PROGRESSIVE;
1867
1868         I915_WRITE(LPT_TRANSCONF, val);
1869         if (intel_wait_for_register(dev_priv,
1870                                     LPT_TRANSCONF,
1871                                     TRANS_STATE_ENABLE,
1872                                     TRANS_STATE_ENABLE,
1873                                     100))
1874                 DRM_ERROR("Failed to enable PCH transcoder\n");
1875 }
1876
1877 static void ironlake_disable_pch_transcoder(struct drm_i915_private *dev_priv,
1878                                             enum pipe pipe)
1879 {
1880         struct drm_device *dev = &dev_priv->drm;
1881         i915_reg_t reg;
1882         uint32_t val;
1883
1884         /* FDI relies on the transcoder */
1885         assert_fdi_tx_disabled(dev_priv, pipe);
1886         assert_fdi_rx_disabled(dev_priv, pipe);
1887
1888         /* Ports must be off as well */
1889         assert_pch_ports_disabled(dev_priv, pipe);
1890
1891         reg = PCH_TRANSCONF(pipe);
1892         val = I915_READ(reg);
1893         val &= ~TRANS_ENABLE;
1894         I915_WRITE(reg, val);
1895         /* wait for PCH transcoder off, transcoder state */
1896         if (intel_wait_for_register(dev_priv,
1897                                     reg, TRANS_STATE_ENABLE, 0,
1898                                     50))
1899                 DRM_ERROR("failed to disable transcoder %c\n", pipe_name(pipe));
1900
1901         if (HAS_PCH_CPT(dev)) {
1902                 /* Workaround: Clear the timing override chicken bit again. */
1903                 reg = TRANS_CHICKEN2(pipe);
1904                 val = I915_READ(reg);
1905                 val &= ~TRANS_CHICKEN2_TIMING_OVERRIDE;
1906                 I915_WRITE(reg, val);
1907         }
1908 }
1909
1910 void lpt_disable_pch_transcoder(struct drm_i915_private *dev_priv)
1911 {
1912         u32 val;
1913
1914         val = I915_READ(LPT_TRANSCONF);
1915         val &= ~TRANS_ENABLE;
1916         I915_WRITE(LPT_TRANSCONF, val);
1917         /* wait for PCH transcoder off, transcoder state */
1918         if (intel_wait_for_register(dev_priv,
1919                                     LPT_TRANSCONF, TRANS_STATE_ENABLE, 0,
1920                                     50))
1921                 DRM_ERROR("Failed to disable PCH transcoder\n");
1922
1923         /* Workaround: clear timing override bit. */
1924         val = I915_READ(TRANS_CHICKEN2(PIPE_A));
1925         val &= ~TRANS_CHICKEN2_TIMING_OVERRIDE;
1926         I915_WRITE(TRANS_CHICKEN2(PIPE_A), val);
1927 }
1928
1929 /**
1930  * intel_enable_pipe - enable a pipe, asserting requirements
1931  * @crtc: crtc responsible for the pipe
1932  *
1933  * Enable @crtc's pipe, making sure that various hardware specific requirements
1934  * are met, if applicable, e.g. PLL enabled, LVDS pairs enabled, etc.
1935  */
1936 static void intel_enable_pipe(struct intel_crtc *crtc)
1937 {
1938         struct drm_device *dev = crtc->base.dev;
1939         struct drm_i915_private *dev_priv = to_i915(dev);
1940         enum pipe pipe = crtc->pipe;
1941         enum transcoder cpu_transcoder = crtc->config->cpu_transcoder;
1942         enum pipe pch_transcoder;
1943         i915_reg_t reg;
1944         u32 val;
1945
1946         DRM_DEBUG_KMS("enabling pipe %c\n", pipe_name(pipe));
1947
1948         assert_planes_disabled(dev_priv, pipe);
1949         assert_cursor_disabled(dev_priv, pipe);
1950         assert_sprites_disabled(dev_priv, pipe);
1951
1952         if (HAS_PCH_LPT(dev_priv))
1953                 pch_transcoder = PIPE_A;
1954         else
1955                 pch_transcoder = pipe;
1956
1957         /*
1958          * A pipe without a PLL won't actually be able to drive bits from
1959          * a plane.  On ILK+ the pipe PLLs are integrated, so we don't
1960          * need the check.
1961          */
1962         if (HAS_GMCH_DISPLAY(dev_priv)) {
1963                 if (intel_crtc_has_type(crtc->config, INTEL_OUTPUT_DSI))
1964                         assert_dsi_pll_enabled(dev_priv);
1965                 else
1966                         assert_pll_enabled(dev_priv, pipe);
1967         } else {
1968                 if (crtc->config->has_pch_encoder) {
1969                         /* if driving the PCH, we need FDI enabled */
1970                         assert_fdi_rx_pll_enabled(dev_priv, pch_transcoder);
1971                         assert_fdi_tx_pll_enabled(dev_priv,
1972                                                   (enum pipe) cpu_transcoder);
1973                 }
1974                 /* FIXME: assert CPU port conditions for SNB+ */
1975         }
1976
1977         reg = PIPECONF(cpu_transcoder);
1978         val = I915_READ(reg);
1979         if (val & PIPECONF_ENABLE) {
1980                 WARN_ON(!((pipe == PIPE_A && dev_priv->quirks & QUIRK_PIPEA_FORCE) ||
1981                           (pipe == PIPE_B && dev_priv->quirks & QUIRK_PIPEB_FORCE)));
1982                 return;
1983         }
1984
1985         I915_WRITE(reg, val | PIPECONF_ENABLE);
1986         POSTING_READ(reg);
1987
1988         /*
1989          * Until the pipe starts DSL will read as 0, which would cause
1990          * an apparent vblank timestamp jump, which messes up also the
1991          * frame count when it's derived from the timestamps. So let's
1992          * wait for the pipe to start properly before we call
1993          * drm_crtc_vblank_on()
1994          */
1995         if (dev->max_vblank_count == 0 &&
1996             wait_for(intel_get_crtc_scanline(crtc) != crtc->scanline_offset, 50))
1997                 DRM_ERROR("pipe %c didn't start\n", pipe_name(pipe));
1998 }
1999
2000 /**
2001  * intel_disable_pipe - disable a pipe, asserting requirements
2002  * @crtc: crtc whose pipes is to be disabled
2003  *
2004  * Disable the pipe of @crtc, making sure that various hardware
2005  * specific requirements are met, if applicable, e.g. plane
2006  * disabled, panel fitter off, etc.
2007  *
2008  * Will wait until the pipe has shut down before returning.
2009  */
2010 static void intel_disable_pipe(struct intel_crtc *crtc)
2011 {
2012         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
2013         enum transcoder cpu_transcoder = crtc->config->cpu_transcoder;
2014         enum pipe pipe = crtc->pipe;
2015         i915_reg_t reg;
2016         u32 val;
2017
2018         DRM_DEBUG_KMS("disabling pipe %c\n", pipe_name(pipe));
2019
2020         /*
2021          * Make sure planes won't keep trying to pump pixels to us,
2022          * or we might hang the display.
2023          */
2024         assert_planes_disabled(dev_priv, pipe);
2025         assert_cursor_disabled(dev_priv, pipe);
2026         assert_sprites_disabled(dev_priv, pipe);
2027
2028         reg = PIPECONF(cpu_transcoder);
2029         val = I915_READ(reg);
2030         if ((val & PIPECONF_ENABLE) == 0)
2031                 return;
2032
2033         /*
2034          * Double wide has implications for planes
2035          * so best keep it disabled when not needed.
2036          */
2037         if (crtc->config->double_wide)
2038                 val &= ~PIPECONF_DOUBLE_WIDE;
2039
2040         /* Don't disable pipe or pipe PLLs if needed */
2041         if (!(pipe == PIPE_A && dev_priv->quirks & QUIRK_PIPEA_FORCE) &&
2042             !(pipe == PIPE_B && dev_priv->quirks & QUIRK_PIPEB_FORCE))
2043                 val &= ~PIPECONF_ENABLE;
2044
2045         I915_WRITE(reg, val);
2046         if ((val & PIPECONF_ENABLE) == 0)
2047                 intel_wait_for_pipe_off(crtc);
2048 }
2049
2050 static unsigned int intel_tile_size(const struct drm_i915_private *dev_priv)
2051 {
2052         return IS_GEN2(dev_priv) ? 2048 : 4096;
2053 }
2054
2055 static unsigned int intel_tile_width_bytes(const struct drm_i915_private *dev_priv,
2056                                            uint64_t fb_modifier, unsigned int cpp)
2057 {
2058         switch (fb_modifier) {
2059         case DRM_FORMAT_MOD_NONE:
2060                 return cpp;
2061         case I915_FORMAT_MOD_X_TILED:
2062                 if (IS_GEN2(dev_priv))
2063                         return 128;
2064                 else
2065                         return 512;
2066         case I915_FORMAT_MOD_Y_TILED:
2067                 if (IS_GEN2(dev_priv) || HAS_128_BYTE_Y_TILING(dev_priv))
2068                         return 128;
2069                 else
2070                         return 512;
2071         case I915_FORMAT_MOD_Yf_TILED:
2072                 switch (cpp) {
2073                 case 1:
2074                         return 64;
2075                 case 2:
2076                 case 4:
2077                         return 128;
2078                 case 8:
2079                 case 16:
2080                         return 256;
2081                 default:
2082                         MISSING_CASE(cpp);
2083                         return cpp;
2084                 }
2085                 break;
2086         default:
2087                 MISSING_CASE(fb_modifier);
2088                 return cpp;
2089         }
2090 }
2091
2092 unsigned int intel_tile_height(const struct drm_i915_private *dev_priv,
2093                                uint64_t fb_modifier, unsigned int cpp)
2094 {
2095         if (fb_modifier == DRM_FORMAT_MOD_NONE)
2096                 return 1;
2097         else
2098                 return intel_tile_size(dev_priv) /
2099                         intel_tile_width_bytes(dev_priv, fb_modifier, cpp);
2100 }
2101
2102 /* Return the tile dimensions in pixel units */
2103 static void intel_tile_dims(const struct drm_i915_private *dev_priv,
2104                             unsigned int *tile_width,
2105                             unsigned int *tile_height,
2106                             uint64_t fb_modifier,
2107                             unsigned int cpp)
2108 {
2109         unsigned int tile_width_bytes =
2110                 intel_tile_width_bytes(dev_priv, fb_modifier, cpp);
2111
2112         *tile_width = tile_width_bytes / cpp;
2113         *tile_height = intel_tile_size(dev_priv) / tile_width_bytes;
2114 }
2115
2116 unsigned int
2117 intel_fb_align_height(struct drm_device *dev, unsigned int height,
2118                       uint32_t pixel_format, uint64_t fb_modifier)
2119 {
2120         unsigned int cpp = drm_format_plane_cpp(pixel_format, 0);
2121         unsigned int tile_height = intel_tile_height(to_i915(dev), fb_modifier, cpp);
2122
2123         return ALIGN(height, tile_height);
2124 }
2125
2126 unsigned int intel_rotation_info_size(const struct intel_rotation_info *rot_info)
2127 {
2128         unsigned int size = 0;
2129         int i;
2130
2131         for (i = 0 ; i < ARRAY_SIZE(rot_info->plane); i++)
2132                 size += rot_info->plane[i].width * rot_info->plane[i].height;
2133
2134         return size;
2135 }
2136
2137 static void
2138 intel_fill_fb_ggtt_view(struct i915_ggtt_view *view,
2139                         const struct drm_framebuffer *fb,
2140                         unsigned int rotation)
2141 {
2142         if (intel_rotation_90_or_270(rotation)) {
2143                 *view = i915_ggtt_view_rotated;
2144                 view->params.rotated = to_intel_framebuffer(fb)->rot_info;
2145         } else {
2146                 *view = i915_ggtt_view_normal;
2147         }
2148 }
2149
2150 static unsigned int intel_linear_alignment(const struct drm_i915_private *dev_priv)
2151 {
2152         if (INTEL_INFO(dev_priv)->gen >= 9)
2153                 return 256 * 1024;
2154         else if (IS_BROADWATER(dev_priv) || IS_CRESTLINE(dev_priv) ||
2155                  IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
2156                 return 128 * 1024;
2157         else if (INTEL_INFO(dev_priv)->gen >= 4)
2158                 return 4 * 1024;
2159         else
2160                 return 0;
2161 }
2162
2163 static unsigned int intel_surf_alignment(const struct drm_i915_private *dev_priv,
2164                                          uint64_t fb_modifier)
2165 {
2166         switch (fb_modifier) {
2167         case DRM_FORMAT_MOD_NONE:
2168                 return intel_linear_alignment(dev_priv);
2169         case I915_FORMAT_MOD_X_TILED:
2170                 if (INTEL_INFO(dev_priv)->gen >= 9)
2171                         return 256 * 1024;
2172                 return 0;
2173         case I915_FORMAT_MOD_Y_TILED:
2174         case I915_FORMAT_MOD_Yf_TILED:
2175                 return 1 * 1024 * 1024;
2176         default:
2177                 MISSING_CASE(fb_modifier);
2178                 return 0;
2179         }
2180 }
2181
2182 struct i915_vma *
2183 intel_pin_and_fence_fb_obj(struct drm_framebuffer *fb, unsigned int rotation)
2184 {
2185         struct drm_device *dev = fb->dev;
2186         struct drm_i915_private *dev_priv = to_i915(dev);
2187         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
2188         struct i915_ggtt_view view;
2189         struct i915_vma *vma;
2190         u32 alignment;
2191
2192         WARN_ON(!mutex_is_locked(&dev->struct_mutex));
2193
2194         alignment = intel_surf_alignment(dev_priv, fb->modifier[0]);
2195
2196         intel_fill_fb_ggtt_view(&view, fb, rotation);
2197
2198         /* Note that the w/a also requires 64 PTE of padding following the
2199          * bo. We currently fill all unused PTE with the shadow page and so
2200          * we should always have valid PTE following the scanout preventing
2201          * the VT-d warning.
2202          */
2203         if (intel_scanout_needs_vtd_wa(dev_priv) && alignment < 256 * 1024)
2204                 alignment = 256 * 1024;
2205
2206         /*
2207          * Global gtt pte registers are special registers which actually forward
2208          * writes to a chunk of system memory. Which means that there is no risk
2209          * that the register values disappear as soon as we call
2210          * intel_runtime_pm_put(), so it is correct to wrap only the
2211          * pin/unpin/fence and not more.
2212          */
2213         intel_runtime_pm_get(dev_priv);
2214
2215         vma = i915_gem_object_pin_to_display_plane(obj, alignment, &view);
2216         if (IS_ERR(vma))
2217                 goto err;
2218
2219         if (i915_vma_is_map_and_fenceable(vma)) {
2220                 /* Install a fence for tiled scan-out. Pre-i965 always needs a
2221                  * fence, whereas 965+ only requires a fence if using
2222                  * framebuffer compression.  For simplicity, we always, when
2223                  * possible, install a fence as the cost is not that onerous.
2224                  *
2225                  * If we fail to fence the tiled scanout, then either the
2226                  * modeset will reject the change (which is highly unlikely as
2227                  * the affected systems, all but one, do not have unmappable
2228                  * space) or we will not be able to enable full powersaving
2229                  * techniques (also likely not to apply due to various limits
2230                  * FBC and the like impose on the size of the buffer, which
2231                  * presumably we violated anyway with this unmappable buffer).
2232                  * Anyway, it is presumably better to stumble onwards with
2233                  * something and try to run the system in a "less than optimal"
2234                  * mode that matches the user configuration.
2235                  */
2236                 if (i915_vma_get_fence(vma) == 0)
2237                         i915_vma_pin_fence(vma);
2238         }
2239
2240 err:
2241         intel_runtime_pm_put(dev_priv);
2242         return vma;
2243 }
2244
2245 void intel_unpin_fb_obj(struct drm_framebuffer *fb, unsigned int rotation)
2246 {
2247         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
2248         struct i915_ggtt_view view;
2249         struct i915_vma *vma;
2250
2251         WARN_ON(!mutex_is_locked(&obj->base.dev->struct_mutex));
2252
2253         intel_fill_fb_ggtt_view(&view, fb, rotation);
2254         vma = i915_gem_object_to_ggtt(obj, &view);
2255
2256         if (WARN_ON_ONCE(!vma))
2257                 return;
2258
2259         i915_vma_unpin_fence(vma);
2260         i915_gem_object_unpin_from_display_plane(vma);
2261 }
2262
2263 static int intel_fb_pitch(const struct drm_framebuffer *fb, int plane,
2264                           unsigned int rotation)
2265 {
2266         if (intel_rotation_90_or_270(rotation))
2267                 return to_intel_framebuffer(fb)->rotated[plane].pitch;
2268         else
2269                 return fb->pitches[plane];
2270 }
2271
2272 /*
2273  * Convert the x/y offsets into a linear offset.
2274  * Only valid with 0/180 degree rotation, which is fine since linear
2275  * offset is only used with linear buffers on pre-hsw and tiled buffers
2276  * with gen2/3, and 90/270 degree rotations isn't supported on any of them.
2277  */
2278 u32 intel_fb_xy_to_linear(int x, int y,
2279                           const struct intel_plane_state *state,
2280                           int plane)
2281 {
2282         const struct drm_framebuffer *fb = state->base.fb;
2283         unsigned int cpp = drm_format_plane_cpp(fb->pixel_format, plane);
2284         unsigned int pitch = fb->pitches[plane];
2285
2286         return y * pitch + x * cpp;
2287 }
2288
2289 /*
2290  * Add the x/y offsets derived from fb->offsets[] to the user
2291  * specified plane src x/y offsets. The resulting x/y offsets
2292  * specify the start of scanout from the beginning of the gtt mapping.
2293  */
2294 void intel_add_fb_offsets(int *x, int *y,
2295                           const struct intel_plane_state *state,
2296                           int plane)
2297
2298 {
2299         const struct intel_framebuffer *intel_fb = to_intel_framebuffer(state->base.fb);
2300         unsigned int rotation = state->base.rotation;
2301
2302         if (intel_rotation_90_or_270(rotation)) {
2303                 *x += intel_fb->rotated[plane].x;
2304                 *y += intel_fb->rotated[plane].y;
2305         } else {
2306                 *x += intel_fb->normal[plane].x;
2307                 *y += intel_fb->normal[plane].y;
2308         }
2309 }
2310
2311 /*
2312  * Input tile dimensions and pitch must already be
2313  * rotated to match x and y, and in pixel units.
2314  */
2315 static u32 _intel_adjust_tile_offset(int *x, int *y,
2316                                      unsigned int tile_width,
2317                                      unsigned int tile_height,
2318                                      unsigned int tile_size,
2319                                      unsigned int pitch_tiles,
2320                                      u32 old_offset,
2321                                      u32 new_offset)
2322 {
2323         unsigned int pitch_pixels = pitch_tiles * tile_width;
2324         unsigned int tiles;
2325
2326         WARN_ON(old_offset & (tile_size - 1));
2327         WARN_ON(new_offset & (tile_size - 1));
2328         WARN_ON(new_offset > old_offset);
2329
2330         tiles = (old_offset - new_offset) / tile_size;
2331
2332         *y += tiles / pitch_tiles * tile_height;
2333         *x += tiles % pitch_tiles * tile_width;
2334
2335         /* minimize x in case it got needlessly big */
2336         *y += *x / pitch_pixels * tile_height;
2337         *x %= pitch_pixels;
2338
2339         return new_offset;
2340 }
2341
2342 /*
2343  * Adjust the tile offset by moving the difference into
2344  * the x/y offsets.
2345  */
2346 static u32 intel_adjust_tile_offset(int *x, int *y,
2347                                     const struct intel_plane_state *state, int plane,
2348                                     u32 old_offset, u32 new_offset)
2349 {
2350         const struct drm_i915_private *dev_priv = to_i915(state->base.plane->dev);
2351         const struct drm_framebuffer *fb = state->base.fb;
2352         unsigned int cpp = drm_format_plane_cpp(fb->pixel_format, plane);
2353         unsigned int rotation = state->base.rotation;
2354         unsigned int pitch = intel_fb_pitch(fb, plane, rotation);
2355
2356         WARN_ON(new_offset > old_offset);
2357
2358         if (fb->modifier[plane] != DRM_FORMAT_MOD_NONE) {
2359                 unsigned int tile_size, tile_width, tile_height;
2360                 unsigned int pitch_tiles;
2361
2362                 tile_size = intel_tile_size(dev_priv);
2363                 intel_tile_dims(dev_priv, &tile_width, &tile_height,
2364                                 fb->modifier[plane], cpp);
2365
2366                 if (intel_rotation_90_or_270(rotation)) {
2367                         pitch_tiles = pitch / tile_height;
2368                         swap(tile_width, tile_height);
2369                 } else {
2370                         pitch_tiles = pitch / (tile_width * cpp);
2371                 }
2372
2373                 _intel_adjust_tile_offset(x, y, tile_width, tile_height,
2374                                           tile_size, pitch_tiles,
2375                                           old_offset, new_offset);
2376         } else {
2377                 old_offset += *y * pitch + *x * cpp;
2378
2379                 *y = (old_offset - new_offset) / pitch;
2380                 *x = ((old_offset - new_offset) - *y * pitch) / cpp;
2381         }
2382
2383         return new_offset;
2384 }
2385
2386 /*
2387  * Computes the linear offset to the base tile and adjusts
2388  * x, y. bytes per pixel is assumed to be a power-of-two.
2389  *
2390  * In the 90/270 rotated case, x and y are assumed
2391  * to be already rotated to match the rotated GTT view, and
2392  * pitch is the tile_height aligned framebuffer height.
2393  *
2394  * This function is used when computing the derived information
2395  * under intel_framebuffer, so using any of that information
2396  * here is not allowed. Anything under drm_framebuffer can be
2397  * used. This is why the user has to pass in the pitch since it
2398  * is specified in the rotated orientation.
2399  */
2400 static u32 _intel_compute_tile_offset(const struct drm_i915_private *dev_priv,
2401                                       int *x, int *y,
2402                                       const struct drm_framebuffer *fb, int plane,
2403                                       unsigned int pitch,
2404                                       unsigned int rotation,
2405                                       u32 alignment)
2406 {
2407         uint64_t fb_modifier = fb->modifier[plane];
2408         unsigned int cpp = drm_format_plane_cpp(fb->pixel_format, plane);
2409         u32 offset, offset_aligned;
2410
2411         if (alignment)
2412                 alignment--;
2413
2414         if (fb_modifier != DRM_FORMAT_MOD_NONE) {
2415                 unsigned int tile_size, tile_width, tile_height;
2416                 unsigned int tile_rows, tiles, pitch_tiles;
2417
2418                 tile_size = intel_tile_size(dev_priv);
2419                 intel_tile_dims(dev_priv, &tile_width, &tile_height,
2420                                 fb_modifier, cpp);
2421
2422                 if (intel_rotation_90_or_270(rotation)) {
2423                         pitch_tiles = pitch / tile_height;
2424                         swap(tile_width, tile_height);
2425                 } else {
2426                         pitch_tiles = pitch / (tile_width * cpp);
2427                 }
2428
2429                 tile_rows = *y / tile_height;
2430                 *y %= tile_height;
2431
2432                 tiles = *x / tile_width;
2433                 *x %= tile_width;
2434
2435                 offset = (tile_rows * pitch_tiles + tiles) * tile_size;
2436                 offset_aligned = offset & ~alignment;
2437
2438                 _intel_adjust_tile_offset(x, y, tile_width, tile_height,
2439                                           tile_size, pitch_tiles,
2440                                           offset, offset_aligned);
2441         } else {
2442                 offset = *y * pitch + *x * cpp;
2443                 offset_aligned = offset & ~alignment;
2444
2445                 *y = (offset & alignment) / pitch;
2446                 *x = ((offset & alignment) - *y * pitch) / cpp;
2447         }
2448
2449         return offset_aligned;
2450 }
2451
2452 u32 intel_compute_tile_offset(int *x, int *y,
2453                               const struct intel_plane_state *state,
2454                               int plane)
2455 {
2456         const struct drm_i915_private *dev_priv = to_i915(state->base.plane->dev);
2457         const struct drm_framebuffer *fb = state->base.fb;
2458         unsigned int rotation = state->base.rotation;
2459         int pitch = intel_fb_pitch(fb, plane, rotation);
2460         u32 alignment;
2461
2462         /* AUX_DIST needs only 4K alignment */
2463         if (fb->pixel_format == DRM_FORMAT_NV12 && plane == 1)
2464                 alignment = 4096;
2465         else
2466                 alignment = intel_surf_alignment(dev_priv, fb->modifier[plane]);
2467
2468         return _intel_compute_tile_offset(dev_priv, x, y, fb, plane, pitch,
2469                                           rotation, alignment);
2470 }
2471
2472 /* Convert the fb->offset[] linear offset into x/y offsets */
2473 static void intel_fb_offset_to_xy(int *x, int *y,
2474                                   const struct drm_framebuffer *fb, int plane)
2475 {
2476         unsigned int cpp = drm_format_plane_cpp(fb->pixel_format, plane);
2477         unsigned int pitch = fb->pitches[plane];
2478         u32 linear_offset = fb->offsets[plane];
2479
2480         *y = linear_offset / pitch;
2481         *x = linear_offset % pitch / cpp;
2482 }
2483
2484 static unsigned int intel_fb_modifier_to_tiling(uint64_t fb_modifier)
2485 {
2486         switch (fb_modifier) {
2487         case I915_FORMAT_MOD_X_TILED:
2488                 return I915_TILING_X;
2489         case I915_FORMAT_MOD_Y_TILED:
2490                 return I915_TILING_Y;
2491         default:
2492                 return I915_TILING_NONE;
2493         }
2494 }
2495
2496 static int
2497 intel_fill_fb_info(struct drm_i915_private *dev_priv,
2498                    struct drm_framebuffer *fb)
2499 {
2500         struct intel_framebuffer *intel_fb = to_intel_framebuffer(fb);
2501         struct intel_rotation_info *rot_info = &intel_fb->rot_info;
2502         u32 gtt_offset_rotated = 0;
2503         unsigned int max_size = 0;
2504         uint32_t format = fb->pixel_format;
2505         int i, num_planes = drm_format_num_planes(format);
2506         unsigned int tile_size = intel_tile_size(dev_priv);
2507
2508         for (i = 0; i < num_planes; i++) {
2509                 unsigned int width, height;
2510                 unsigned int cpp, size;
2511                 u32 offset;
2512                 int x, y;
2513
2514                 cpp = drm_format_plane_cpp(format, i);
2515                 width = drm_format_plane_width(fb->width, format, i);
2516                 height = drm_format_plane_height(fb->height, format, i);
2517
2518                 intel_fb_offset_to_xy(&x, &y, fb, i);
2519
2520                 /*
2521                  * The fence (if used) is aligned to the start of the object
2522                  * so having the framebuffer wrap around across the edge of the
2523                  * fenced region doesn't really work. We have no API to configure
2524                  * the fence start offset within the object (nor could we probably
2525                  * on gen2/3). So it's just easier if we just require that the
2526                  * fb layout agrees with the fence layout. We already check that the
2527                  * fb stride matches the fence stride elsewhere.
2528                  */
2529                 if (i915_gem_object_is_tiled(intel_fb->obj) &&
2530                     (x + width) * cpp > fb->pitches[i]) {
2531                         DRM_DEBUG("bad fb plane %d offset: 0x%x\n",
2532                                   i, fb->offsets[i]);
2533                         return -EINVAL;
2534                 }
2535
2536                 /*
2537                  * First pixel of the framebuffer from
2538                  * the start of the normal gtt mapping.
2539                  */
2540                 intel_fb->normal[i].x = x;
2541                 intel_fb->normal[i].y = y;
2542
2543                 offset = _intel_compute_tile_offset(dev_priv, &x, &y,
2544                                                     fb, 0, fb->pitches[i],
2545                                                     DRM_ROTATE_0, tile_size);
2546                 offset /= tile_size;
2547
2548                 if (fb->modifier[i] != DRM_FORMAT_MOD_NONE) {
2549                         unsigned int tile_width, tile_height;
2550                         unsigned int pitch_tiles;
2551                         struct drm_rect r;
2552
2553                         intel_tile_dims(dev_priv, &tile_width, &tile_height,
2554                                         fb->modifier[i], cpp);
2555
2556                         rot_info->plane[i].offset = offset;
2557                         rot_info->plane[i].stride = DIV_ROUND_UP(fb->pitches[i], tile_width * cpp);
2558                         rot_info->plane[i].width = DIV_ROUND_UP(x + width, tile_width);
2559                         rot_info->plane[i].height = DIV_ROUND_UP(y + height, tile_height);
2560
2561                         intel_fb->rotated[i].pitch =
2562                                 rot_info->plane[i].height * tile_height;
2563
2564                         /* how many tiles does this plane need */
2565                         size = rot_info->plane[i].stride * rot_info->plane[i].height;
2566                         /*
2567                          * If the plane isn't horizontally tile aligned,
2568                          * we need one more tile.
2569                          */
2570                         if (x != 0)
2571                                 size++;
2572
2573                         /* rotate the x/y offsets to match the GTT view */
2574                         r.x1 = x;
2575                         r.y1 = y;
2576                         r.x2 = x + width;
2577                         r.y2 = y + height;
2578                         drm_rect_rotate(&r,
2579                                         rot_info->plane[i].width * tile_width,
2580                                         rot_info->plane[i].height * tile_height,
2581                                         DRM_ROTATE_270);
2582                         x = r.x1;
2583                         y = r.y1;
2584
2585                         /* rotate the tile dimensions to match the GTT view */
2586                         pitch_tiles = intel_fb->rotated[i].pitch / tile_height;
2587                         swap(tile_width, tile_height);
2588
2589                         /*
2590                          * We only keep the x/y offsets, so push all of the
2591                          * gtt offset into the x/y offsets.
2592                          */
2593                         _intel_adjust_tile_offset(&x, &y,
2594                                                   tile_width, tile_height,
2595                                                   tile_size, pitch_tiles,
2596                                                   gtt_offset_rotated * tile_size, 0);
2597
2598                         gtt_offset_rotated += rot_info->plane[i].width * rot_info->plane[i].height;
2599
2600                         /*
2601                          * First pixel of the framebuffer from
2602                          * the start of the rotated gtt mapping.
2603                          */
2604                         intel_fb->rotated[i].x = x;
2605                         intel_fb->rotated[i].y = y;
2606                 } else {
2607                         size = DIV_ROUND_UP((y + height) * fb->pitches[i] +
2608                                             x * cpp, tile_size);
2609                 }
2610
2611                 /* how many tiles in total needed in the bo */
2612                 max_size = max(max_size, offset + size);
2613         }
2614
2615         if (max_size * tile_size > to_intel_framebuffer(fb)->obj->base.size) {
2616                 DRM_DEBUG("fb too big for bo (need %u bytes, have %zu bytes)\n",
2617                           max_size * tile_size, to_intel_framebuffer(fb)->obj->base.size);
2618                 return -EINVAL;
2619         }
2620
2621         return 0;
2622 }
2623
2624 static int i9xx_format_to_fourcc(int format)
2625 {
2626         switch (format) {
2627         case DISPPLANE_8BPP:
2628                 return DRM_FORMAT_C8;
2629         case DISPPLANE_BGRX555:
2630                 return DRM_FORMAT_XRGB1555;
2631         case DISPPLANE_BGRX565:
2632                 return DRM_FORMAT_RGB565;
2633         default:
2634         case DISPPLANE_BGRX888:
2635                 return DRM_FORMAT_XRGB8888;
2636         case DISPPLANE_RGBX888:
2637                 return DRM_FORMAT_XBGR8888;
2638         case DISPPLANE_BGRX101010:
2639                 return DRM_FORMAT_XRGB2101010;
2640         case DISPPLANE_RGBX101010:
2641                 return DRM_FORMAT_XBGR2101010;
2642         }
2643 }
2644
2645 static int skl_format_to_fourcc(int format, bool rgb_order, bool alpha)
2646 {
2647         switch (format) {
2648         case PLANE_CTL_FORMAT_RGB_565:
2649                 return DRM_FORMAT_RGB565;
2650         default:
2651         case PLANE_CTL_FORMAT_XRGB_8888:
2652                 if (rgb_order) {
2653                         if (alpha)
2654                                 return DRM_FORMAT_ABGR8888;
2655                         else
2656                                 return DRM_FORMAT_XBGR8888;
2657                 } else {
2658                         if (alpha)
2659                                 return DRM_FORMAT_ARGB8888;
2660                         else
2661                                 return DRM_FORMAT_XRGB8888;
2662                 }
2663         case PLANE_CTL_FORMAT_XRGB_2101010:
2664                 if (rgb_order)
2665                         return DRM_FORMAT_XBGR2101010;
2666                 else
2667                         return DRM_FORMAT_XRGB2101010;
2668         }
2669 }
2670
2671 static bool
2672 intel_alloc_initial_plane_obj(struct intel_crtc *crtc,
2673                               struct intel_initial_plane_config *plane_config)
2674 {
2675         struct drm_device *dev = crtc->base.dev;
2676         struct drm_i915_private *dev_priv = to_i915(dev);
2677         struct i915_ggtt *ggtt = &dev_priv->ggtt;
2678         struct drm_i915_gem_object *obj = NULL;
2679         struct drm_mode_fb_cmd2 mode_cmd = { 0 };
2680         struct drm_framebuffer *fb = &plane_config->fb->base;
2681         u32 base_aligned = round_down(plane_config->base, PAGE_SIZE);
2682         u32 size_aligned = round_up(plane_config->base + plane_config->size,
2683                                     PAGE_SIZE);
2684
2685         size_aligned -= base_aligned;
2686
2687         if (plane_config->size == 0)
2688                 return false;
2689
2690         /* If the FB is too big, just don't use it since fbdev is not very
2691          * important and we should probably use that space with FBC or other
2692          * features. */
2693         if (size_aligned * 2 > ggtt->stolen_usable_size)
2694                 return false;
2695
2696         mutex_lock(&dev->struct_mutex);
2697
2698         obj = i915_gem_object_create_stolen_for_preallocated(dev,
2699                                                              base_aligned,
2700                                                              base_aligned,
2701                                                              size_aligned);
2702         if (!obj) {
2703                 mutex_unlock(&dev->struct_mutex);
2704                 return false;
2705         }
2706
2707         if (plane_config->tiling == I915_TILING_X)
2708                 obj->tiling_and_stride = fb->pitches[0] | I915_TILING_X;
2709
2710         mode_cmd.pixel_format = fb->pixel_format;
2711         mode_cmd.width = fb->width;
2712         mode_cmd.height = fb->height;
2713         mode_cmd.pitches[0] = fb->pitches[0];
2714         mode_cmd.modifier[0] = fb->modifier[0];
2715         mode_cmd.flags = DRM_MODE_FB_MODIFIERS;
2716
2717         if (intel_framebuffer_init(dev, to_intel_framebuffer(fb),
2718                                    &mode_cmd, obj)) {
2719                 DRM_DEBUG_KMS("intel fb init failed\n");
2720                 goto out_unref_obj;
2721         }
2722
2723         mutex_unlock(&dev->struct_mutex);
2724
2725         DRM_DEBUG_KMS("initial plane fb obj %p\n", obj);
2726         return true;
2727
2728 out_unref_obj:
2729         i915_gem_object_put(obj);
2730         mutex_unlock(&dev->struct_mutex);
2731         return false;
2732 }
2733
2734 /* Update plane->state->fb to match plane->fb after driver-internal updates */
2735 static void
2736 update_state_fb(struct drm_plane *plane)
2737 {
2738         if (plane->fb == plane->state->fb)
2739                 return;
2740
2741         if (plane->state->fb)
2742                 drm_framebuffer_unreference(plane->state->fb);
2743         plane->state->fb = plane->fb;
2744         if (plane->state->fb)
2745                 drm_framebuffer_reference(plane->state->fb);
2746 }
2747
2748 static void
2749 intel_find_initial_plane_obj(struct intel_crtc *intel_crtc,
2750                              struct intel_initial_plane_config *plane_config)
2751 {
2752         struct drm_device *dev = intel_crtc->base.dev;
2753         struct drm_i915_private *dev_priv = to_i915(dev);
2754         struct drm_crtc *c;
2755         struct intel_crtc *i;
2756         struct drm_i915_gem_object *obj;
2757         struct drm_plane *primary = intel_crtc->base.primary;
2758         struct drm_plane_state *plane_state = primary->state;
2759         struct drm_crtc_state *crtc_state = intel_crtc->base.state;
2760         struct intel_plane *intel_plane = to_intel_plane(primary);
2761         struct intel_plane_state *intel_state =
2762                 to_intel_plane_state(plane_state);
2763         struct drm_framebuffer *fb;
2764
2765         if (!plane_config->fb)
2766                 return;
2767
2768         if (intel_alloc_initial_plane_obj(intel_crtc, plane_config)) {
2769                 fb = &plane_config->fb->base;
2770                 goto valid_fb;
2771         }
2772
2773         kfree(plane_config->fb);
2774
2775         /*
2776          * Failed to alloc the obj, check to see if we should share
2777          * an fb with another CRTC instead
2778          */
2779         for_each_crtc(dev, c) {
2780                 i = to_intel_crtc(c);
2781
2782                 if (c == &intel_crtc->base)
2783                         continue;
2784
2785                 if (!i->active)
2786                         continue;
2787
2788                 fb = c->primary->fb;
2789                 if (!fb)
2790                         continue;
2791
2792                 obj = intel_fb_obj(fb);
2793                 if (i915_gem_object_ggtt_offset(obj, NULL) == plane_config->base) {
2794                         drm_framebuffer_reference(fb);
2795                         goto valid_fb;
2796                 }
2797         }
2798
2799         /*
2800          * We've failed to reconstruct the BIOS FB.  Current display state
2801          * indicates that the primary plane is visible, but has a NULL FB,
2802          * which will lead to problems later if we don't fix it up.  The
2803          * simplest solution is to just disable the primary plane now and
2804          * pretend the BIOS never had it enabled.
2805          */
2806         to_intel_plane_state(plane_state)->base.visible = false;
2807         crtc_state->plane_mask &= ~(1 << drm_plane_index(primary));
2808         intel_pre_disable_primary_noatomic(&intel_crtc->base);
2809         intel_plane->disable_plane(primary, &intel_crtc->base);
2810
2811         return;
2812
2813 valid_fb:
2814         plane_state->src_x = 0;
2815         plane_state->src_y = 0;
2816         plane_state->src_w = fb->width << 16;
2817         plane_state->src_h = fb->height << 16;
2818
2819         plane_state->crtc_x = 0;
2820         plane_state->crtc_y = 0;
2821         plane_state->crtc_w = fb->width;
2822         plane_state->crtc_h = fb->height;
2823
2824         intel_state->base.src.x1 = plane_state->src_x;
2825         intel_state->base.src.y1 = plane_state->src_y;
2826         intel_state->base.src.x2 = plane_state->src_x + plane_state->src_w;
2827         intel_state->base.src.y2 = plane_state->src_y + plane_state->src_h;
2828         intel_state->base.dst.x1 = plane_state->crtc_x;
2829         intel_state->base.dst.y1 = plane_state->crtc_y;
2830         intel_state->base.dst.x2 = plane_state->crtc_x + plane_state->crtc_w;
2831         intel_state->base.dst.y2 = plane_state->crtc_y + plane_state->crtc_h;
2832
2833         obj = intel_fb_obj(fb);
2834         if (i915_gem_object_is_tiled(obj))
2835                 dev_priv->preserve_bios_swizzle = true;
2836
2837         drm_framebuffer_reference(fb);
2838         primary->fb = primary->state->fb = fb;
2839         primary->crtc = primary->state->crtc = &intel_crtc->base;
2840         intel_crtc->base.state->plane_mask |= (1 << drm_plane_index(primary));
2841         atomic_or(to_intel_plane(primary)->frontbuffer_bit,
2842                   &obj->frontbuffer_bits);
2843 }
2844
2845 static int skl_max_plane_width(const struct drm_framebuffer *fb, int plane,
2846                                unsigned int rotation)
2847 {
2848         int cpp = drm_format_plane_cpp(fb->pixel_format, plane);
2849
2850         switch (fb->modifier[plane]) {
2851         case DRM_FORMAT_MOD_NONE:
2852         case I915_FORMAT_MOD_X_TILED:
2853                 switch (cpp) {
2854                 case 8:
2855                         return 4096;
2856                 case 4:
2857                 case 2:
2858                 case 1:
2859                         return 8192;
2860                 default:
2861                         MISSING_CASE(cpp);
2862                         break;
2863                 }
2864                 break;
2865         case I915_FORMAT_MOD_Y_TILED:
2866         case I915_FORMAT_MOD_Yf_TILED:
2867                 switch (cpp) {
2868                 case 8:
2869                         return 2048;
2870                 case 4:
2871                         return 4096;
2872                 case 2:
2873                 case 1:
2874                         return 8192;
2875                 default:
2876                         MISSING_CASE(cpp);
2877                         break;
2878                 }
2879                 break;
2880         default:
2881                 MISSING_CASE(fb->modifier[plane]);
2882         }
2883
2884         return 2048;
2885 }
2886
2887 static int skl_check_main_surface(struct intel_plane_state *plane_state)
2888 {
2889         const struct drm_i915_private *dev_priv = to_i915(plane_state->base.plane->dev);
2890         const struct drm_framebuffer *fb = plane_state->base.fb;
2891         unsigned int rotation = plane_state->base.rotation;
2892         int x = plane_state->base.src.x1 >> 16;
2893         int y = plane_state->base.src.y1 >> 16;
2894         int w = drm_rect_width(&plane_state->base.src) >> 16;
2895         int h = drm_rect_height(&plane_state->base.src) >> 16;
2896         int max_width = skl_max_plane_width(fb, 0, rotation);
2897         int max_height = 4096;
2898         u32 alignment, offset, aux_offset = plane_state->aux.offset;
2899
2900         if (w > max_width || h > max_height) {
2901                 DRM_DEBUG_KMS("requested Y/RGB source size %dx%d too big (limit %dx%d)\n",
2902                               w, h, max_width, max_height);
2903                 return -EINVAL;
2904         }
2905
2906         intel_add_fb_offsets(&x, &y, plane_state, 0);
2907         offset = intel_compute_tile_offset(&x, &y, plane_state, 0);
2908
2909         alignment = intel_surf_alignment(dev_priv, fb->modifier[0]);
2910
2911         /*
2912          * AUX surface offset is specified as the distance from the
2913          * main surface offset, and it must be non-negative. Make
2914          * sure that is what we will get.
2915          */
2916         if (offset > aux_offset)
2917                 offset = intel_adjust_tile_offset(&x, &y, plane_state, 0,
2918                                                   offset, aux_offset & ~(alignment - 1));
2919
2920         /*
2921          * When using an X-tiled surface, the plane blows up
2922          * if the x offset + width exceed the stride.
2923          *
2924          * TODO: linear and Y-tiled seem fine, Yf untested,
2925          */
2926         if (fb->modifier[0] == I915_FORMAT_MOD_X_TILED) {
2927                 int cpp = drm_format_plane_cpp(fb->pixel_format, 0);
2928
2929                 while ((x + w) * cpp > fb->pitches[0]) {
2930                         if (offset == 0) {
2931                                 DRM_DEBUG_KMS("Unable to find suitable display surface offset\n");
2932                                 return -EINVAL;
2933                         }
2934
2935                         offset = intel_adjust_tile_offset(&x, &y, plane_state, 0,
2936                                                           offset, offset - alignment);
2937                 }
2938         }
2939
2940         plane_state->main.offset = offset;
2941         plane_state->main.x = x;
2942         plane_state->main.y = y;
2943
2944         return 0;
2945 }
2946
2947 static int skl_check_nv12_aux_surface(struct intel_plane_state *plane_state)
2948 {
2949         const struct drm_framebuffer *fb = plane_state->base.fb;
2950         unsigned int rotation = plane_state->base.rotation;
2951         int max_width = skl_max_plane_width(fb, 1, rotation);
2952         int max_height = 4096;
2953         int x = plane_state->base.src.x1 >> 17;
2954         int y = plane_state->base.src.y1 >> 17;
2955         int w = drm_rect_width(&plane_state->base.src) >> 17;
2956         int h = drm_rect_height(&plane_state->base.src) >> 17;
2957         u32 offset;
2958
2959         intel_add_fb_offsets(&x, &y, plane_state, 1);
2960         offset = intel_compute_tile_offset(&x, &y, plane_state, 1);
2961
2962         /* FIXME not quite sure how/if these apply to the chroma plane */
2963         if (w > max_width || h > max_height) {
2964                 DRM_DEBUG_KMS("CbCr source size %dx%d too big (limit %dx%d)\n",
2965                               w, h, max_width, max_height);
2966                 return -EINVAL;
2967         }
2968
2969         plane_state->aux.offset = offset;
2970         plane_state->aux.x = x;
2971         plane_state->aux.y = y;
2972
2973         return 0;
2974 }
2975
2976 int skl_check_plane_surface(struct intel_plane_state *plane_state)
2977 {
2978         const struct drm_framebuffer *fb = plane_state->base.fb;
2979         unsigned int rotation = plane_state->base.rotation;
2980         int ret;
2981
2982         if (!plane_state->base.visible)
2983                 return 0;
2984
2985         /* Rotate src coordinates to match rotated GTT view */
2986         if (intel_rotation_90_or_270(rotation))
2987                 drm_rect_rotate(&plane_state->base.src,
2988                                 fb->width << 16, fb->height << 16,
2989                                 DRM_ROTATE_270);
2990
2991         /*
2992          * Handle the AUX surface first since
2993          * the main surface setup depends on it.
2994          */
2995         if (fb->pixel_format == DRM_FORMAT_NV12) {
2996                 ret = skl_check_nv12_aux_surface(plane_state);
2997                 if (ret)
2998                         return ret;
2999         } else {
3000                 plane_state->aux.offset = ~0xfff;
3001                 plane_state->aux.x = 0;
3002                 plane_state->aux.y = 0;
3003         }
3004
3005         ret = skl_check_main_surface(plane_state);
3006         if (ret)
3007                 return ret;
3008
3009         return 0;
3010 }
3011
3012 static void i9xx_update_primary_plane(struct drm_plane *primary,
3013                                       const struct intel_crtc_state *crtc_state,
3014                                       const struct intel_plane_state *plane_state)
3015 {
3016         struct drm_device *dev = primary->dev;
3017         struct drm_i915_private *dev_priv = to_i915(dev);
3018         struct intel_crtc *intel_crtc = to_intel_crtc(crtc_state->base.crtc);
3019         struct drm_framebuffer *fb = plane_state->base.fb;
3020         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
3021         int plane = intel_crtc->plane;
3022         u32 linear_offset;
3023         u32 dspcntr;
3024         i915_reg_t reg = DSPCNTR(plane);
3025         unsigned int rotation = plane_state->base.rotation;
3026         int x = plane_state->base.src.x1 >> 16;
3027         int y = plane_state->base.src.y1 >> 16;
3028
3029         dspcntr = DISPPLANE_GAMMA_ENABLE;
3030
3031         dspcntr |= DISPLAY_PLANE_ENABLE;
3032
3033         if (INTEL_INFO(dev)->gen < 4) {
3034                 if (intel_crtc->pipe == PIPE_B)
3035                         dspcntr |= DISPPLANE_SEL_PIPE_B;
3036
3037                 /* pipesrc and dspsize control the size that is scaled from,
3038                  * which should always be the user's requested size.
3039                  */
3040                 I915_WRITE(DSPSIZE(plane),
3041                            ((crtc_state->pipe_src_h - 1) << 16) |
3042                            (crtc_state->pipe_src_w - 1));
3043                 I915_WRITE(DSPPOS(plane), 0);
3044         } else if (IS_CHERRYVIEW(dev) && plane == PLANE_B) {
3045                 I915_WRITE(PRIMSIZE(plane),
3046                            ((crtc_state->pipe_src_h - 1) << 16) |
3047                            (crtc_state->pipe_src_w - 1));
3048                 I915_WRITE(PRIMPOS(plane), 0);
3049                 I915_WRITE(PRIMCNSTALPHA(plane), 0);
3050         }
3051
3052         switch (fb->pixel_format) {
3053         case DRM_FORMAT_C8:
3054                 dspcntr |= DISPPLANE_8BPP;
3055                 break;
3056         case DRM_FORMAT_XRGB1555:
3057                 dspcntr |= DISPPLANE_BGRX555;
3058                 break;
3059         case DRM_FORMAT_RGB565:
3060                 dspcntr |= DISPPLANE_BGRX565;
3061                 break;
3062         case DRM_FORMAT_XRGB8888:
3063                 dspcntr |= DISPPLANE_BGRX888;
3064                 break;
3065         case DRM_FORMAT_XBGR8888:
3066                 dspcntr |= DISPPLANE_RGBX888;
3067                 break;
3068         case DRM_FORMAT_XRGB2101010:
3069                 dspcntr |= DISPPLANE_BGRX101010;
3070                 break;
3071         case DRM_FORMAT_XBGR2101010:
3072                 dspcntr |= DISPPLANE_RGBX101010;
3073                 break;
3074         default:
3075                 BUG();
3076         }
3077
3078         if (INTEL_GEN(dev_priv) >= 4 &&
3079             fb->modifier[0] == I915_FORMAT_MOD_X_TILED)
3080                 dspcntr |= DISPPLANE_TILED;
3081
3082         if (IS_G4X(dev))
3083                 dspcntr |= DISPPLANE_TRICKLE_FEED_DISABLE;
3084
3085         intel_add_fb_offsets(&x, &y, plane_state, 0);
3086
3087         if (INTEL_INFO(dev)->gen >= 4)
3088                 intel_crtc->dspaddr_offset =
3089                         intel_compute_tile_offset(&x, &y, plane_state, 0);
3090
3091         if (rotation == DRM_ROTATE_180) {
3092                 dspcntr |= DISPPLANE_ROTATE_180;
3093
3094                 x += (crtc_state->pipe_src_w - 1);
3095                 y += (crtc_state->pipe_src_h - 1);
3096         }
3097
3098         linear_offset = intel_fb_xy_to_linear(x, y, plane_state, 0);
3099
3100         if (INTEL_INFO(dev)->gen < 4)
3101                 intel_crtc->dspaddr_offset = linear_offset;
3102
3103         intel_crtc->adjusted_x = x;
3104         intel_crtc->adjusted_y = y;
3105
3106         I915_WRITE(reg, dspcntr);
3107
3108         I915_WRITE(DSPSTRIDE(plane), fb->pitches[0]);
3109         if (INTEL_INFO(dev)->gen >= 4) {
3110                 I915_WRITE(DSPSURF(plane),
3111                            intel_fb_gtt_offset(fb, rotation) +
3112                            intel_crtc->dspaddr_offset);
3113                 I915_WRITE(DSPTILEOFF(plane), (y << 16) | x);
3114                 I915_WRITE(DSPLINOFF(plane), linear_offset);
3115         } else
3116                 I915_WRITE(DSPADDR(plane), i915_gem_object_ggtt_offset(obj, NULL) + linear_offset);
3117         POSTING_READ(reg);
3118 }
3119
3120 static void i9xx_disable_primary_plane(struct drm_plane *primary,
3121                                        struct drm_crtc *crtc)
3122 {
3123         struct drm_device *dev = crtc->dev;
3124         struct drm_i915_private *dev_priv = to_i915(dev);
3125         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3126         int plane = intel_crtc->plane;
3127
3128         I915_WRITE(DSPCNTR(plane), 0);
3129         if (INTEL_INFO(dev_priv)->gen >= 4)
3130                 I915_WRITE(DSPSURF(plane), 0);
3131         else
3132                 I915_WRITE(DSPADDR(plane), 0);
3133         POSTING_READ(DSPCNTR(plane));
3134 }
3135
3136 static void ironlake_update_primary_plane(struct drm_plane *primary,
3137                                           const struct intel_crtc_state *crtc_state,
3138                                           const struct intel_plane_state *plane_state)
3139 {
3140         struct drm_device *dev = primary->dev;
3141         struct drm_i915_private *dev_priv = to_i915(dev);
3142         struct intel_crtc *intel_crtc = to_intel_crtc(crtc_state->base.crtc);
3143         struct drm_framebuffer *fb = plane_state->base.fb;
3144         int plane = intel_crtc->plane;
3145         u32 linear_offset;
3146         u32 dspcntr;
3147         i915_reg_t reg = DSPCNTR(plane);
3148         unsigned int rotation = plane_state->base.rotation;
3149         int x = plane_state->base.src.x1 >> 16;
3150         int y = plane_state->base.src.y1 >> 16;
3151
3152         dspcntr = DISPPLANE_GAMMA_ENABLE;
3153         dspcntr |= DISPLAY_PLANE_ENABLE;
3154
3155         if (IS_HASWELL(dev) || IS_BROADWELL(dev))
3156                 dspcntr |= DISPPLANE_PIPE_CSC_ENABLE;
3157
3158         switch (fb->pixel_format) {
3159         case DRM_FORMAT_C8:
3160                 dspcntr |= DISPPLANE_8BPP;
3161                 break;
3162         case DRM_FORMAT_RGB565:
3163                 dspcntr |= DISPPLANE_BGRX565;
3164                 break;
3165         case DRM_FORMAT_XRGB8888:
3166                 dspcntr |= DISPPLANE_BGRX888;
3167                 break;
3168         case DRM_FORMAT_XBGR8888:
3169                 dspcntr |= DISPPLANE_RGBX888;
3170                 break;
3171         case DRM_FORMAT_XRGB2101010:
3172                 dspcntr |= DISPPLANE_BGRX101010;
3173                 break;
3174         case DRM_FORMAT_XBGR2101010:
3175                 dspcntr |= DISPPLANE_RGBX101010;
3176                 break;
3177         default:
3178                 BUG();
3179         }
3180
3181         if (fb->modifier[0] == I915_FORMAT_MOD_X_TILED)
3182                 dspcntr |= DISPPLANE_TILED;
3183
3184         if (!IS_HASWELL(dev) && !IS_BROADWELL(dev))
3185                 dspcntr |= DISPPLANE_TRICKLE_FEED_DISABLE;
3186
3187         intel_add_fb_offsets(&x, &y, plane_state, 0);
3188
3189         intel_crtc->dspaddr_offset =
3190                 intel_compute_tile_offset(&x, &y, plane_state, 0);
3191
3192         if (rotation == DRM_ROTATE_180) {
3193                 dspcntr |= DISPPLANE_ROTATE_180;
3194
3195                 if (!IS_HASWELL(dev) && !IS_BROADWELL(dev)) {
3196                         x += (crtc_state->pipe_src_w - 1);
3197                         y += (crtc_state->pipe_src_h - 1);
3198                 }
3199         }
3200
3201         linear_offset = intel_fb_xy_to_linear(x, y, plane_state, 0);
3202
3203         intel_crtc->adjusted_x = x;
3204         intel_crtc->adjusted_y = y;
3205
3206         I915_WRITE(reg, dspcntr);
3207
3208         I915_WRITE(DSPSTRIDE(plane), fb->pitches[0]);
3209         I915_WRITE(DSPSURF(plane),
3210                    intel_fb_gtt_offset(fb, rotation) +
3211                    intel_crtc->dspaddr_offset);
3212         if (IS_HASWELL(dev) || IS_BROADWELL(dev)) {
3213                 I915_WRITE(DSPOFFSET(plane), (y << 16) | x);
3214         } else {
3215                 I915_WRITE(DSPTILEOFF(plane), (y << 16) | x);
3216                 I915_WRITE(DSPLINOFF(plane), linear_offset);
3217         }
3218         POSTING_READ(reg);
3219 }
3220
3221 u32 intel_fb_stride_alignment(const struct drm_i915_private *dev_priv,
3222                               uint64_t fb_modifier, uint32_t pixel_format)
3223 {
3224         if (fb_modifier == DRM_FORMAT_MOD_NONE) {
3225                 return 64;
3226         } else {
3227                 int cpp = drm_format_plane_cpp(pixel_format, 0);
3228
3229                 return intel_tile_width_bytes(dev_priv, fb_modifier, cpp);
3230         }
3231 }
3232
3233 u32 intel_fb_gtt_offset(struct drm_framebuffer *fb,
3234                         unsigned int rotation)
3235 {
3236         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
3237         struct i915_ggtt_view view;
3238         struct i915_vma *vma;
3239
3240         intel_fill_fb_ggtt_view(&view, fb, rotation);
3241
3242         vma = i915_gem_object_to_ggtt(obj, &view);
3243         if (WARN(!vma, "ggtt vma for display object not found! (view=%u)\n",
3244                  view.type))
3245                 return -1;
3246
3247         return i915_ggtt_offset(vma);
3248 }
3249
3250 static void skl_detach_scaler(struct intel_crtc *intel_crtc, int id)
3251 {
3252         struct drm_device *dev = intel_crtc->base.dev;
3253         struct drm_i915_private *dev_priv = to_i915(dev);
3254
3255         I915_WRITE(SKL_PS_CTRL(intel_crtc->pipe, id), 0);
3256         I915_WRITE(SKL_PS_WIN_POS(intel_crtc->pipe, id), 0);
3257         I915_WRITE(SKL_PS_WIN_SZ(intel_crtc->pipe, id), 0);
3258 }
3259
3260 /*
3261  * This function detaches (aka. unbinds) unused scalers in hardware
3262  */
3263 static void skl_detach_scalers(struct intel_crtc *intel_crtc)
3264 {
3265         struct intel_crtc_scaler_state *scaler_state;
3266         int i;
3267
3268         scaler_state = &intel_crtc->config->scaler_state;
3269
3270         /* loop through and disable scalers that aren't in use */
3271         for (i = 0; i < intel_crtc->num_scalers; i++) {
3272                 if (!scaler_state->scalers[i].in_use)
3273                         skl_detach_scaler(intel_crtc, i);
3274         }
3275 }
3276
3277 u32 skl_plane_stride(const struct drm_framebuffer *fb, int plane,
3278                      unsigned int rotation)
3279 {
3280         const struct drm_i915_private *dev_priv = to_i915(fb->dev);
3281         u32 stride = intel_fb_pitch(fb, plane, rotation);
3282
3283         /*
3284          * The stride is either expressed as a multiple of 64 bytes chunks for
3285          * linear buffers or in number of tiles for tiled buffers.
3286          */
3287         if (intel_rotation_90_or_270(rotation)) {
3288                 int cpp = drm_format_plane_cpp(fb->pixel_format, plane);
3289
3290                 stride /= intel_tile_height(dev_priv, fb->modifier[0], cpp);
3291         } else {
3292                 stride /= intel_fb_stride_alignment(dev_priv, fb->modifier[0],
3293                                                     fb->pixel_format);
3294         }
3295
3296         return stride;
3297 }
3298
3299 u32 skl_plane_ctl_format(uint32_t pixel_format)
3300 {
3301         switch (pixel_format) {
3302         case DRM_FORMAT_C8:
3303                 return PLANE_CTL_FORMAT_INDEXED;
3304         case DRM_FORMAT_RGB565:
3305                 return PLANE_CTL_FORMAT_RGB_565;
3306         case DRM_FORMAT_XBGR8888:
3307                 return PLANE_CTL_FORMAT_XRGB_8888 | PLANE_CTL_ORDER_RGBX;
3308         case DRM_FORMAT_XRGB8888:
3309                 return PLANE_CTL_FORMAT_XRGB_8888;
3310         /*
3311          * XXX: For ARBG/ABGR formats we default to expecting scanout buffers
3312          * to be already pre-multiplied. We need to add a knob (or a different
3313          * DRM_FORMAT) for user-space to configure that.
3314          */
3315         case DRM_FORMAT_ABGR8888:
3316                 return PLANE_CTL_FORMAT_XRGB_8888 | PLANE_CTL_ORDER_RGBX |
3317                         PLANE_CTL_ALPHA_SW_PREMULTIPLY;
3318         case DRM_FORMAT_ARGB8888:
3319                 return PLANE_CTL_FORMAT_XRGB_8888 |
3320                         PLANE_CTL_ALPHA_SW_PREMULTIPLY;
3321         case DRM_FORMAT_XRGB2101010:
3322                 return PLANE_CTL_FORMAT_XRGB_2101010;
3323         case DRM_FORMAT_XBGR2101010:
3324                 return PLANE_CTL_ORDER_RGBX | PLANE_CTL_FORMAT_XRGB_2101010;
3325         case DRM_FORMAT_YUYV:
3326                 return PLANE_CTL_FORMAT_YUV422 | PLANE_CTL_YUV422_YUYV;
3327         case DRM_FORMAT_YVYU:
3328                 return PLANE_CTL_FORMAT_YUV422 | PLANE_CTL_YUV422_YVYU;
3329         case DRM_FORMAT_UYVY:
3330                 return PLANE_CTL_FORMAT_YUV422 | PLANE_CTL_YUV422_UYVY;
3331         case DRM_FORMAT_VYUY:
3332                 return PLANE_CTL_FORMAT_YUV422 | PLANE_CTL_YUV422_VYUY;
3333         default:
3334                 MISSING_CASE(pixel_format);
3335         }
3336
3337         return 0;
3338 }
3339
3340 u32 skl_plane_ctl_tiling(uint64_t fb_modifier)
3341 {
3342         switch (fb_modifier) {
3343         case DRM_FORMAT_MOD_NONE:
3344                 break;
3345         case I915_FORMAT_MOD_X_TILED:
3346                 return PLANE_CTL_TILED_X;
3347         case I915_FORMAT_MOD_Y_TILED:
3348                 return PLANE_CTL_TILED_Y;
3349         case I915_FORMAT_MOD_Yf_TILED:
3350                 return PLANE_CTL_TILED_YF;
3351         default:
3352                 MISSING_CASE(fb_modifier);
3353         }
3354
3355         return 0;
3356 }
3357
3358 u32 skl_plane_ctl_rotation(unsigned int rotation)
3359 {
3360         switch (rotation) {
3361         case DRM_ROTATE_0:
3362                 break;
3363         /*
3364          * DRM_ROTATE_ is counter clockwise to stay compatible with Xrandr
3365          * while i915 HW rotation is clockwise, thats why this swapping.
3366          */
3367         case DRM_ROTATE_90:
3368                 return PLANE_CTL_ROTATE_270;
3369         case DRM_ROTATE_180:
3370                 return PLANE_CTL_ROTATE_180;
3371         case DRM_ROTATE_270:
3372                 return PLANE_CTL_ROTATE_90;
3373         default:
3374                 MISSING_CASE(rotation);
3375         }
3376
3377         return 0;
3378 }
3379
3380 static void skylake_update_primary_plane(struct drm_plane *plane,
3381                                          const struct intel_crtc_state *crtc_state,
3382                                          const struct intel_plane_state *plane_state)
3383 {
3384         struct drm_device *dev = plane->dev;
3385         struct drm_i915_private *dev_priv = to_i915(dev);
3386         struct intel_crtc *intel_crtc = to_intel_crtc(crtc_state->base.crtc);
3387         struct drm_framebuffer *fb = plane_state->base.fb;
3388         const struct skl_wm_values *wm = &dev_priv->wm.skl_results;
3389         int pipe = intel_crtc->pipe;
3390         u32 plane_ctl;
3391         unsigned int rotation = plane_state->base.rotation;
3392         u32 stride = skl_plane_stride(fb, 0, rotation);
3393         u32 surf_addr = plane_state->main.offset;
3394         int scaler_id = plane_state->scaler_id;
3395         int src_x = plane_state->main.x;
3396         int src_y = plane_state->main.y;
3397         int src_w = drm_rect_width(&plane_state->base.src) >> 16;
3398         int src_h = drm_rect_height(&plane_state->base.src) >> 16;
3399         int dst_x = plane_state->base.dst.x1;
3400         int dst_y = plane_state->base.dst.y1;
3401         int dst_w = drm_rect_width(&plane_state->base.dst);
3402         int dst_h = drm_rect_height(&plane_state->base.dst);
3403
3404         plane_ctl = PLANE_CTL_ENABLE |
3405                     PLANE_CTL_PIPE_GAMMA_ENABLE |
3406                     PLANE_CTL_PIPE_CSC_ENABLE;
3407
3408         plane_ctl |= skl_plane_ctl_format(fb->pixel_format);
3409         plane_ctl |= skl_plane_ctl_tiling(fb->modifier[0]);
3410         plane_ctl |= PLANE_CTL_PLANE_GAMMA_DISABLE;
3411         plane_ctl |= skl_plane_ctl_rotation(rotation);
3412
3413         /* Sizes are 0 based */
3414         src_w--;
3415         src_h--;
3416         dst_w--;
3417         dst_h--;
3418
3419         intel_crtc->dspaddr_offset = surf_addr;
3420
3421         intel_crtc->adjusted_x = src_x;
3422         intel_crtc->adjusted_y = src_y;
3423
3424         if (wm->dirty_pipes & drm_crtc_mask(&intel_crtc->base))
3425                 skl_write_plane_wm(intel_crtc, wm, 0);
3426
3427         I915_WRITE(PLANE_CTL(pipe, 0), plane_ctl);
3428         I915_WRITE(PLANE_OFFSET(pipe, 0), (src_y << 16) | src_x);
3429         I915_WRITE(PLANE_STRIDE(pipe, 0), stride);
3430         I915_WRITE(PLANE_SIZE(pipe, 0), (src_h << 16) | src_w);
3431
3432         if (scaler_id >= 0) {
3433                 uint32_t ps_ctrl = 0;
3434
3435                 WARN_ON(!dst_w || !dst_h);
3436                 ps_ctrl = PS_SCALER_EN | PS_PLANE_SEL(0) |
3437                         crtc_state->scaler_state.scalers[scaler_id].mode;
3438                 I915_WRITE(SKL_PS_CTRL(pipe, scaler_id), ps_ctrl);
3439                 I915_WRITE(SKL_PS_PWR_GATE(pipe, scaler_id), 0);
3440                 I915_WRITE(SKL_PS_WIN_POS(pipe, scaler_id), (dst_x << 16) | dst_y);
3441                 I915_WRITE(SKL_PS_WIN_SZ(pipe, scaler_id), (dst_w << 16) | dst_h);
3442                 I915_WRITE(PLANE_POS(pipe, 0), 0);
3443         } else {
3444                 I915_WRITE(PLANE_POS(pipe, 0), (dst_y << 16) | dst_x);
3445         }
3446
3447         I915_WRITE(PLANE_SURF(pipe, 0),
3448                    intel_fb_gtt_offset(fb, rotation) + surf_addr);
3449
3450         POSTING_READ(PLANE_SURF(pipe, 0));
3451 }
3452
3453 static void skylake_disable_primary_plane(struct drm_plane *primary,
3454                                           struct drm_crtc *crtc)
3455 {
3456         struct drm_device *dev = crtc->dev;
3457         struct drm_i915_private *dev_priv = to_i915(dev);
3458         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3459         int pipe = intel_crtc->pipe;
3460
3461         /*
3462          * We only populate skl_results on watermark updates, and if the
3463          * plane's visiblity isn't actually changing neither is its watermarks.
3464          */
3465         if (!crtc->primary->state->visible)
3466                 skl_write_plane_wm(intel_crtc, &dev_priv->wm.skl_results, 0);
3467
3468         I915_WRITE(PLANE_CTL(pipe, 0), 0);
3469         I915_WRITE(PLANE_SURF(pipe, 0), 0);
3470         POSTING_READ(PLANE_SURF(pipe, 0));
3471 }
3472
3473 /* Assume fb object is pinned & idle & fenced and just update base pointers */
3474 static int
3475 intel_pipe_set_base_atomic(struct drm_crtc *crtc, struct drm_framebuffer *fb,
3476                            int x, int y, enum mode_set_atomic state)
3477 {
3478         /* Support for kgdboc is disabled, this needs a major rework. */
3479         DRM_ERROR("legacy panic handler not supported any more.\n");
3480
3481         return -ENODEV;
3482 }
3483
3484 static void intel_complete_page_flips(struct drm_i915_private *dev_priv)
3485 {
3486         struct intel_crtc *crtc;
3487
3488         for_each_intel_crtc(&dev_priv->drm, crtc)
3489                 intel_finish_page_flip_cs(dev_priv, crtc->pipe);
3490 }
3491
3492 static void intel_update_primary_planes(struct drm_device *dev)
3493 {
3494         struct drm_crtc *crtc;
3495
3496         for_each_crtc(dev, crtc) {
3497                 struct intel_plane *plane = to_intel_plane(crtc->primary);
3498                 struct intel_plane_state *plane_state =
3499                         to_intel_plane_state(plane->base.state);
3500
3501                 if (plane_state->base.visible)
3502                         plane->update_plane(&plane->base,
3503                                             to_intel_crtc_state(crtc->state),
3504                                             plane_state);
3505         }
3506 }
3507
3508 static int
3509 __intel_display_resume(struct drm_device *dev,
3510                        struct drm_atomic_state *state)
3511 {
3512         struct drm_crtc_state *crtc_state;
3513         struct drm_crtc *crtc;
3514         int i, ret;
3515
3516         intel_modeset_setup_hw_state(dev);
3517         i915_redisable_vga(dev);
3518
3519         if (!state)
3520                 return 0;
3521
3522         for_each_crtc_in_state(state, crtc, crtc_state, i) {
3523                 /*
3524                  * Force recalculation even if we restore
3525                  * current state. With fast modeset this may not result
3526                  * in a modeset when the state is compatible.
3527                  */
3528                 crtc_state->mode_changed = true;
3529         }
3530
3531         /* ignore any reset values/BIOS leftovers in the WM registers */
3532         to_intel_atomic_state(state)->skip_intermediate_wm = true;
3533
3534         ret = drm_atomic_commit(state);
3535
3536         WARN_ON(ret == -EDEADLK);
3537         return ret;
3538 }
3539
3540 static bool gpu_reset_clobbers_display(struct drm_i915_private *dev_priv)
3541 {
3542         return intel_has_gpu_reset(dev_priv) &&
3543                 INTEL_GEN(dev_priv) < 5 && !IS_G4X(dev_priv);
3544 }
3545
3546 void intel_prepare_reset(struct drm_i915_private *dev_priv)
3547 {
3548         struct drm_device *dev = &dev_priv->drm;
3549         struct drm_modeset_acquire_ctx *ctx = &dev_priv->reset_ctx;
3550         struct drm_atomic_state *state;
3551         int ret;
3552
3553         /*
3554          * Need mode_config.mutex so that we don't
3555          * trample ongoing ->detect() and whatnot.
3556          */
3557         mutex_lock(&dev->mode_config.mutex);
3558         drm_modeset_acquire_init(ctx, 0);
3559         while (1) {
3560                 ret = drm_modeset_lock_all_ctx(dev, ctx);
3561                 if (ret != -EDEADLK)
3562                         break;
3563
3564                 drm_modeset_backoff(ctx);
3565         }
3566
3567         /* reset doesn't touch the display, but flips might get nuked anyway, */
3568         if (!i915.force_reset_modeset_test &&
3569             !gpu_reset_clobbers_display(dev_priv))
3570                 return;
3571
3572         /*
3573          * Disabling the crtcs gracefully seems nicer. Also the
3574          * g33 docs say we should at least disable all the planes.
3575          */
3576         state = drm_atomic_helper_duplicate_state(dev, ctx);
3577         if (IS_ERR(state)) {
3578                 ret = PTR_ERR(state);
3579                 state = NULL;
3580                 DRM_ERROR("Duplicating state failed with %i\n", ret);
3581                 goto err;
3582         }
3583
3584         ret = drm_atomic_helper_disable_all(dev, ctx);
3585         if (ret) {
3586                 DRM_ERROR("Suspending crtc's failed with %i\n", ret);
3587                 goto err;
3588         }
3589
3590         dev_priv->modeset_restore_state = state;
3591         state->acquire_ctx = ctx;
3592         return;
3593
3594 err:
3595         drm_atomic_state_free(state);
3596 }
3597
3598 void intel_finish_reset(struct drm_i915_private *dev_priv)
3599 {
3600         struct drm_device *dev = &dev_priv->drm;
3601         struct drm_modeset_acquire_ctx *ctx = &dev_priv->reset_ctx;
3602         struct drm_atomic_state *state = dev_priv->modeset_restore_state;
3603         int ret;
3604
3605         /*
3606          * Flips in the rings will be nuked by the reset,
3607          * so complete all pending flips so that user space
3608          * will get its events and not get stuck.
3609          */
3610         intel_complete_page_flips(dev_priv);
3611
3612         dev_priv->modeset_restore_state = NULL;
3613
3614         dev_priv->modeset_restore_state = NULL;
3615
3616         /* reset doesn't touch the display */
3617         if (!gpu_reset_clobbers_display(dev_priv)) {
3618                 if (!state) {
3619                         /*
3620                          * Flips in the rings have been nuked by the reset,
3621                          * so update the base address of all primary
3622                          * planes to the the last fb to make sure we're
3623                          * showing the correct fb after a reset.
3624                          *
3625                          * FIXME: Atomic will make this obsolete since we won't schedule
3626                          * CS-based flips (which might get lost in gpu resets) any more.
3627                          */
3628                         intel_update_primary_planes(dev);
3629                 } else {
3630                         ret = __intel_display_resume(dev, state);
3631                         if (ret)
3632                                 DRM_ERROR("Restoring old state failed with %i\n", ret);
3633                 }
3634         } else {
3635                 /*
3636                  * The display has been reset as well,
3637                  * so need a full re-initialization.
3638                  */
3639                 intel_runtime_pm_disable_interrupts(dev_priv);
3640                 intel_runtime_pm_enable_interrupts(dev_priv);
3641
3642                 intel_pps_unlock_regs_wa(dev_priv);
3643                 intel_modeset_init_hw(dev);
3644
3645                 spin_lock_irq(&dev_priv->irq_lock);
3646                 if (dev_priv->display.hpd_irq_setup)
3647                         dev_priv->display.hpd_irq_setup(dev_priv);
3648                 spin_unlock_irq(&dev_priv->irq_lock);
3649
3650                 ret = __intel_display_resume(dev, state);
3651                 if (ret)
3652                         DRM_ERROR("Restoring old state failed with %i\n", ret);
3653
3654                 intel_hpd_init(dev_priv);
3655         }
3656
3657         drm_modeset_drop_locks(ctx);
3658         drm_modeset_acquire_fini(ctx);
3659         mutex_unlock(&dev->mode_config.mutex);
3660 }
3661
3662 static bool abort_flip_on_reset(struct intel_crtc *crtc)
3663 {
3664         struct i915_gpu_error *error = &to_i915(crtc->base.dev)->gpu_error;
3665
3666         if (i915_reset_in_progress(error))
3667                 return true;
3668
3669         if (crtc->reset_count != i915_reset_count(error))
3670                 return true;
3671
3672         return false;
3673 }
3674
3675 static bool intel_crtc_has_pending_flip(struct drm_crtc *crtc)
3676 {
3677         struct drm_device *dev = crtc->dev;
3678         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3679         bool pending;
3680
3681         if (abort_flip_on_reset(intel_crtc))
3682                 return false;
3683
3684         spin_lock_irq(&dev->event_lock);
3685         pending = to_intel_crtc(crtc)->flip_work != NULL;
3686         spin_unlock_irq(&dev->event_lock);
3687
3688         return pending;
3689 }
3690
3691 static void intel_update_pipe_config(struct intel_crtc *crtc,
3692                                      struct intel_crtc_state *old_crtc_state)
3693 {
3694         struct drm_device *dev = crtc->base.dev;
3695         struct drm_i915_private *dev_priv = to_i915(dev);
3696         struct intel_crtc_state *pipe_config =
3697                 to_intel_crtc_state(crtc->base.state);
3698
3699         /* drm_atomic_helper_update_legacy_modeset_state might not be called. */
3700         crtc->base.mode = crtc->base.state->mode;
3701
3702         /*
3703          * Update pipe size and adjust fitter if needed: the reason for this is
3704          * that in compute_mode_changes we check the native mode (not the pfit
3705          * mode) to see if we can flip rather than do a full mode set. In the
3706          * fastboot case, we'll flip, but if we don't update the pipesrc and
3707          * pfit state, we'll end up with a big fb scanned out into the wrong
3708          * sized surface.
3709          */
3710
3711         I915_WRITE(PIPESRC(crtc->pipe),
3712                    ((pipe_config->pipe_src_w - 1) << 16) |
3713                    (pipe_config->pipe_src_h - 1));
3714
3715         /* on skylake this is done by detaching scalers */
3716         if (INTEL_INFO(dev)->gen >= 9) {
3717                 skl_detach_scalers(crtc);
3718
3719                 if (pipe_config->pch_pfit.enabled)
3720                         skylake_pfit_enable(crtc);
3721         } else if (HAS_PCH_SPLIT(dev)) {
3722                 if (pipe_config->pch_pfit.enabled)
3723                         ironlake_pfit_enable(crtc);
3724                 else if (old_crtc_state->pch_pfit.enabled)
3725                         ironlake_pfit_disable(crtc, true);
3726         }
3727 }
3728
3729 static void intel_fdi_normal_train(struct drm_crtc *crtc)
3730 {
3731         struct drm_device *dev = crtc->dev;
3732         struct drm_i915_private *dev_priv = to_i915(dev);
3733         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3734         int pipe = intel_crtc->pipe;
3735         i915_reg_t reg;
3736         u32 temp;
3737
3738         /* enable normal train */
3739         reg = FDI_TX_CTL(pipe);
3740         temp = I915_READ(reg);
3741         if (IS_IVYBRIDGE(dev)) {
3742                 temp &= ~FDI_LINK_TRAIN_NONE_IVB;
3743                 temp |= FDI_LINK_TRAIN_NONE_IVB | FDI_TX_ENHANCE_FRAME_ENABLE;
3744         } else {
3745                 temp &= ~FDI_LINK_TRAIN_NONE;
3746                 temp |= FDI_LINK_TRAIN_NONE | FDI_TX_ENHANCE_FRAME_ENABLE;
3747         }
3748         I915_WRITE(reg, temp);
3749
3750         reg = FDI_RX_CTL(pipe);
3751         temp = I915_READ(reg);
3752         if (HAS_PCH_CPT(dev)) {
3753                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
3754                 temp |= FDI_LINK_TRAIN_NORMAL_CPT;
3755         } else {
3756                 temp &= ~FDI_LINK_TRAIN_NONE;
3757                 temp |= FDI_LINK_TRAIN_NONE;
3758         }
3759         I915_WRITE(reg, temp | FDI_RX_ENHANCE_FRAME_ENABLE);
3760
3761         /* wait one idle pattern time */
3762         POSTING_READ(reg);
3763         udelay(1000);
3764
3765         /* IVB wants error correction enabled */
3766         if (IS_IVYBRIDGE(dev))
3767                 I915_WRITE(reg, I915_READ(reg) | FDI_FS_ERRC_ENABLE |
3768                            FDI_FE_ERRC_ENABLE);
3769 }
3770
3771 /* The FDI link training functions for ILK/Ibexpeak. */
3772 static void ironlake_fdi_link_train(struct drm_crtc *crtc)
3773 {
3774         struct drm_device *dev = crtc->dev;
3775         struct drm_i915_private *dev_priv = to_i915(dev);
3776         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3777         int pipe = intel_crtc->pipe;
3778         i915_reg_t reg;
3779         u32 temp, tries;
3780
3781         /* FDI needs bits from pipe first */
3782         assert_pipe_enabled(dev_priv, pipe);
3783
3784         /* Train 1: umask FDI RX Interrupt symbol_lock and bit_lock bit
3785            for train result */
3786         reg = FDI_RX_IMR(pipe);
3787         temp = I915_READ(reg);
3788         temp &= ~FDI_RX_SYMBOL_LOCK;
3789         temp &= ~FDI_RX_BIT_LOCK;
3790         I915_WRITE(reg, temp);
3791         I915_READ(reg);
3792         udelay(150);
3793
3794         /* enable CPU FDI TX and PCH FDI RX */
3795         reg = FDI_TX_CTL(pipe);
3796         temp = I915_READ(reg);
3797         temp &= ~FDI_DP_PORT_WIDTH_MASK;
3798         temp |= FDI_DP_PORT_WIDTH(intel_crtc->config->fdi_lanes);
3799         temp &= ~FDI_LINK_TRAIN_NONE;
3800         temp |= FDI_LINK_TRAIN_PATTERN_1;
3801         I915_WRITE(reg, temp | FDI_TX_ENABLE);
3802
3803         reg = FDI_RX_CTL(pipe);
3804         temp = I915_READ(reg);
3805         temp &= ~FDI_LINK_TRAIN_NONE;
3806         temp |= FDI_LINK_TRAIN_PATTERN_1;
3807         I915_WRITE(reg, temp | FDI_RX_ENABLE);
3808
3809         POSTING_READ(reg);
3810         udelay(150);
3811
3812         /* Ironlake workaround, enable clock pointer after FDI enable*/
3813         I915_WRITE(FDI_RX_CHICKEN(pipe), FDI_RX_PHASE_SYNC_POINTER_OVR);
3814         I915_WRITE(FDI_RX_CHICKEN(pipe), FDI_RX_PHASE_SYNC_POINTER_OVR |
3815                    FDI_RX_PHASE_SYNC_POINTER_EN);
3816
3817         reg = FDI_RX_IIR(pipe);
3818         for (tries = 0; tries < 5; tries++) {
3819                 temp = I915_READ(reg);
3820                 DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
3821
3822                 if ((temp & FDI_RX_BIT_LOCK)) {
3823                         DRM_DEBUG_KMS("FDI train 1 done.\n");
3824                         I915_WRITE(reg, temp | FDI_RX_BIT_LOCK);
3825                         break;
3826                 }
3827         }
3828         if (tries == 5)
3829                 DRM_ERROR("FDI train 1 fail!\n");
3830
3831         /* Train 2 */
3832         reg = FDI_TX_CTL(pipe);
3833         temp = I915_READ(reg);
3834         temp &= ~FDI_LINK_TRAIN_NONE;
3835         temp |= FDI_LINK_TRAIN_PATTERN_2;
3836         I915_WRITE(reg, temp);
3837
3838         reg = FDI_RX_CTL(pipe);
3839         temp = I915_READ(reg);
3840         temp &= ~FDI_LINK_TRAIN_NONE;
3841         temp |= FDI_LINK_TRAIN_PATTERN_2;
3842         I915_WRITE(reg, temp);
3843
3844         POSTING_READ(reg);
3845         udelay(150);
3846
3847         reg = FDI_RX_IIR(pipe);
3848         for (tries = 0; tries < 5; tries++) {
3849                 temp = I915_READ(reg);
3850                 DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
3851
3852                 if (temp & FDI_RX_SYMBOL_LOCK) {
3853                         I915_WRITE(reg, temp | FDI_RX_SYMBOL_LOCK);
3854                         DRM_DEBUG_KMS("FDI train 2 done.\n");
3855                         break;
3856                 }
3857         }
3858         if (tries == 5)
3859                 DRM_ERROR("FDI train 2 fail!\n");
3860
3861         DRM_DEBUG_KMS("FDI train done\n");
3862
3863 }
3864
3865 static const int snb_b_fdi_train_param[] = {
3866         FDI_LINK_TRAIN_400MV_0DB_SNB_B,
3867         FDI_LINK_TRAIN_400MV_6DB_SNB_B,
3868         FDI_LINK_TRAIN_600MV_3_5DB_SNB_B,
3869         FDI_LINK_TRAIN_800MV_0DB_SNB_B,
3870 };
3871
3872 /* The FDI link training functions for SNB/Cougarpoint. */
3873 static void gen6_fdi_link_train(struct drm_crtc *crtc)
3874 {
3875         struct drm_device *dev = crtc->dev;
3876         struct drm_i915_private *dev_priv = to_i915(dev);
3877         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3878         int pipe = intel_crtc->pipe;
3879         i915_reg_t reg;
3880         u32 temp, i, retry;
3881
3882         /* Train 1: umask FDI RX Interrupt symbol_lock and bit_lock bit
3883            for train result */
3884         reg = FDI_RX_IMR(pipe);
3885         temp = I915_READ(reg);
3886         temp &= ~FDI_RX_SYMBOL_LOCK;
3887         temp &= ~FDI_RX_BIT_LOCK;
3888         I915_WRITE(reg, temp);
3889
3890         POSTING_READ(reg);
3891         udelay(150);
3892
3893         /* enable CPU FDI TX and PCH FDI RX */
3894         reg = FDI_TX_CTL(pipe);
3895         temp = I915_READ(reg);
3896         temp &= ~FDI_DP_PORT_WIDTH_MASK;
3897         temp |= FDI_DP_PORT_WIDTH(intel_crtc->config->fdi_lanes);
3898         temp &= ~FDI_LINK_TRAIN_NONE;
3899         temp |= FDI_LINK_TRAIN_PATTERN_1;
3900         temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
3901         /* SNB-B */
3902         temp |= FDI_LINK_TRAIN_400MV_0DB_SNB_B;
3903         I915_WRITE(reg, temp | FDI_TX_ENABLE);
3904
3905         I915_WRITE(FDI_RX_MISC(pipe),
3906                    FDI_RX_TP1_TO_TP2_48 | FDI_RX_FDI_DELAY_90);
3907
3908         reg = FDI_RX_CTL(pipe);
3909         temp = I915_READ(reg);
3910         if (HAS_PCH_CPT(dev)) {
3911                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
3912                 temp |= FDI_LINK_TRAIN_PATTERN_1_CPT;
3913         } else {
3914                 temp &= ~FDI_LINK_TRAIN_NONE;
3915                 temp |= FDI_LINK_TRAIN_PATTERN_1;
3916         }
3917         I915_WRITE(reg, temp | FDI_RX_ENABLE);
3918
3919         POSTING_READ(reg);
3920         udelay(150);
3921
3922         for (i = 0; i < 4; i++) {
3923                 reg = FDI_TX_CTL(pipe);
3924                 temp = I915_READ(reg);
3925                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
3926                 temp |= snb_b_fdi_train_param[i];
3927                 I915_WRITE(reg, temp);
3928
3929                 POSTING_READ(reg);
3930                 udelay(500);
3931
3932                 for (retry = 0; retry < 5; retry++) {
3933                         reg = FDI_RX_IIR(pipe);
3934                         temp = I915_READ(reg);
3935                         DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
3936                         if (temp & FDI_RX_BIT_LOCK) {
3937                                 I915_WRITE(reg, temp | FDI_RX_BIT_LOCK);
3938                                 DRM_DEBUG_KMS("FDI train 1 done.\n");
3939                                 break;
3940                         }
3941                         udelay(50);
3942                 }
3943                 if (retry < 5)
3944                         break;
3945         }
3946         if (i == 4)
3947                 DRM_ERROR("FDI train 1 fail!\n");
3948
3949         /* Train 2 */
3950         reg = FDI_TX_CTL(pipe);
3951         temp = I915_READ(reg);
3952         temp &= ~FDI_LINK_TRAIN_NONE;
3953         temp |= FDI_LINK_TRAIN_PATTERN_2;
3954         if (IS_GEN6(dev)) {
3955                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
3956                 /* SNB-B */
3957                 temp |= FDI_LINK_TRAIN_400MV_0DB_SNB_B;
3958         }
3959         I915_WRITE(reg, temp);
3960
3961         reg = FDI_RX_CTL(pipe);
3962         temp = I915_READ(reg);
3963         if (HAS_PCH_CPT(dev)) {
3964                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
3965                 temp |= FDI_LINK_TRAIN_PATTERN_2_CPT;
3966         } else {
3967                 temp &= ~FDI_LINK_TRAIN_NONE;
3968                 temp |= FDI_LINK_TRAIN_PATTERN_2;
3969         }
3970         I915_WRITE(reg, temp);
3971
3972         POSTING_READ(reg);
3973         udelay(150);
3974
3975         for (i = 0; i < 4; i++) {
3976                 reg = FDI_TX_CTL(pipe);
3977                 temp = I915_READ(reg);
3978                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
3979                 temp |= snb_b_fdi_train_param[i];
3980                 I915_WRITE(reg, temp);
3981
3982                 POSTING_READ(reg);
3983                 udelay(500);
3984
3985                 for (retry = 0; retry < 5; retry++) {
3986                         reg = FDI_RX_IIR(pipe);
3987                         temp = I915_READ(reg);
3988                         DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
3989                         if (temp & FDI_RX_SYMBOL_LOCK) {
3990                                 I915_WRITE(reg, temp | FDI_RX_SYMBOL_LOCK);
3991                                 DRM_DEBUG_KMS("FDI train 2 done.\n");
3992                                 break;
3993                         }
3994                         udelay(50);
3995                 }
3996                 if (retry < 5)
3997                         break;
3998         }
3999         if (i == 4)
4000                 DRM_ERROR("FDI train 2 fail!\n");
4001
4002         DRM_DEBUG_KMS("FDI train done.\n");
4003 }
4004
4005 /* Manual link training for Ivy Bridge A0 parts */
4006 static void ivb_manual_fdi_link_train(struct drm_crtc *crtc)
4007 {
4008         struct drm_device *dev = crtc->dev;
4009         struct drm_i915_private *dev_priv = to_i915(dev);
4010         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4011         int pipe = intel_crtc->pipe;
4012         i915_reg_t reg;
4013         u32 temp, i, j;
4014
4015         /* Train 1: umask FDI RX Interrupt symbol_lock and bit_lock bit
4016            for train result */
4017         reg = FDI_RX_IMR(pipe);
4018         temp = I915_READ(reg);
4019         temp &= ~FDI_RX_SYMBOL_LOCK;
4020         temp &= ~FDI_RX_BIT_LOCK;
4021         I915_WRITE(reg, temp);
4022
4023         POSTING_READ(reg);
4024         udelay(150);
4025
4026         DRM_DEBUG_KMS("FDI_RX_IIR before link train 0x%x\n",
4027                       I915_READ(FDI_RX_IIR(pipe)));
4028
4029         /* Try each vswing and preemphasis setting twice before moving on */
4030         for (j = 0; j < ARRAY_SIZE(snb_b_fdi_train_param) * 2; j++) {
4031                 /* disable first in case we need to retry */
4032                 reg = FDI_TX_CTL(pipe);
4033                 temp = I915_READ(reg);
4034                 temp &= ~(FDI_LINK_TRAIN_AUTO | FDI_LINK_TRAIN_NONE_IVB);
4035                 temp &= ~FDI_TX_ENABLE;
4036                 I915_WRITE(reg, temp);
4037
4038                 reg = FDI_RX_CTL(pipe);
4039                 temp = I915_READ(reg);
4040                 temp &= ~FDI_LINK_TRAIN_AUTO;
4041                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
4042                 temp &= ~FDI_RX_ENABLE;
4043                 I915_WRITE(reg, temp);
4044
4045                 /* enable CPU FDI TX and PCH FDI RX */
4046                 reg = FDI_TX_CTL(pipe);
4047                 temp = I915_READ(reg);
4048                 temp &= ~FDI_DP_PORT_WIDTH_MASK;
4049                 temp |= FDI_DP_PORT_WIDTH(intel_crtc->config->fdi_lanes);
4050                 temp |= FDI_LINK_TRAIN_PATTERN_1_IVB;
4051                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
4052                 temp |= snb_b_fdi_train_param[j/2];
4053                 temp |= FDI_COMPOSITE_SYNC;
4054                 I915_WRITE(reg, temp | FDI_TX_ENABLE);
4055
4056                 I915_WRITE(FDI_RX_MISC(pipe),
4057                            FDI_RX_TP1_TO_TP2_48 | FDI_RX_FDI_DELAY_90);
4058
4059                 reg = FDI_RX_CTL(pipe);
4060                 temp = I915_READ(reg);
4061                 temp |= FDI_LINK_TRAIN_PATTERN_1_CPT;
4062                 temp |= FDI_COMPOSITE_SYNC;
4063                 I915_WRITE(reg, temp | FDI_RX_ENABLE);
4064
4065                 POSTING_READ(reg);
4066                 udelay(1); /* should be 0.5us */
4067
4068                 for (i = 0; i < 4; i++) {
4069                         reg = FDI_RX_IIR(pipe);
4070                         temp = I915_READ(reg);
4071                         DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
4072
4073                         if (temp & FDI_RX_BIT_LOCK ||
4074                             (I915_READ(reg) & FDI_RX_BIT_LOCK)) {
4075                                 I915_WRITE(reg, temp | FDI_RX_BIT_LOCK);
4076                                 DRM_DEBUG_KMS("FDI train 1 done, level %i.\n",
4077                                               i);
4078                                 break;
4079                         }
4080                         udelay(1); /* should be 0.5us */
4081                 }
4082                 if (i == 4) {
4083                         DRM_DEBUG_KMS("FDI train 1 fail on vswing %d\n", j / 2);
4084                         continue;
4085                 }
4086
4087                 /* Train 2 */
4088                 reg = FDI_TX_CTL(pipe);
4089                 temp = I915_READ(reg);
4090                 temp &= ~FDI_LINK_TRAIN_NONE_IVB;
4091                 temp |= FDI_LINK_TRAIN_PATTERN_2_IVB;
4092                 I915_WRITE(reg, temp);
4093
4094                 reg = FDI_RX_CTL(pipe);
4095                 temp = I915_READ(reg);
4096                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
4097                 temp |= FDI_LINK_TRAIN_PATTERN_2_CPT;
4098                 I915_WRITE(reg, temp);
4099
4100                 POSTING_READ(reg);
4101                 udelay(2); /* should be 1.5us */
4102
4103                 for (i = 0; i < 4; i++) {
4104                         reg = FDI_RX_IIR(pipe);
4105                         temp = I915_READ(reg);
4106                         DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
4107
4108                         if (temp & FDI_RX_SYMBOL_LOCK ||
4109                             (I915_READ(reg) & FDI_RX_SYMBOL_LOCK)) {
4110                                 I915_WRITE(reg, temp | FDI_RX_SYMBOL_LOCK);
4111                                 DRM_DEBUG_KMS("FDI train 2 done, level %i.\n",
4112                                               i);
4113                                 goto train_done;
4114                         }
4115                         udelay(2); /* should be 1.5us */
4116                 }
4117                 if (i == 4)
4118                         DRM_DEBUG_KMS("FDI train 2 fail on vswing %d\n", j / 2);
4119         }
4120
4121 train_done:
4122         DRM_DEBUG_KMS("FDI train done.\n");
4123 }
4124
4125 static void ironlake_fdi_pll_enable(struct intel_crtc *intel_crtc)
4126 {
4127         struct drm_device *dev = intel_crtc->base.dev;
4128         struct drm_i915_private *dev_priv = to_i915(dev);
4129         int pipe = intel_crtc->pipe;
4130         i915_reg_t reg;
4131         u32 temp;
4132
4133         /* enable PCH FDI RX PLL, wait warmup plus DMI latency */
4134         reg = FDI_RX_CTL(pipe);
4135         temp = I915_READ(reg);
4136         temp &= ~(FDI_DP_PORT_WIDTH_MASK | (0x7 << 16));
4137         temp |= FDI_DP_PORT_WIDTH(intel_crtc->config->fdi_lanes);
4138         temp |= (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) << 11;
4139         I915_WRITE(reg, temp | FDI_RX_PLL_ENABLE);
4140
4141         POSTING_READ(reg);
4142         udelay(200);
4143
4144         /* Switch from Rawclk to PCDclk */
4145         temp = I915_READ(reg);
4146         I915_WRITE(reg, temp | FDI_PCDCLK);
4147
4148         POSTING_READ(reg);
4149         udelay(200);
4150
4151         /* Enable CPU FDI TX PLL, always on for Ironlake */
4152         reg = FDI_TX_CTL(pipe);
4153         temp = I915_READ(reg);
4154         if ((temp & FDI_TX_PLL_ENABLE) == 0) {
4155                 I915_WRITE(reg, temp | FDI_TX_PLL_ENABLE);
4156
4157                 POSTING_READ(reg);
4158                 udelay(100);
4159         }
4160 }
4161
4162 static void ironlake_fdi_pll_disable(struct intel_crtc *intel_crtc)
4163 {
4164         struct drm_device *dev = intel_crtc->base.dev;
4165         struct drm_i915_private *dev_priv = to_i915(dev);
4166         int pipe = intel_crtc->pipe;
4167         i915_reg_t reg;
4168         u32 temp;
4169
4170         /* Switch from PCDclk to Rawclk */
4171         reg = FDI_RX_CTL(pipe);
4172         temp = I915_READ(reg);
4173         I915_WRITE(reg, temp & ~FDI_PCDCLK);
4174
4175         /* Disable CPU FDI TX PLL */
4176         reg = FDI_TX_CTL(pipe);
4177         temp = I915_READ(reg);
4178         I915_WRITE(reg, temp & ~FDI_TX_PLL_ENABLE);
4179
4180         POSTING_READ(reg);
4181         udelay(100);
4182
4183         reg = FDI_RX_CTL(pipe);
4184         temp = I915_READ(reg);
4185         I915_WRITE(reg, temp & ~FDI_RX_PLL_ENABLE);
4186
4187         /* Wait for the clocks to turn off. */
4188         POSTING_READ(reg);
4189         udelay(100);
4190 }
4191
4192 static void ironlake_fdi_disable(struct drm_crtc *crtc)
4193 {
4194         struct drm_device *dev = crtc->dev;
4195         struct drm_i915_private *dev_priv = to_i915(dev);
4196         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4197         int pipe = intel_crtc->pipe;
4198         i915_reg_t reg;
4199         u32 temp;
4200
4201         /* disable CPU FDI tx and PCH FDI rx */
4202         reg = FDI_TX_CTL(pipe);
4203         temp = I915_READ(reg);
4204         I915_WRITE(reg, temp & ~FDI_TX_ENABLE);
4205         POSTING_READ(reg);
4206
4207         reg = FDI_RX_CTL(pipe);
4208         temp = I915_READ(reg);
4209         temp &= ~(0x7 << 16);
4210         temp |= (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) << 11;
4211         I915_WRITE(reg, temp & ~FDI_RX_ENABLE);
4212
4213         POSTING_READ(reg);
4214         udelay(100);
4215
4216         /* Ironlake workaround, disable clock pointer after downing FDI */
4217         if (HAS_PCH_IBX(dev))
4218                 I915_WRITE(FDI_RX_CHICKEN(pipe), FDI_RX_PHASE_SYNC_POINTER_OVR);
4219
4220         /* still set train pattern 1 */
4221         reg = FDI_TX_CTL(pipe);
4222         temp = I915_READ(reg);
4223         temp &= ~FDI_LINK_TRAIN_NONE;
4224         temp |= FDI_LINK_TRAIN_PATTERN_1;
4225         I915_WRITE(reg, temp);
4226
4227         reg = FDI_RX_CTL(pipe);
4228         temp = I915_READ(reg);
4229         if (HAS_PCH_CPT(dev)) {
4230                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
4231                 temp |= FDI_LINK_TRAIN_PATTERN_1_CPT;
4232         } else {
4233                 temp &= ~FDI_LINK_TRAIN_NONE;
4234                 temp |= FDI_LINK_TRAIN_PATTERN_1;
4235         }
4236         /* BPC in FDI rx is consistent with that in PIPECONF */
4237         temp &= ~(0x07 << 16);
4238         temp |= (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) << 11;
4239         I915_WRITE(reg, temp);
4240
4241         POSTING_READ(reg);
4242         udelay(100);
4243 }
4244
4245 bool intel_has_pending_fb_unpin(struct drm_device *dev)
4246 {
4247         struct intel_crtc *crtc;
4248
4249         /* Note that we don't need to be called with mode_config.lock here
4250          * as our list of CRTC objects is static for the lifetime of the
4251          * device and so cannot disappear as we iterate. Similarly, we can
4252          * happily treat the predicates as racy, atomic checks as userspace
4253          * cannot claim and pin a new fb without at least acquring the
4254          * struct_mutex and so serialising with us.
4255          */
4256         for_each_intel_crtc(dev, crtc) {
4257                 if (atomic_read(&crtc->unpin_work_count) == 0)
4258                         continue;
4259
4260                 if (crtc->flip_work)
4261                         intel_wait_for_vblank(dev, crtc->pipe);
4262
4263                 return true;
4264         }
4265
4266         return false;
4267 }
4268
4269 static void page_flip_completed(struct intel_crtc *intel_crtc)
4270 {
4271         struct drm_i915_private *dev_priv = to_i915(intel_crtc->base.dev);
4272         struct intel_flip_work *work = intel_crtc->flip_work;
4273
4274         intel_crtc->flip_work = NULL;
4275
4276         if (work->event)
4277                 drm_crtc_send_vblank_event(&intel_crtc->base, work->event);
4278
4279         drm_crtc_vblank_put(&intel_crtc->base);
4280
4281         wake_up_all(&dev_priv->pending_flip_queue);
4282         trace_i915_flip_complete(intel_crtc->plane,
4283                                  work->pending_flip_obj);
4284
4285         queue_work(dev_priv->wq, &work->unpin_work);
4286 }
4287
4288 static int intel_crtc_wait_for_pending_flips(struct drm_crtc *crtc)
4289 {
4290         struct drm_device *dev = crtc->dev;
4291         struct drm_i915_private *dev_priv = to_i915(dev);
4292         long ret;
4293
4294         WARN_ON(waitqueue_active(&dev_priv->pending_flip_queue));
4295
4296         ret = wait_event_interruptible_timeout(
4297                                         dev_priv->pending_flip_queue,
4298                                         !intel_crtc_has_pending_flip(crtc),
4299                                         60*HZ);
4300
4301         if (ret < 0)
4302                 return ret;
4303
4304         if (ret == 0) {
4305                 struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4306                 struct intel_flip_work *work;
4307
4308                 spin_lock_irq(&dev->event_lock);
4309                 work = intel_crtc->flip_work;
4310                 if (work && !is_mmio_work(work)) {
4311                         WARN_ONCE(1, "Removing stuck page flip\n");
4312                         page_flip_completed(intel_crtc);
4313                 }
4314                 spin_unlock_irq(&dev->event_lock);
4315         }
4316
4317         return 0;
4318 }
4319
4320 void lpt_disable_iclkip(struct drm_i915_private *dev_priv)
4321 {
4322         u32 temp;
4323
4324         I915_WRITE(PIXCLK_GATE, PIXCLK_GATE_GATE);
4325
4326         mutex_lock(&dev_priv->sb_lock);
4327
4328         temp = intel_sbi_read(dev_priv, SBI_SSCCTL6, SBI_ICLK);
4329         temp |= SBI_SSCCTL_DISABLE;
4330         intel_sbi_write(dev_priv, SBI_SSCCTL6, temp, SBI_ICLK);
4331
4332         mutex_unlock(&dev_priv->sb_lock);
4333 }
4334
4335 /* Program iCLKIP clock to the desired frequency */
4336 static void lpt_program_iclkip(struct drm_crtc *crtc)
4337 {
4338         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
4339         int clock = to_intel_crtc(crtc)->config->base.adjusted_mode.crtc_clock;
4340         u32 divsel, phaseinc, auxdiv, phasedir = 0;
4341         u32 temp;
4342
4343         lpt_disable_iclkip(dev_priv);
4344
4345         /* The iCLK virtual clock root frequency is in MHz,
4346          * but the adjusted_mode->crtc_clock in in KHz. To get the
4347          * divisors, it is necessary to divide one by another, so we
4348          * convert the virtual clock precision to KHz here for higher
4349          * precision.
4350          */
4351         for (auxdiv = 0; auxdiv < 2; auxdiv++) {
4352                 u32 iclk_virtual_root_freq = 172800 * 1000;
4353                 u32 iclk_pi_range = 64;
4354                 u32 desired_divisor;
4355
4356                 desired_divisor = DIV_ROUND_CLOSEST(iclk_virtual_root_freq,
4357                                                     clock << auxdiv);
4358                 divsel = (desired_divisor / iclk_pi_range) - 2;
4359                 phaseinc = desired_divisor % iclk_pi_range;
4360
4361                 /*
4362                  * Near 20MHz is a corner case which is
4363                  * out of range for the 7-bit divisor
4364                  */
4365                 if (divsel <= 0x7f)
4366                         break;
4367         }
4368
4369         /* This should not happen with any sane values */
4370         WARN_ON(SBI_SSCDIVINTPHASE_DIVSEL(divsel) &
4371                 ~SBI_SSCDIVINTPHASE_DIVSEL_MASK);
4372         WARN_ON(SBI_SSCDIVINTPHASE_DIR(phasedir) &
4373                 ~SBI_SSCDIVINTPHASE_INCVAL_MASK);
4374
4375         DRM_DEBUG_KMS("iCLKIP clock: found settings for %dKHz refresh rate: auxdiv=%x, divsel=%x, phasedir=%x, phaseinc=%x\n",
4376                         clock,
4377                         auxdiv,
4378                         divsel,
4379                         phasedir,
4380                         phaseinc);
4381
4382         mutex_lock(&dev_priv->sb_lock);
4383
4384         /* Program SSCDIVINTPHASE6 */
4385         temp = intel_sbi_read(dev_priv, SBI_SSCDIVINTPHASE6, SBI_ICLK);
4386         temp &= ~SBI_SSCDIVINTPHASE_DIVSEL_MASK;
4387         temp |= SBI_SSCDIVINTPHASE_DIVSEL(divsel);
4388         temp &= ~SBI_SSCDIVINTPHASE_INCVAL_MASK;
4389         temp |= SBI_SSCDIVINTPHASE_INCVAL(phaseinc);
4390         temp |= SBI_SSCDIVINTPHASE_DIR(phasedir);
4391         temp |= SBI_SSCDIVINTPHASE_PROPAGATE;
4392         intel_sbi_write(dev_priv, SBI_SSCDIVINTPHASE6, temp, SBI_ICLK);
4393
4394         /* Program SSCAUXDIV */
4395         temp = intel_sbi_read(dev_priv, SBI_SSCAUXDIV6, SBI_ICLK);
4396         temp &= ~SBI_SSCAUXDIV_FINALDIV2SEL(1);
4397         temp |= SBI_SSCAUXDIV_FINALDIV2SEL(auxdiv);
4398         intel_sbi_write(dev_priv, SBI_SSCAUXDIV6, temp, SBI_ICLK);
4399
4400         /* Enable modulator and associated divider */
4401         temp = intel_sbi_read(dev_priv, SBI_SSCCTL6, SBI_ICLK);
4402         temp &= ~SBI_SSCCTL_DISABLE;
4403         intel_sbi_write(dev_priv, SBI_SSCCTL6, temp, SBI_ICLK);
4404
4405         mutex_unlock(&dev_priv->sb_lock);
4406
4407         /* Wait for initialization time */
4408         udelay(24);
4409
4410         I915_WRITE(PIXCLK_GATE, PIXCLK_GATE_UNGATE);
4411 }
4412
4413 int lpt_get_iclkip(struct drm_i915_private *dev_priv)
4414 {
4415         u32 divsel, phaseinc, auxdiv;
4416         u32 iclk_virtual_root_freq = 172800 * 1000;
4417         u32 iclk_pi_range = 64;
4418         u32 desired_divisor;
4419         u32 temp;
4420
4421         if ((I915_READ(PIXCLK_GATE) & PIXCLK_GATE_UNGATE) == 0)
4422                 return 0;
4423
4424         mutex_lock(&dev_priv->sb_lock);
4425
4426         temp = intel_sbi_read(dev_priv, SBI_SSCCTL6, SBI_ICLK);
4427         if (temp & SBI_SSCCTL_DISABLE) {
4428                 mutex_unlock(&dev_priv->sb_lock);
4429                 return 0;
4430         }
4431
4432         temp = intel_sbi_read(dev_priv, SBI_SSCDIVINTPHASE6, SBI_ICLK);
4433         divsel = (temp & SBI_SSCDIVINTPHASE_DIVSEL_MASK) >>
4434                 SBI_SSCDIVINTPHASE_DIVSEL_SHIFT;
4435         phaseinc = (temp & SBI_SSCDIVINTPHASE_INCVAL_MASK) >>
4436                 SBI_SSCDIVINTPHASE_INCVAL_SHIFT;
4437
4438         temp = intel_sbi_read(dev_priv, SBI_SSCAUXDIV6, SBI_ICLK);
4439         auxdiv = (temp & SBI_SSCAUXDIV_FINALDIV2SEL_MASK) >>
4440                 SBI_SSCAUXDIV_FINALDIV2SEL_SHIFT;
4441
4442         mutex_unlock(&dev_priv->sb_lock);
4443
4444         desired_divisor = (divsel + 2) * iclk_pi_range + phaseinc;
4445
4446         return DIV_ROUND_CLOSEST(iclk_virtual_root_freq,
4447                                  desired_divisor << auxdiv);
4448 }
4449
4450 static void ironlake_pch_transcoder_set_timings(struct intel_crtc *crtc,
4451                                                 enum pipe pch_transcoder)
4452 {
4453         struct drm_device *dev = crtc->base.dev;
4454         struct drm_i915_private *dev_priv = to_i915(dev);
4455         enum transcoder cpu_transcoder = crtc->config->cpu_transcoder;
4456
4457         I915_WRITE(PCH_TRANS_HTOTAL(pch_transcoder),
4458                    I915_READ(HTOTAL(cpu_transcoder)));
4459         I915_WRITE(PCH_TRANS_HBLANK(pch_transcoder),
4460                    I915_READ(HBLANK(cpu_transcoder)));
4461         I915_WRITE(PCH_TRANS_HSYNC(pch_transcoder),
4462                    I915_READ(HSYNC(cpu_transcoder)));
4463
4464         I915_WRITE(PCH_TRANS_VTOTAL(pch_transcoder),
4465                    I915_READ(VTOTAL(cpu_transcoder)));
4466         I915_WRITE(PCH_TRANS_VBLANK(pch_transcoder),
4467                    I915_READ(VBLANK(cpu_transcoder)));
4468         I915_WRITE(PCH_TRANS_VSYNC(pch_transcoder),
4469                    I915_READ(VSYNC(cpu_transcoder)));
4470         I915_WRITE(PCH_TRANS_VSYNCSHIFT(pch_transcoder),
4471                    I915_READ(VSYNCSHIFT(cpu_transcoder)));
4472 }
4473
4474 static void cpt_set_fdi_bc_bifurcation(struct drm_device *dev, bool enable)
4475 {
4476         struct drm_i915_private *dev_priv = to_i915(dev);
4477         uint32_t temp;
4478
4479         temp = I915_READ(SOUTH_CHICKEN1);
4480         if (!!(temp & FDI_BC_BIFURCATION_SELECT) == enable)
4481                 return;
4482
4483         WARN_ON(I915_READ(FDI_RX_CTL(PIPE_B)) & FDI_RX_ENABLE);
4484         WARN_ON(I915_READ(FDI_RX_CTL(PIPE_C)) & FDI_RX_ENABLE);
4485
4486         temp &= ~FDI_BC_BIFURCATION_SELECT;
4487         if (enable)
4488                 temp |= FDI_BC_BIFURCATION_SELECT;
4489
4490         DRM_DEBUG_KMS("%sabling fdi C rx\n", enable ? "en" : "dis");
4491         I915_WRITE(SOUTH_CHICKEN1, temp);
4492         POSTING_READ(SOUTH_CHICKEN1);
4493 }
4494
4495 static void ivybridge_update_fdi_bc_bifurcation(struct intel_crtc *intel_crtc)
4496 {
4497         struct drm_device *dev = intel_crtc->base.dev;
4498
4499         switch (intel_crtc->pipe) {
4500         case PIPE_A:
4501                 break;
4502         case PIPE_B:
4503                 if (intel_crtc->config->fdi_lanes > 2)
4504                         cpt_set_fdi_bc_bifurcation(dev, false);
4505                 else
4506                         cpt_set_fdi_bc_bifurcation(dev, true);
4507
4508                 break;
4509         case PIPE_C:
4510                 cpt_set_fdi_bc_bifurcation(dev, true);
4511
4512                 break;
4513         default:
4514                 BUG();
4515         }
4516 }
4517
4518 /* Return which DP Port should be selected for Transcoder DP control */
4519 static enum port
4520 intel_trans_dp_port_sel(struct drm_crtc *crtc)
4521 {
4522         struct drm_device *dev = crtc->dev;
4523         struct intel_encoder *encoder;
4524
4525         for_each_encoder_on_crtc(dev, crtc, encoder) {
4526                 if (encoder->type == INTEL_OUTPUT_DP ||
4527                     encoder->type == INTEL_OUTPUT_EDP)
4528                         return enc_to_dig_port(&encoder->base)->port;
4529         }
4530
4531         return -1;
4532 }
4533
4534 /*
4535  * Enable PCH resources required for PCH ports:
4536  *   - PCH PLLs
4537  *   - FDI training & RX/TX
4538  *   - update transcoder timings
4539  *   - DP transcoding bits
4540  *   - transcoder
4541  */
4542 static void ironlake_pch_enable(struct drm_crtc *crtc)
4543 {
4544         struct drm_device *dev = crtc->dev;
4545         struct drm_i915_private *dev_priv = to_i915(dev);
4546         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4547         int pipe = intel_crtc->pipe;
4548         u32 temp;
4549
4550         assert_pch_transcoder_disabled(dev_priv, pipe);
4551
4552         if (IS_IVYBRIDGE(dev))
4553                 ivybridge_update_fdi_bc_bifurcation(intel_crtc);
4554
4555         /* Write the TU size bits before fdi link training, so that error
4556          * detection works. */
4557         I915_WRITE(FDI_RX_TUSIZE1(pipe),
4558                    I915_READ(PIPE_DATA_M1(pipe)) & TU_SIZE_MASK);
4559
4560         /* For PCH output, training FDI link */
4561         dev_priv->display.fdi_link_train(crtc);
4562
4563         /* We need to program the right clock selection before writing the pixel
4564          * mutliplier into the DPLL. */
4565         if (HAS_PCH_CPT(dev)) {
4566                 u32 sel;
4567
4568                 temp = I915_READ(PCH_DPLL_SEL);
4569                 temp |= TRANS_DPLL_ENABLE(pipe);
4570                 sel = TRANS_DPLLB_SEL(pipe);
4571                 if (intel_crtc->config->shared_dpll ==
4572                     intel_get_shared_dpll_by_id(dev_priv, DPLL_ID_PCH_PLL_B))
4573                         temp |= sel;
4574                 else
4575                         temp &= ~sel;
4576                 I915_WRITE(PCH_DPLL_SEL, temp);
4577         }
4578
4579         /* XXX: pch pll's can be enabled any time before we enable the PCH
4580          * transcoder, and we actually should do this to not upset any PCH
4581          * transcoder that already use the clock when we share it.
4582          *
4583          * Note that enable_shared_dpll tries to do the right thing, but
4584          * get_shared_dpll unconditionally resets the pll - we need that to have
4585          * the right LVDS enable sequence. */
4586         intel_enable_shared_dpll(intel_crtc);
4587
4588         /* set transcoder timing, panel must allow it */
4589         assert_panel_unlocked(dev_priv, pipe);
4590         ironlake_pch_transcoder_set_timings(intel_crtc, pipe);
4591
4592         intel_fdi_normal_train(crtc);
4593
4594         /* For PCH DP, enable TRANS_DP_CTL */
4595         if (HAS_PCH_CPT(dev) && intel_crtc_has_dp_encoder(intel_crtc->config)) {
4596                 const struct drm_display_mode *adjusted_mode =
4597                         &intel_crtc->config->base.adjusted_mode;
4598                 u32 bpc = (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) >> 5;
4599                 i915_reg_t reg = TRANS_DP_CTL(pipe);
4600                 temp = I915_READ(reg);
4601                 temp &= ~(TRANS_DP_PORT_SEL_MASK |
4602                           TRANS_DP_SYNC_MASK |
4603                           TRANS_DP_BPC_MASK);
4604                 temp |= TRANS_DP_OUTPUT_ENABLE;
4605                 temp |= bpc << 9; /* same format but at 11:9 */
4606
4607                 if (adjusted_mode->flags & DRM_MODE_FLAG_PHSYNC)
4608                         temp |= TRANS_DP_HSYNC_ACTIVE_HIGH;
4609                 if (adjusted_mode->flags & DRM_MODE_FLAG_PVSYNC)
4610                         temp |= TRANS_DP_VSYNC_ACTIVE_HIGH;
4611
4612                 switch (intel_trans_dp_port_sel(crtc)) {
4613                 case PORT_B:
4614                         temp |= TRANS_DP_PORT_SEL_B;
4615                         break;
4616                 case PORT_C:
4617                         temp |= TRANS_DP_PORT_SEL_C;
4618                         break;
4619                 case PORT_D:
4620                         temp |= TRANS_DP_PORT_SEL_D;
4621                         break;
4622                 default:
4623                         BUG();
4624                 }
4625
4626                 I915_WRITE(reg, temp);
4627         }
4628
4629         ironlake_enable_pch_transcoder(dev_priv, pipe);
4630 }
4631
4632 static void lpt_pch_enable(struct drm_crtc *crtc)
4633 {
4634         struct drm_device *dev = crtc->dev;
4635         struct drm_i915_private *dev_priv = to_i915(dev);
4636         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4637         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
4638
4639         assert_pch_transcoder_disabled(dev_priv, PIPE_A);
4640
4641         lpt_program_iclkip(crtc);
4642
4643         /* Set transcoder timing. */
4644         ironlake_pch_transcoder_set_timings(intel_crtc, PIPE_A);
4645
4646         lpt_enable_pch_transcoder(dev_priv, cpu_transcoder);
4647 }
4648
4649 static void cpt_verify_modeset(struct drm_device *dev, int pipe)
4650 {
4651         struct drm_i915_private *dev_priv = to_i915(dev);
4652         i915_reg_t dslreg = PIPEDSL(pipe);
4653         u32 temp;
4654
4655         temp = I915_READ(dslreg);
4656         udelay(500);
4657         if (wait_for(I915_READ(dslreg) != temp, 5)) {
4658                 if (wait_for(I915_READ(dslreg) != temp, 5))
4659                         DRM_ERROR("mode set failed: pipe %c stuck\n", pipe_name(pipe));
4660         }
4661 }
4662
4663 static int
4664 skl_update_scaler(struct intel_crtc_state *crtc_state, bool force_detach,
4665                   unsigned scaler_user, int *scaler_id, unsigned int rotation,
4666                   int src_w, int src_h, int dst_w, int dst_h)
4667 {
4668         struct intel_crtc_scaler_state *scaler_state =
4669                 &crtc_state->scaler_state;
4670         struct intel_crtc *intel_crtc =
4671                 to_intel_crtc(crtc_state->base.crtc);
4672         int need_scaling;
4673
4674         need_scaling = intel_rotation_90_or_270(rotation) ?
4675                 (src_h != dst_w || src_w != dst_h):
4676                 (src_w != dst_w || src_h != dst_h);
4677
4678         /*
4679          * if plane is being disabled or scaler is no more required or force detach
4680          *  - free scaler binded to this plane/crtc
4681          *  - in order to do this, update crtc->scaler_usage
4682          *
4683          * Here scaler state in crtc_state is set free so that
4684          * scaler can be assigned to other user. Actual register
4685          * update to free the scaler is done in plane/panel-fit programming.
4686          * For this purpose crtc/plane_state->scaler_id isn't reset here.
4687          */
4688         if (force_detach || !need_scaling) {
4689                 if (*scaler_id >= 0) {
4690                         scaler_state->scaler_users &= ~(1 << scaler_user);
4691                         scaler_state->scalers[*scaler_id].in_use = 0;
4692
4693                         DRM_DEBUG_KMS("scaler_user index %u.%u: "
4694                                 "Staged freeing scaler id %d scaler_users = 0x%x\n",
4695                                 intel_crtc->pipe, scaler_user, *scaler_id,
4696                                 scaler_state->scaler_users);
4697                         *scaler_id = -1;
4698                 }
4699                 return 0;
4700         }
4701
4702         /* range checks */
4703         if (src_w < SKL_MIN_SRC_W || src_h < SKL_MIN_SRC_H ||
4704                 dst_w < SKL_MIN_DST_W || dst_h < SKL_MIN_DST_H ||
4705
4706                 src_w > SKL_MAX_SRC_W || src_h > SKL_MAX_SRC_H ||
4707                 dst_w > SKL_MAX_DST_W || dst_h > SKL_MAX_DST_H) {
4708                 DRM_DEBUG_KMS("scaler_user index %u.%u: src %ux%u dst %ux%u "
4709                         "size is out of scaler range\n",
4710                         intel_crtc->pipe, scaler_user, src_w, src_h, dst_w, dst_h);
4711                 return -EINVAL;
4712         }
4713
4714         /* mark this plane as a scaler user in crtc_state */
4715         scaler_state->scaler_users |= (1 << scaler_user);
4716         DRM_DEBUG_KMS("scaler_user index %u.%u: "
4717                 "staged scaling request for %ux%u->%ux%u scaler_users = 0x%x\n",
4718                 intel_crtc->pipe, scaler_user, src_w, src_h, dst_w, dst_h,
4719                 scaler_state->scaler_users);
4720
4721         return 0;
4722 }
4723
4724 /**
4725  * skl_update_scaler_crtc - Stages update to scaler state for a given crtc.
4726  *
4727  * @state: crtc's scaler state
4728  *
4729  * Return
4730  *     0 - scaler_usage updated successfully
4731  *    error - requested scaling cannot be supported or other error condition
4732  */
4733 int skl_update_scaler_crtc(struct intel_crtc_state *state)
4734 {
4735         struct intel_crtc *intel_crtc = to_intel_crtc(state->base.crtc);
4736         const struct drm_display_mode *adjusted_mode = &state->base.adjusted_mode;
4737
4738         DRM_DEBUG_KMS("Updating scaler for [CRTC:%d:%s] scaler_user index %u.%u\n",
4739                       intel_crtc->base.base.id, intel_crtc->base.name,
4740                       intel_crtc->pipe, SKL_CRTC_INDEX);
4741
4742         return skl_update_scaler(state, !state->base.active, SKL_CRTC_INDEX,
4743                 &state->scaler_state.scaler_id, DRM_ROTATE_0,
4744                 state->pipe_src_w, state->pipe_src_h,
4745                 adjusted_mode->crtc_hdisplay, adjusted_mode->crtc_vdisplay);
4746 }
4747
4748 /**
4749  * skl_update_scaler_plane - Stages update to scaler state for a given plane.
4750  *
4751  * @state: crtc's scaler state
4752  * @plane_state: atomic plane state to update
4753  *
4754  * Return
4755  *     0 - scaler_usage updated successfully
4756  *    error - requested scaling cannot be supported or other error condition
4757  */
4758 static int skl_update_scaler_plane(struct intel_crtc_state *crtc_state,
4759                                    struct intel_plane_state *plane_state)
4760 {
4761
4762         struct intel_crtc *intel_crtc = to_intel_crtc(crtc_state->base.crtc);
4763         struct intel_plane *intel_plane =
4764                 to_intel_plane(plane_state->base.plane);
4765         struct drm_framebuffer *fb = plane_state->base.fb;
4766         int ret;
4767
4768         bool force_detach = !fb || !plane_state->base.visible;
4769
4770         DRM_DEBUG_KMS("Updating scaler for [PLANE:%d:%s] scaler_user index %u.%u\n",
4771                       intel_plane->base.base.id, intel_plane->base.name,
4772                       intel_crtc->pipe, drm_plane_index(&intel_plane->base));
4773
4774         ret = skl_update_scaler(crtc_state, force_detach,
4775                                 drm_plane_index(&intel_plane->base),
4776                                 &plane_state->scaler_id,
4777                                 plane_state->base.rotation,
4778                                 drm_rect_width(&plane_state->base.src) >> 16,
4779                                 drm_rect_height(&plane_state->base.src) >> 16,
4780                                 drm_rect_width(&plane_state->base.dst),
4781                                 drm_rect_height(&plane_state->base.dst));
4782
4783         if (ret || plane_state->scaler_id < 0)
4784                 return ret;
4785
4786         /* check colorkey */
4787         if (plane_state->ckey.flags != I915_SET_COLORKEY_NONE) {
4788                 DRM_DEBUG_KMS("[PLANE:%d:%s] scaling with color key not allowed",
4789                               intel_plane->base.base.id,
4790                               intel_plane->base.name);
4791                 return -EINVAL;
4792         }
4793
4794         /* Check src format */
4795         switch (fb->pixel_format) {
4796         case DRM_FORMAT_RGB565:
4797         case DRM_FORMAT_XBGR8888:
4798         case DRM_FORMAT_XRGB8888:
4799         case DRM_FORMAT_ABGR8888:
4800         case DRM_FORMAT_ARGB8888:
4801         case DRM_FORMAT_XRGB2101010:
4802         case DRM_FORMAT_XBGR2101010:
4803         case DRM_FORMAT_YUYV:
4804         case DRM_FORMAT_YVYU:
4805         case DRM_FORMAT_UYVY:
4806         case DRM_FORMAT_VYUY:
4807                 break;
4808         default:
4809                 DRM_DEBUG_KMS("[PLANE:%d:%s] FB:%d unsupported scaling format 0x%x\n",
4810                               intel_plane->base.base.id, intel_plane->base.name,
4811                               fb->base.id, fb->pixel_format);
4812                 return -EINVAL;
4813         }
4814
4815         return 0;
4816 }
4817
4818 static void skylake_scaler_disable(struct intel_crtc *crtc)
4819 {
4820         int i;
4821
4822         for (i = 0; i < crtc->num_scalers; i++)
4823                 skl_detach_scaler(crtc, i);
4824 }
4825
4826 static void skylake_pfit_enable(struct intel_crtc *crtc)
4827 {
4828         struct drm_device *dev = crtc->base.dev;
4829         struct drm_i915_private *dev_priv = to_i915(dev);
4830         int pipe = crtc->pipe;
4831         struct intel_crtc_scaler_state *scaler_state =
4832                 &crtc->config->scaler_state;
4833
4834         if (crtc->config->pch_pfit.enabled) {
4835                 int id;
4836
4837                 if (WARN_ON(crtc->config->scaler_state.scaler_id < 0))
4838                         return;
4839
4840                 id = scaler_state->scaler_id;
4841                 I915_WRITE(SKL_PS_CTRL(pipe, id), PS_SCALER_EN |
4842                         PS_FILTER_MEDIUM | scaler_state->scalers[id].mode);
4843                 I915_WRITE(SKL_PS_WIN_POS(pipe, id), crtc->config->pch_pfit.pos);
4844                 I915_WRITE(SKL_PS_WIN_SZ(pipe, id), crtc->config->pch_pfit.size);
4845         }
4846 }
4847
4848 static void ironlake_pfit_enable(struct intel_crtc *crtc)
4849 {
4850         struct drm_device *dev = crtc->base.dev;
4851         struct drm_i915_private *dev_priv = to_i915(dev);
4852         int pipe = crtc->pipe;
4853
4854         if (crtc->config->pch_pfit.enabled) {
4855                 /* Force use of hard-coded filter coefficients
4856                  * as some pre-programmed values are broken,
4857                  * e.g. x201.
4858                  */
4859                 if (IS_IVYBRIDGE(dev) || IS_HASWELL(dev))
4860                         I915_WRITE(PF_CTL(pipe), PF_ENABLE | PF_FILTER_MED_3x3 |
4861                                                  PF_PIPE_SEL_IVB(pipe));
4862                 else
4863                         I915_WRITE(PF_CTL(pipe), PF_ENABLE | PF_FILTER_MED_3x3);
4864                 I915_WRITE(PF_WIN_POS(pipe), crtc->config->pch_pfit.pos);
4865                 I915_WRITE(PF_WIN_SZ(pipe), crtc->config->pch_pfit.size);
4866         }
4867 }
4868
4869 void hsw_enable_ips(struct intel_crtc *crtc)
4870 {
4871         struct drm_device *dev = crtc->base.dev;
4872         struct drm_i915_private *dev_priv = to_i915(dev);
4873
4874         if (!crtc->config->ips_enabled)
4875                 return;
4876
4877         /*
4878          * We can only enable IPS after we enable a plane and wait for a vblank
4879          * This function is called from post_plane_update, which is run after
4880          * a vblank wait.
4881          */
4882
4883         assert_plane_enabled(dev_priv, crtc->plane);
4884         if (IS_BROADWELL(dev)) {
4885                 mutex_lock(&dev_priv->rps.hw_lock);
4886                 WARN_ON(sandybridge_pcode_write(dev_priv, DISPLAY_IPS_CONTROL, 0xc0000000));
4887                 mutex_unlock(&dev_priv->rps.hw_lock);
4888                 /* Quoting Art Runyan: "its not safe to expect any particular
4889                  * value in IPS_CTL bit 31 after enabling IPS through the
4890                  * mailbox." Moreover, the mailbox may return a bogus state,
4891                  * so we need to just enable it and continue on.
4892                  */
4893         } else {
4894                 I915_WRITE(IPS_CTL, IPS_ENABLE);
4895                 /* The bit only becomes 1 in the next vblank, so this wait here
4896                  * is essentially intel_wait_for_vblank. If we don't have this
4897                  * and don't wait for vblanks until the end of crtc_enable, then
4898                  * the HW state readout code will complain that the expected
4899                  * IPS_CTL value is not the one we read. */
4900                 if (intel_wait_for_register(dev_priv,
4901                                             IPS_CTL, IPS_ENABLE, IPS_ENABLE,
4902                                             50))
4903                         DRM_ERROR("Timed out waiting for IPS enable\n");
4904         }
4905 }
4906
4907 void hsw_disable_ips(struct intel_crtc *crtc)
4908 {
4909         struct drm_device *dev = crtc->base.dev;
4910         struct drm_i915_private *dev_priv = to_i915(dev);
4911
4912         if (!crtc->config->ips_enabled)
4913                 return;
4914
4915         assert_plane_enabled(dev_priv, crtc->plane);
4916         if (IS_BROADWELL(dev)) {
4917                 mutex_lock(&dev_priv->rps.hw_lock);
4918                 WARN_ON(sandybridge_pcode_write(dev_priv, DISPLAY_IPS_CONTROL, 0));
4919                 mutex_unlock(&dev_priv->rps.hw_lock);
4920                 /* wait for pcode to finish disabling IPS, which may take up to 42ms */
4921                 if (intel_wait_for_register(dev_priv,
4922                                             IPS_CTL, IPS_ENABLE, 0,
4923                                             42))
4924                         DRM_ERROR("Timed out waiting for IPS disable\n");
4925         } else {
4926                 I915_WRITE(IPS_CTL, 0);
4927                 POSTING_READ(IPS_CTL);
4928         }
4929
4930         /* We need to wait for a vblank before we can disable the plane. */
4931         intel_wait_for_vblank(dev, crtc->pipe);
4932 }
4933
4934 static void intel_crtc_dpms_overlay_disable(struct intel_crtc *intel_crtc)
4935 {
4936         if (intel_crtc->overlay) {
4937                 struct drm_device *dev = intel_crtc->base.dev;
4938                 struct drm_i915_private *dev_priv = to_i915(dev);
4939
4940                 mutex_lock(&dev->struct_mutex);
4941                 dev_priv->mm.interruptible = false;
4942                 (void) intel_overlay_switch_off(intel_crtc->overlay);
4943                 dev_priv->mm.interruptible = true;
4944                 mutex_unlock(&dev->struct_mutex);
4945         }
4946
4947         /* Let userspace switch the overlay on again. In most cases userspace
4948          * has to recompute where to put it anyway.
4949          */
4950 }
4951
4952 /**
4953  * intel_post_enable_primary - Perform operations after enabling primary plane
4954  * @crtc: the CRTC whose primary plane was just enabled
4955  *
4956  * Performs potentially sleeping operations that must be done after the primary
4957  * plane is enabled, such as updating FBC and IPS.  Note that this may be
4958  * called due to an explicit primary plane update, or due to an implicit
4959  * re-enable that is caused when a sprite plane is updated to no longer
4960  * completely hide the primary plane.
4961  */
4962 static void
4963 intel_post_enable_primary(struct drm_crtc *crtc)
4964 {
4965         struct drm_device *dev = crtc->dev;
4966         struct drm_i915_private *dev_priv = to_i915(dev);
4967         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4968         int pipe = intel_crtc->pipe;
4969
4970         /*
4971          * FIXME IPS should be fine as long as one plane is
4972          * enabled, but in practice it seems to have problems
4973          * when going from primary only to sprite only and vice
4974          * versa.
4975          */
4976         hsw_enable_ips(intel_crtc);
4977
4978         /*
4979          * Gen2 reports pipe underruns whenever all planes are disabled.
4980          * So don't enable underrun reporting before at least some planes
4981          * are enabled.
4982          * FIXME: Need to fix the logic to work when we turn off all planes
4983          * but leave the pipe running.
4984          */
4985         if (IS_GEN2(dev))
4986                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
4987
4988         /* Underruns don't always raise interrupts, so check manually. */
4989         intel_check_cpu_fifo_underruns(dev_priv);
4990         intel_check_pch_fifo_underruns(dev_priv);
4991 }
4992
4993 /* FIXME move all this to pre_plane_update() with proper state tracking */
4994 static void
4995 intel_pre_disable_primary(struct drm_crtc *crtc)
4996 {
4997         struct drm_device *dev = crtc->dev;
4998         struct drm_i915_private *dev_priv = to_i915(dev);
4999         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5000         int pipe = intel_crtc->pipe;
5001
5002         /*
5003          * Gen2 reports pipe underruns whenever all planes are disabled.
5004          * So diasble underrun reporting before all the planes get disabled.
5005          * FIXME: Need to fix the logic to work when we turn off all planes
5006          * but leave the pipe running.
5007          */
5008         if (IS_GEN2(dev))
5009                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
5010
5011         /*
5012          * FIXME IPS should be fine as long as one plane is
5013          * enabled, but in practice it seems to have problems
5014          * when going from primary only to sprite only and vice
5015          * versa.
5016          */
5017         hsw_disable_ips(intel_crtc);
5018 }
5019
5020 /* FIXME get rid of this and use pre_plane_update */
5021 static void
5022 intel_pre_disable_primary_noatomic(struct drm_crtc *crtc)
5023 {
5024         struct drm_device *dev = crtc->dev;
5025         struct drm_i915_private *dev_priv = to_i915(dev);
5026         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5027         int pipe = intel_crtc->pipe;
5028
5029         intel_pre_disable_primary(crtc);
5030
5031         /*
5032          * Vblank time updates from the shadow to live plane control register
5033          * are blocked if the memory self-refresh mode is active at that
5034          * moment. So to make sure the plane gets truly disabled, disable
5035          * first the self-refresh mode. The self-refresh enable bit in turn
5036          * will be checked/applied by the HW only at the next frame start
5037          * event which is after the vblank start event, so we need to have a
5038          * wait-for-vblank between disabling the plane and the pipe.
5039          */
5040         if (HAS_GMCH_DISPLAY(dev)) {
5041                 intel_set_memory_cxsr(dev_priv, false);
5042                 dev_priv->wm.vlv.cxsr = false;
5043                 intel_wait_for_vblank(dev, pipe);
5044         }
5045 }
5046
5047 static void intel_post_plane_update(struct intel_crtc_state *old_crtc_state)
5048 {
5049         struct intel_crtc *crtc = to_intel_crtc(old_crtc_state->base.crtc);
5050         struct drm_atomic_state *old_state = old_crtc_state->base.state;
5051         struct intel_crtc_state *pipe_config =
5052                 to_intel_crtc_state(crtc->base.state);
5053         struct drm_plane *primary = crtc->base.primary;
5054         struct drm_plane_state *old_pri_state =
5055                 drm_atomic_get_existing_plane_state(old_state, primary);
5056
5057         intel_frontbuffer_flip(to_i915(crtc->base.dev), pipe_config->fb_bits);
5058
5059         crtc->wm.cxsr_allowed = true;
5060
5061         if (pipe_config->update_wm_post && pipe_config->base.active)
5062                 intel_update_watermarks(&crtc->base);
5063
5064         if (old_pri_state) {
5065                 struct intel_plane_state *primary_state =
5066                         to_intel_plane_state(primary->state);
5067                 struct intel_plane_state *old_primary_state =
5068                         to_intel_plane_state(old_pri_state);
5069
5070                 intel_fbc_post_update(crtc);
5071
5072                 if (primary_state->base.visible &&
5073                     (needs_modeset(&pipe_config->base) ||
5074                      !old_primary_state->base.visible))
5075                         intel_post_enable_primary(&crtc->base);
5076         }
5077 }
5078
5079 static void intel_pre_plane_update(struct intel_crtc_state *old_crtc_state)
5080 {
5081         struct intel_crtc *crtc = to_intel_crtc(old_crtc_state->base.crtc);
5082         struct drm_device *dev = crtc->base.dev;
5083         struct drm_i915_private *dev_priv = to_i915(dev);
5084         struct intel_crtc_state *pipe_config =
5085                 to_intel_crtc_state(crtc->base.state);
5086         struct drm_atomic_state *old_state = old_crtc_state->base.state;
5087         struct drm_plane *primary = crtc->base.primary;
5088         struct drm_plane_state *old_pri_state =
5089                 drm_atomic_get_existing_plane_state(old_state, primary);
5090         bool modeset = needs_modeset(&pipe_config->base);
5091
5092         if (old_pri_state) {
5093                 struct intel_plane_state *primary_state =
5094                         to_intel_plane_state(primary->state);
5095                 struct intel_plane_state *old_primary_state =
5096                         to_intel_plane_state(old_pri_state);
5097
5098                 intel_fbc_pre_update(crtc, pipe_config, primary_state);
5099
5100                 if (old_primary_state->base.visible &&
5101                     (modeset || !primary_state->base.visible))
5102                         intel_pre_disable_primary(&crtc->base);
5103         }
5104
5105         if (pipe_config->disable_cxsr && HAS_GMCH_DISPLAY(dev)) {
5106                 crtc->wm.cxsr_allowed = false;
5107
5108                 /*
5109                  * Vblank time updates from the shadow to live plane control register
5110                  * are blocked if the memory self-refresh mode is active at that
5111                  * moment. So to make sure the plane gets truly disabled, disable
5112                  * first the self-refresh mode. The self-refresh enable bit in turn
5113                  * will be checked/applied by the HW only at the next frame start
5114                  * event which is after the vblank start event, so we need to have a
5115                  * wait-for-vblank between disabling the plane and the pipe.
5116                  */
5117                 if (old_crtc_state->base.active) {
5118                         intel_set_memory_cxsr(dev_priv, false);
5119                         dev_priv->wm.vlv.cxsr = false;
5120                         intel_wait_for_vblank(dev, crtc->pipe);
5121                 }
5122         }
5123
5124         /*
5125          * IVB workaround: must disable low power watermarks for at least
5126          * one frame before enabling scaling.  LP watermarks can be re-enabled
5127          * when scaling is disabled.
5128          *
5129          * WaCxSRDisabledForSpriteScaling:ivb
5130          */
5131         if (pipe_config->disable_lp_wm) {
5132                 ilk_disable_lp_wm(dev);
5133                 intel_wait_for_vblank(dev, crtc->pipe);
5134         }
5135
5136         /*
5137          * If we're doing a modeset, we're done.  No need to do any pre-vblank
5138          * watermark programming here.
5139          */
5140         if (needs_modeset(&pipe_config->base))
5141                 return;
5142
5143         /*
5144          * For platforms that support atomic watermarks, program the
5145          * 'intermediate' watermarks immediately.  On pre-gen9 platforms, these
5146          * will be the intermediate values that are safe for both pre- and
5147          * post- vblank; when vblank happens, the 'active' values will be set
5148          * to the final 'target' values and we'll do this again to get the
5149          * optimal watermarks.  For gen9+ platforms, the values we program here
5150          * will be the final target values which will get automatically latched
5151          * at vblank time; no further programming will be necessary.
5152          *
5153          * If a platform hasn't been transitioned to atomic watermarks yet,
5154          * we'll continue to update watermarks the old way, if flags tell
5155          * us to.
5156          */
5157         if (dev_priv->display.initial_watermarks != NULL)
5158                 dev_priv->display.initial_watermarks(pipe_config);
5159         else if (pipe_config->update_wm_pre)
5160                 intel_update_watermarks(&crtc->base);
5161 }
5162
5163 static void intel_crtc_disable_planes(struct drm_crtc *crtc, unsigned plane_mask)
5164 {
5165         struct drm_device *dev = crtc->dev;
5166         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5167         struct drm_plane *p;
5168         int pipe = intel_crtc->pipe;
5169
5170         intel_crtc_dpms_overlay_disable(intel_crtc);
5171
5172         drm_for_each_plane_mask(p, dev, plane_mask)
5173                 to_intel_plane(p)->disable_plane(p, crtc);
5174
5175         /*
5176          * FIXME: Once we grow proper nuclear flip support out of this we need
5177          * to compute the mask of flip planes precisely. For the time being
5178          * consider this a flip to a NULL plane.
5179          */
5180         intel_frontbuffer_flip(to_i915(dev), INTEL_FRONTBUFFER_ALL_MASK(pipe));
5181 }
5182
5183 static void intel_encoders_pre_pll_enable(struct drm_crtc *crtc,
5184                                           struct intel_crtc_state *crtc_state,
5185                                           struct drm_atomic_state *old_state)
5186 {
5187         struct drm_connector_state *old_conn_state;
5188         struct drm_connector *conn;
5189         int i;
5190
5191         for_each_connector_in_state(old_state, conn, old_conn_state, i) {
5192                 struct drm_connector_state *conn_state = conn->state;
5193                 struct intel_encoder *encoder =
5194                         to_intel_encoder(conn_state->best_encoder);
5195
5196                 if (conn_state->crtc != crtc)
5197                         continue;
5198
5199                 if (encoder->pre_pll_enable)
5200                         encoder->pre_pll_enable(encoder, crtc_state, conn_state);
5201         }
5202 }
5203
5204 static void intel_encoders_pre_enable(struct drm_crtc *crtc,
5205                                       struct intel_crtc_state *crtc_state,
5206                                       struct drm_atomic_state *old_state)
5207 {
5208         struct drm_connector_state *old_conn_state;
5209         struct drm_connector *conn;
5210         int i;
5211
5212         for_each_connector_in_state(old_state, conn, old_conn_state, i) {
5213                 struct drm_connector_state *conn_state = conn->state;
5214                 struct intel_encoder *encoder =
5215                         to_intel_encoder(conn_state->best_encoder);
5216
5217                 if (conn_state->crtc != crtc)
5218                         continue;
5219
5220                 if (encoder->pre_enable)
5221                         encoder->pre_enable(encoder, crtc_state, conn_state);
5222         }
5223 }
5224
5225 static void intel_encoders_enable(struct drm_crtc *crtc,
5226                                   struct intel_crtc_state *crtc_state,
5227                                   struct drm_atomic_state *old_state)
5228 {
5229         struct drm_connector_state *old_conn_state;
5230         struct drm_connector *conn;
5231         int i;
5232
5233         for_each_connector_in_state(old_state, conn, old_conn_state, i) {
5234                 struct drm_connector_state *conn_state = conn->state;
5235                 struct intel_encoder *encoder =
5236                         to_intel_encoder(conn_state->best_encoder);
5237
5238                 if (conn_state->crtc != crtc)
5239                         continue;
5240
5241                 encoder->enable(encoder, crtc_state, conn_state);
5242                 intel_opregion_notify_encoder(encoder, true);
5243         }
5244 }
5245
5246 static void intel_encoders_disable(struct drm_crtc *crtc,
5247                                    struct intel_crtc_state *old_crtc_state,
5248                                    struct drm_atomic_state *old_state)
5249 {
5250         struct drm_connector_state *old_conn_state;
5251         struct drm_connector *conn;
5252         int i;
5253
5254         for_each_connector_in_state(old_state, conn, old_conn_state, i) {
5255                 struct intel_encoder *encoder =
5256                         to_intel_encoder(old_conn_state->best_encoder);
5257
5258                 if (old_conn_state->crtc != crtc)
5259                         continue;
5260
5261                 intel_opregion_notify_encoder(encoder, false);
5262                 encoder->disable(encoder, old_crtc_state, old_conn_state);
5263         }
5264 }
5265
5266 static void intel_encoders_post_disable(struct drm_crtc *crtc,
5267                                         struct intel_crtc_state *old_crtc_state,
5268                                         struct drm_atomic_state *old_state)
5269 {
5270         struct drm_connector_state *old_conn_state;
5271         struct drm_connector *conn;
5272         int i;
5273
5274         for_each_connector_in_state(old_state, conn, old_conn_state, i) {
5275                 struct intel_encoder *encoder =
5276                         to_intel_encoder(old_conn_state->best_encoder);
5277
5278                 if (old_conn_state->crtc != crtc)
5279                         continue;
5280
5281                 if (encoder->post_disable)
5282                         encoder->post_disable(encoder, old_crtc_state, old_conn_state);
5283         }
5284 }
5285
5286 static void intel_encoders_post_pll_disable(struct drm_crtc *crtc,
5287                                             struct intel_crtc_state *old_crtc_state,
5288                                             struct drm_atomic_state *old_state)
5289 {
5290         struct drm_connector_state *old_conn_state;
5291         struct drm_connector *conn;
5292         int i;
5293
5294         for_each_connector_in_state(old_state, conn, old_conn_state, i) {
5295                 struct intel_encoder *encoder =
5296                         to_intel_encoder(old_conn_state->best_encoder);
5297
5298                 if (old_conn_state->crtc != crtc)
5299                         continue;
5300
5301                 if (encoder->post_pll_disable)
5302                         encoder->post_pll_disable(encoder, old_crtc_state, old_conn_state);
5303         }
5304 }
5305
5306 static void ironlake_crtc_enable(struct intel_crtc_state *pipe_config,
5307                                  struct drm_atomic_state *old_state)
5308 {
5309         struct drm_crtc *crtc = pipe_config->base.crtc;
5310         struct drm_device *dev = crtc->dev;
5311         struct drm_i915_private *dev_priv = to_i915(dev);
5312         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5313         int pipe = intel_crtc->pipe;
5314
5315         if (WARN_ON(intel_crtc->active))
5316                 return;
5317
5318         /*
5319          * Sometimes spurious CPU pipe underruns happen during FDI
5320          * training, at least with VGA+HDMI cloning. Suppress them.
5321          *
5322          * On ILK we get an occasional spurious CPU pipe underruns
5323          * between eDP port A enable and vdd enable. Also PCH port
5324          * enable seems to result in the occasional CPU pipe underrun.
5325          *
5326          * Spurious PCH underruns also occur during PCH enabling.
5327          */
5328         if (intel_crtc->config->has_pch_encoder || IS_GEN5(dev_priv))
5329                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
5330         if (intel_crtc->config->has_pch_encoder)
5331                 intel_set_pch_fifo_underrun_reporting(dev_priv, pipe, false);
5332
5333         if (intel_crtc->config->has_pch_encoder)
5334                 intel_prepare_shared_dpll(intel_crtc);
5335
5336         if (intel_crtc_has_dp_encoder(intel_crtc->config))
5337                 intel_dp_set_m_n(intel_crtc, M1_N1);
5338
5339         intel_set_pipe_timings(intel_crtc);
5340         intel_set_pipe_src_size(intel_crtc);
5341
5342         if (intel_crtc->config->has_pch_encoder) {
5343                 intel_cpu_transcoder_set_m_n(intel_crtc,
5344                                      &intel_crtc->config->fdi_m_n, NULL);
5345         }
5346
5347         ironlake_set_pipeconf(crtc);
5348
5349         intel_crtc->active = true;
5350
5351         intel_encoders_pre_enable(crtc, pipe_config, old_state);
5352
5353         if (intel_crtc->config->has_pch_encoder) {
5354                 /* Note: FDI PLL enabling _must_ be done before we enable the
5355                  * cpu pipes, hence this is separate from all the other fdi/pch
5356                  * enabling. */
5357                 ironlake_fdi_pll_enable(intel_crtc);
5358         } else {
5359                 assert_fdi_tx_disabled(dev_priv, pipe);
5360                 assert_fdi_rx_disabled(dev_priv, pipe);
5361         }
5362
5363         ironlake_pfit_enable(intel_crtc);
5364
5365         /*
5366          * On ILK+ LUT must be loaded before the pipe is running but with
5367          * clocks enabled
5368          */
5369         intel_color_load_luts(&pipe_config->base);
5370
5371         if (dev_priv->display.initial_watermarks != NULL)
5372                 dev_priv->display.initial_watermarks(intel_crtc->config);
5373         intel_enable_pipe(intel_crtc);
5374
5375         if (intel_crtc->config->has_pch_encoder)
5376                 ironlake_pch_enable(crtc);
5377
5378         assert_vblank_disabled(crtc);
5379         drm_crtc_vblank_on(crtc);
5380
5381         intel_encoders_enable(crtc, pipe_config, old_state);
5382
5383         if (HAS_PCH_CPT(dev))
5384                 cpt_verify_modeset(dev, intel_crtc->pipe);
5385
5386         /* Must wait for vblank to avoid spurious PCH FIFO underruns */
5387         if (intel_crtc->config->has_pch_encoder)
5388                 intel_wait_for_vblank(dev, pipe);
5389         intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
5390         intel_set_pch_fifo_underrun_reporting(dev_priv, pipe, true);
5391 }
5392
5393 /* IPS only exists on ULT machines and is tied to pipe A. */
5394 static bool hsw_crtc_supports_ips(struct intel_crtc *crtc)
5395 {
5396         return HAS_IPS(crtc->base.dev) && crtc->pipe == PIPE_A;
5397 }
5398
5399 static void haswell_crtc_enable(struct intel_crtc_state *pipe_config,
5400                                 struct drm_atomic_state *old_state)
5401 {
5402         struct drm_crtc *crtc = pipe_config->base.crtc;
5403         struct drm_device *dev = crtc->dev;
5404         struct drm_i915_private *dev_priv = to_i915(dev);
5405         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5406         int pipe = intel_crtc->pipe, hsw_workaround_pipe;
5407         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
5408
5409         if (WARN_ON(intel_crtc->active))
5410                 return;
5411
5412         if (intel_crtc->config->has_pch_encoder)
5413                 intel_set_pch_fifo_underrun_reporting(dev_priv, PIPE_A,
5414                                                       false);
5415
5416         intel_encoders_pre_pll_enable(crtc, pipe_config, old_state);
5417
5418         if (intel_crtc->config->shared_dpll)
5419                 intel_enable_shared_dpll(intel_crtc);
5420
5421         if (intel_crtc_has_dp_encoder(intel_crtc->config))
5422                 intel_dp_set_m_n(intel_crtc, M1_N1);
5423
5424         if (!transcoder_is_dsi(cpu_transcoder))
5425                 intel_set_pipe_timings(intel_crtc);
5426
5427         intel_set_pipe_src_size(intel_crtc);
5428
5429         if (cpu_transcoder != TRANSCODER_EDP &&
5430             !transcoder_is_dsi(cpu_transcoder)) {
5431                 I915_WRITE(PIPE_MULT(cpu_transcoder),
5432                            intel_crtc->config->pixel_multiplier - 1);
5433         }
5434
5435         if (intel_crtc->config->has_pch_encoder) {
5436                 intel_cpu_transcoder_set_m_n(intel_crtc,
5437                                      &intel_crtc->config->fdi_m_n, NULL);
5438         }
5439
5440         if (!transcoder_is_dsi(cpu_transcoder))
5441                 haswell_set_pipeconf(crtc);
5442
5443         haswell_set_pipemisc(crtc);
5444
5445         intel_color_set_csc(&pipe_config->base);
5446
5447         intel_crtc->active = true;
5448
5449         if (intel_crtc->config->has_pch_encoder)
5450                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
5451         else
5452                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
5453
5454         intel_encoders_pre_enable(crtc, pipe_config, old_state);
5455
5456         if (intel_crtc->config->has_pch_encoder)
5457                 dev_priv->display.fdi_link_train(crtc);
5458
5459         if (!transcoder_is_dsi(cpu_transcoder))
5460                 intel_ddi_enable_pipe_clock(intel_crtc);
5461
5462         if (INTEL_INFO(dev)->gen >= 9)
5463                 skylake_pfit_enable(intel_crtc);
5464         else
5465                 ironlake_pfit_enable(intel_crtc);
5466
5467         /*
5468          * On ILK+ LUT must be loaded before the pipe is running but with
5469          * clocks enabled
5470          */
5471         intel_color_load_luts(&pipe_config->base);
5472
5473         intel_ddi_set_pipe_settings(crtc);
5474         if (!transcoder_is_dsi(cpu_transcoder))
5475                 intel_ddi_enable_transcoder_func(crtc);
5476
5477         if (dev_priv->display.initial_watermarks != NULL)
5478                 dev_priv->display.initial_watermarks(pipe_config);
5479         else
5480                 intel_update_watermarks(crtc);
5481
5482         /* XXX: Do the pipe assertions at the right place for BXT DSI. */
5483         if (!transcoder_is_dsi(cpu_transcoder))
5484                 intel_enable_pipe(intel_crtc);
5485
5486         if (intel_crtc->config->has_pch_encoder)
5487                 lpt_pch_enable(crtc);
5488
5489         if (intel_crtc->config->dp_encoder_is_mst)
5490                 intel_ddi_set_vc_payload_alloc(crtc, true);
5491
5492         assert_vblank_disabled(crtc);
5493         drm_crtc_vblank_on(crtc);
5494
5495         intel_encoders_enable(crtc, pipe_config, old_state);
5496
5497         if (intel_crtc->config->has_pch_encoder) {
5498                 intel_wait_for_vblank(dev, pipe);
5499                 intel_wait_for_vblank(dev, pipe);
5500                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
5501                 intel_set_pch_fifo_underrun_reporting(dev_priv, PIPE_A,
5502                                                       true);
5503         }
5504
5505         /* If we change the relative order between pipe/planes enabling, we need
5506          * to change the workaround. */
5507         hsw_workaround_pipe = pipe_config->hsw_workaround_pipe;
5508         if (IS_HASWELL(dev) && hsw_workaround_pipe != INVALID_PIPE) {
5509                 intel_wait_for_vblank(dev, hsw_workaround_pipe);
5510                 intel_wait_for_vblank(dev, hsw_workaround_pipe);
5511         }
5512 }
5513
5514 static void ironlake_pfit_disable(struct intel_crtc *crtc, bool force)
5515 {
5516         struct drm_device *dev = crtc->base.dev;
5517         struct drm_i915_private *dev_priv = to_i915(dev);
5518         int pipe = crtc->pipe;
5519
5520         /* To avoid upsetting the power well on haswell only disable the pfit if
5521          * it's in use. The hw state code will make sure we get this right. */
5522         if (force || crtc->config->pch_pfit.enabled) {
5523                 I915_WRITE(PF_CTL(pipe), 0);
5524                 I915_WRITE(PF_WIN_POS(pipe), 0);
5525                 I915_WRITE(PF_WIN_SZ(pipe), 0);
5526         }
5527 }
5528
5529 static void ironlake_crtc_disable(struct intel_crtc_state *old_crtc_state,
5530                                   struct drm_atomic_state *old_state)
5531 {
5532         struct drm_crtc *crtc = old_crtc_state->base.crtc;
5533         struct drm_device *dev = crtc->dev;
5534         struct drm_i915_private *dev_priv = to_i915(dev);
5535         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5536         int pipe = intel_crtc->pipe;
5537
5538         /*
5539          * Sometimes spurious CPU pipe underruns happen when the
5540          * pipe is already disabled, but FDI RX/TX is still enabled.
5541          * Happens at least with VGA+HDMI cloning. Suppress them.
5542          */
5543         if (intel_crtc->config->has_pch_encoder) {
5544                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
5545                 intel_set_pch_fifo_underrun_reporting(dev_priv, pipe, false);
5546         }
5547
5548         intel_encoders_disable(crtc, old_crtc_state, old_state);
5549
5550         drm_crtc_vblank_off(crtc);
5551         assert_vblank_disabled(crtc);
5552
5553         intel_disable_pipe(intel_crtc);
5554
5555         ironlake_pfit_disable(intel_crtc, false);
5556
5557         if (intel_crtc->config->has_pch_encoder)
5558                 ironlake_fdi_disable(crtc);
5559
5560         intel_encoders_post_disable(crtc, old_crtc_state, old_state);
5561
5562         if (intel_crtc->config->has_pch_encoder) {
5563                 ironlake_disable_pch_transcoder(dev_priv, pipe);
5564
5565                 if (HAS_PCH_CPT(dev)) {
5566                         i915_reg_t reg;
5567                         u32 temp;
5568
5569                         /* disable TRANS_DP_CTL */
5570                         reg = TRANS_DP_CTL(pipe);
5571                         temp = I915_READ(reg);
5572                         temp &= ~(TRANS_DP_OUTPUT_ENABLE |
5573                                   TRANS_DP_PORT_SEL_MASK);
5574                         temp |= TRANS_DP_PORT_SEL_NONE;
5575                         I915_WRITE(reg, temp);
5576
5577                         /* disable DPLL_SEL */
5578                         temp = I915_READ(PCH_DPLL_SEL);
5579                         temp &= ~(TRANS_DPLL_ENABLE(pipe) | TRANS_DPLLB_SEL(pipe));
5580                         I915_WRITE(PCH_DPLL_SEL, temp);
5581                 }
5582
5583                 ironlake_fdi_pll_disable(intel_crtc);
5584         }
5585
5586         intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
5587         intel_set_pch_fifo_underrun_reporting(dev_priv, pipe, true);
5588 }
5589
5590 static void haswell_crtc_disable(struct intel_crtc_state *old_crtc_state,
5591                                  struct drm_atomic_state *old_state)
5592 {
5593         struct drm_crtc *crtc = old_crtc_state->base.crtc;
5594         struct drm_device *dev = crtc->dev;
5595         struct drm_i915_private *dev_priv = to_i915(dev);
5596         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5597         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
5598
5599         if (intel_crtc->config->has_pch_encoder)
5600                 intel_set_pch_fifo_underrun_reporting(dev_priv, PIPE_A,
5601                                                       false);
5602
5603         intel_encoders_disable(crtc, old_crtc_state, old_state);
5604
5605         drm_crtc_vblank_off(crtc);
5606         assert_vblank_disabled(crtc);
5607
5608         /* XXX: Do the pipe assertions at the right place for BXT DSI. */
5609         if (!transcoder_is_dsi(cpu_transcoder))
5610                 intel_disable_pipe(intel_crtc);
5611
5612         if (intel_crtc->config->dp_encoder_is_mst)
5613                 intel_ddi_set_vc_payload_alloc(crtc, false);
5614
5615         if (!transcoder_is_dsi(cpu_transcoder))
5616                 intel_ddi_disable_transcoder_func(dev_priv, cpu_transcoder);
5617
5618         if (INTEL_INFO(dev)->gen >= 9)
5619                 skylake_scaler_disable(intel_crtc);
5620         else
5621                 ironlake_pfit_disable(intel_crtc, false);
5622
5623         if (!transcoder_is_dsi(cpu_transcoder))
5624                 intel_ddi_disable_pipe_clock(intel_crtc);
5625
5626         intel_encoders_post_disable(crtc, old_crtc_state, old_state);
5627
5628         if (old_crtc_state->has_pch_encoder)
5629                 intel_set_pch_fifo_underrun_reporting(dev_priv, PIPE_A,
5630                                                       true);
5631 }
5632
5633 static void i9xx_pfit_enable(struct intel_crtc *crtc)
5634 {
5635         struct drm_device *dev = crtc->base.dev;
5636         struct drm_i915_private *dev_priv = to_i915(dev);
5637         struct intel_crtc_state *pipe_config = crtc->config;
5638
5639         if (!pipe_config->gmch_pfit.control)
5640                 return;
5641
5642         /*
5643          * The panel fitter should only be adjusted whilst the pipe is disabled,
5644          * according to register description and PRM.
5645          */
5646         WARN_ON(I915_READ(PFIT_CONTROL) & PFIT_ENABLE);
5647         assert_pipe_disabled(dev_priv, crtc->pipe);
5648
5649         I915_WRITE(PFIT_PGM_RATIOS, pipe_config->gmch_pfit.pgm_ratios);
5650         I915_WRITE(PFIT_CONTROL, pipe_config->gmch_pfit.control);
5651
5652         /* Border color in case we don't scale up to the full screen. Black by
5653          * default, change to something else for debugging. */
5654         I915_WRITE(BCLRPAT(crtc->pipe), 0);
5655 }
5656
5657 static enum intel_display_power_domain port_to_power_domain(enum port port)
5658 {
5659         switch (port) {
5660         case PORT_A:
5661                 return POWER_DOMAIN_PORT_DDI_A_LANES;
5662         case PORT_B:
5663                 return POWER_DOMAIN_PORT_DDI_B_LANES;
5664         case PORT_C:
5665                 return POWER_DOMAIN_PORT_DDI_C_LANES;
5666         case PORT_D:
5667                 return POWER_DOMAIN_PORT_DDI_D_LANES;
5668         case PORT_E:
5669                 return POWER_DOMAIN_PORT_DDI_E_LANES;
5670         default:
5671                 MISSING_CASE(port);
5672                 return POWER_DOMAIN_PORT_OTHER;
5673         }
5674 }
5675
5676 static enum intel_display_power_domain port_to_aux_power_domain(enum port port)
5677 {
5678         switch (port) {
5679         case PORT_A:
5680                 return POWER_DOMAIN_AUX_A;
5681         case PORT_B:
5682                 return POWER_DOMAIN_AUX_B;
5683         case PORT_C:
5684                 return POWER_DOMAIN_AUX_C;
5685         case PORT_D:
5686                 return POWER_DOMAIN_AUX_D;
5687         case PORT_E:
5688                 /* FIXME: Check VBT for actual wiring of PORT E */
5689                 return POWER_DOMAIN_AUX_D;
5690         default:
5691                 MISSING_CASE(port);
5692                 return POWER_DOMAIN_AUX_A;
5693         }
5694 }
5695
5696 enum intel_display_power_domain
5697 intel_display_port_power_domain(struct intel_encoder *intel_encoder)
5698 {
5699         struct drm_device *dev = intel_encoder->base.dev;
5700         struct intel_digital_port *intel_dig_port;
5701
5702         switch (intel_encoder->type) {
5703         case INTEL_OUTPUT_UNKNOWN:
5704                 /* Only DDI platforms should ever use this output type */
5705                 WARN_ON_ONCE(!HAS_DDI(dev));
5706         case INTEL_OUTPUT_DP:
5707         case INTEL_OUTPUT_HDMI:
5708         case INTEL_OUTPUT_EDP:
5709                 intel_dig_port = enc_to_dig_port(&intel_encoder->base);
5710                 return port_to_power_domain(intel_dig_port->port);
5711         case INTEL_OUTPUT_DP_MST:
5712                 intel_dig_port = enc_to_mst(&intel_encoder->base)->primary;
5713                 return port_to_power_domain(intel_dig_port->port);
5714         case INTEL_OUTPUT_ANALOG:
5715                 return POWER_DOMAIN_PORT_CRT;
5716         case INTEL_OUTPUT_DSI:
5717                 return POWER_DOMAIN_PORT_DSI;
5718         default:
5719                 return POWER_DOMAIN_PORT_OTHER;
5720         }
5721 }
5722
5723 enum intel_display_power_domain
5724 intel_display_port_aux_power_domain(struct intel_encoder *intel_encoder)
5725 {
5726         struct drm_device *dev = intel_encoder->base.dev;
5727         struct intel_digital_port *intel_dig_port;
5728
5729         switch (intel_encoder->type) {
5730         case INTEL_OUTPUT_UNKNOWN:
5731         case INTEL_OUTPUT_HDMI:
5732                 /*
5733                  * Only DDI platforms should ever use these output types.
5734                  * We can get here after the HDMI detect code has already set
5735                  * the type of the shared encoder. Since we can't be sure
5736                  * what's the status of the given connectors, play safe and
5737                  * run the DP detection too.
5738                  */
5739                 WARN_ON_ONCE(!HAS_DDI(dev));
5740         case INTEL_OUTPUT_DP:
5741         case INTEL_OUTPUT_EDP:
5742                 intel_dig_port = enc_to_dig_port(&intel_encoder->base);
5743                 return port_to_aux_power_domain(intel_dig_port->port);
5744         case INTEL_OUTPUT_DP_MST:
5745                 intel_dig_port = enc_to_mst(&intel_encoder->base)->primary;
5746                 return port_to_aux_power_domain(intel_dig_port->port);
5747         default:
5748                 MISSING_CASE(intel_encoder->type);
5749                 return POWER_DOMAIN_AUX_A;
5750         }
5751 }
5752
5753 static unsigned long get_crtc_power_domains(struct drm_crtc *crtc,
5754                                             struct intel_crtc_state *crtc_state)
5755 {
5756         struct drm_device *dev = crtc->dev;
5757         struct drm_encoder *encoder;
5758         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5759         enum pipe pipe = intel_crtc->pipe;
5760         unsigned long mask;
5761         enum transcoder transcoder = crtc_state->cpu_transcoder;
5762
5763         if (!crtc_state->base.active)
5764                 return 0;
5765
5766         mask = BIT(POWER_DOMAIN_PIPE(pipe));
5767         mask |= BIT(POWER_DOMAIN_TRANSCODER(transcoder));
5768         if (crtc_state->pch_pfit.enabled ||
5769             crtc_state->pch_pfit.force_thru)
5770                 mask |= BIT(POWER_DOMAIN_PIPE_PANEL_FITTER(pipe));
5771
5772         drm_for_each_encoder_mask(encoder, dev, crtc_state->base.encoder_mask) {
5773                 struct intel_encoder *intel_encoder = to_intel_encoder(encoder);
5774
5775                 mask |= BIT(intel_display_port_power_domain(intel_encoder));
5776         }
5777
5778         if (crtc_state->shared_dpll)
5779                 mask |= BIT(POWER_DOMAIN_PLLS);
5780
5781         return mask;
5782 }
5783
5784 static unsigned long
5785 modeset_get_crtc_power_domains(struct drm_crtc *crtc,
5786                                struct intel_crtc_state *crtc_state)
5787 {
5788         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
5789         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5790         enum intel_display_power_domain domain;
5791         unsigned long domains, new_domains, old_domains;
5792
5793         old_domains = intel_crtc->enabled_power_domains;
5794         intel_crtc->enabled_power_domains = new_domains =
5795                 get_crtc_power_domains(crtc, crtc_state);
5796
5797         domains = new_domains & ~old_domains;
5798
5799         for_each_power_domain(domain, domains)
5800                 intel_display_power_get(dev_priv, domain);
5801
5802         return old_domains & ~new_domains;
5803 }
5804
5805 static void modeset_put_power_domains(struct drm_i915_private *dev_priv,
5806                                       unsigned long domains)
5807 {
5808         enum intel_display_power_domain domain;
5809
5810         for_each_power_domain(domain, domains)
5811                 intel_display_power_put(dev_priv, domain);
5812 }
5813
5814 static int intel_compute_max_dotclk(struct drm_i915_private *dev_priv)
5815 {
5816         int max_cdclk_freq = dev_priv->max_cdclk_freq;
5817
5818         if (INTEL_INFO(dev_priv)->gen >= 9 ||
5819             IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv))
5820                 return max_cdclk_freq;
5821         else if (IS_CHERRYVIEW(dev_priv))
5822                 return max_cdclk_freq*95/100;
5823         else if (INTEL_INFO(dev_priv)->gen < 4)
5824                 return 2*max_cdclk_freq*90/100;
5825         else
5826                 return max_cdclk_freq*90/100;
5827 }
5828
5829 static int skl_calc_cdclk(int max_pixclk, int vco);
5830
5831 static void intel_update_max_cdclk(struct drm_device *dev)
5832 {
5833         struct drm_i915_private *dev_priv = to_i915(dev);
5834
5835         if (IS_SKYLAKE(dev) || IS_KABYLAKE(dev)) {
5836                 u32 limit = I915_READ(SKL_DFSM) & SKL_DFSM_CDCLK_LIMIT_MASK;
5837                 int max_cdclk, vco;
5838
5839                 vco = dev_priv->skl_preferred_vco_freq;
5840                 WARN_ON(vco != 8100000 && vco != 8640000);
5841
5842                 /*
5843                  * Use the lower (vco 8640) cdclk values as a
5844                  * first guess. skl_calc_cdclk() will correct it
5845                  * if the preferred vco is 8100 instead.
5846                  */
5847                 if (limit == SKL_DFSM_CDCLK_LIMIT_675)
5848                         max_cdclk = 617143;
5849                 else if (limit == SKL_DFSM_CDCLK_LIMIT_540)
5850                         max_cdclk = 540000;
5851                 else if (limit == SKL_DFSM_CDCLK_LIMIT_450)
5852                         max_cdclk = 432000;
5853                 else
5854                         max_cdclk = 308571;
5855
5856                 dev_priv->max_cdclk_freq = skl_calc_cdclk(max_cdclk, vco);
5857         } else if (IS_BROXTON(dev)) {
5858                 dev_priv->max_cdclk_freq = 624000;
5859         } else if (IS_BROADWELL(dev))  {
5860                 /*
5861                  * FIXME with extra cooling we can allow
5862                  * 540 MHz for ULX and 675 Mhz for ULT.
5863                  * How can we know if extra cooling is
5864                  * available? PCI ID, VTB, something else?
5865                  */
5866                 if (I915_READ(FUSE_STRAP) & HSW_CDCLK_LIMIT)
5867                         dev_priv->max_cdclk_freq = 450000;
5868                 else if (IS_BDW_ULX(dev))
5869                         dev_priv->max_cdclk_freq = 450000;
5870                 else if (IS_BDW_ULT(dev))
5871                         dev_priv->max_cdclk_freq = 540000;
5872                 else
5873                         dev_priv->max_cdclk_freq = 675000;
5874         } else if (IS_CHERRYVIEW(dev)) {
5875                 dev_priv->max_cdclk_freq = 320000;
5876         } else if (IS_VALLEYVIEW(dev)) {
5877                 dev_priv->max_cdclk_freq = 400000;
5878         } else {
5879                 /* otherwise assume cdclk is fixed */
5880                 dev_priv->max_cdclk_freq = dev_priv->cdclk_freq;
5881         }
5882
5883         dev_priv->max_dotclk_freq = intel_compute_max_dotclk(dev_priv);
5884
5885         DRM_DEBUG_DRIVER("Max CD clock rate: %d kHz\n",
5886                          dev_priv->max_cdclk_freq);
5887
5888         DRM_DEBUG_DRIVER("Max dotclock rate: %d kHz\n",
5889                          dev_priv->max_dotclk_freq);
5890 }
5891
5892 static void intel_update_cdclk(struct drm_device *dev)
5893 {
5894         struct drm_i915_private *dev_priv = to_i915(dev);
5895
5896         dev_priv->cdclk_freq = dev_priv->display.get_display_clock_speed(dev);
5897
5898         if (INTEL_GEN(dev_priv) >= 9)
5899                 DRM_DEBUG_DRIVER("Current CD clock rate: %d kHz, VCO: %d kHz, ref: %d kHz\n",
5900                                  dev_priv->cdclk_freq, dev_priv->cdclk_pll.vco,
5901                                  dev_priv->cdclk_pll.ref);
5902         else
5903                 DRM_DEBUG_DRIVER("Current CD clock rate: %d kHz\n",
5904                                  dev_priv->cdclk_freq);
5905
5906         /*
5907          * 9:0 CMBUS [sic] CDCLK frequency (cdfreq):
5908          * Programmng [sic] note: bit[9:2] should be programmed to the number
5909          * of cdclk that generates 4MHz reference clock freq which is used to
5910          * generate GMBus clock. This will vary with the cdclk freq.
5911          */
5912         if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
5913                 I915_WRITE(GMBUSFREQ_VLV, DIV_ROUND_UP(dev_priv->cdclk_freq, 1000));
5914 }
5915
5916 /* convert from kHz to .1 fixpoint MHz with -1MHz offset */
5917 static int skl_cdclk_decimal(int cdclk)
5918 {
5919         return DIV_ROUND_CLOSEST(cdclk - 1000, 500);
5920 }
5921
5922 static int bxt_de_pll_vco(struct drm_i915_private *dev_priv, int cdclk)
5923 {
5924         int ratio;
5925
5926         if (cdclk == dev_priv->cdclk_pll.ref)
5927                 return 0;
5928
5929         switch (cdclk) {
5930         default:
5931                 MISSING_CASE(cdclk);
5932         case 144000:
5933         case 288000:
5934         case 384000:
5935         case 576000:
5936                 ratio = 60;
5937                 break;
5938         case 624000:
5939                 ratio = 65;
5940                 break;
5941         }
5942
5943         return dev_priv->cdclk_pll.ref * ratio;
5944 }
5945
5946 static void bxt_de_pll_disable(struct drm_i915_private *dev_priv)
5947 {
5948         I915_WRITE(BXT_DE_PLL_ENABLE, 0);
5949
5950         /* Timeout 200us */
5951         if (intel_wait_for_register(dev_priv,
5952                                     BXT_DE_PLL_ENABLE, BXT_DE_PLL_LOCK, 0,
5953                                     1))
5954                 DRM_ERROR("timeout waiting for DE PLL unlock\n");
5955
5956         dev_priv->cdclk_pll.vco = 0;
5957 }
5958
5959 static void bxt_de_pll_enable(struct drm_i915_private *dev_priv, int vco)
5960 {
5961         int ratio = DIV_ROUND_CLOSEST(vco, dev_priv->cdclk_pll.ref);
5962         u32 val;
5963
5964         val = I915_READ(BXT_DE_PLL_CTL);
5965         val &= ~BXT_DE_PLL_RATIO_MASK;
5966         val |= BXT_DE_PLL_RATIO(ratio);
5967         I915_WRITE(BXT_DE_PLL_CTL, val);
5968
5969         I915_WRITE(BXT_DE_PLL_ENABLE, BXT_DE_PLL_PLL_ENABLE);
5970
5971         /* Timeout 200us */
5972         if (intel_wait_for_register(dev_priv,
5973                                     BXT_DE_PLL_ENABLE,
5974                                     BXT_DE_PLL_LOCK,
5975                                     BXT_DE_PLL_LOCK,
5976                                     1))
5977                 DRM_ERROR("timeout waiting for DE PLL lock\n");
5978
5979         dev_priv->cdclk_pll.vco = vco;
5980 }
5981
5982 static void bxt_set_cdclk(struct drm_i915_private *dev_priv, int cdclk)
5983 {
5984         u32 val, divider;
5985         int vco, ret;
5986
5987         vco = bxt_de_pll_vco(dev_priv, cdclk);
5988
5989         DRM_DEBUG_DRIVER("Changing CDCLK to %d kHz (VCO %d kHz)\n", cdclk, vco);
5990
5991         /* cdclk = vco / 2 / div{1,1.5,2,4} */
5992         switch (DIV_ROUND_CLOSEST(vco, cdclk)) {
5993         case 8:
5994                 divider = BXT_CDCLK_CD2X_DIV_SEL_4;
5995                 break;
5996         case 4:
5997                 divider = BXT_CDCLK_CD2X_DIV_SEL_2;
5998                 break;
5999         case 3:
6000                 divider = BXT_CDCLK_CD2X_DIV_SEL_1_5;
6001                 break;
6002         case 2:
6003                 divider = BXT_CDCLK_CD2X_DIV_SEL_1;
6004                 break;
6005         default:
6006                 WARN_ON(cdclk != dev_priv->cdclk_pll.ref);
6007                 WARN_ON(vco != 0);
6008
6009                 divider = BXT_CDCLK_CD2X_DIV_SEL_1;
6010                 break;
6011         }
6012
6013         /* Inform power controller of upcoming frequency change */
6014         mutex_lock(&dev_priv->rps.hw_lock);
6015         ret = sandybridge_pcode_write_timeout(dev_priv, HSW_PCODE_DE_WRITE_FREQ_REQ,
6016                                               0x80000000, 2000);
6017         mutex_unlock(&dev_priv->rps.hw_lock);
6018
6019         if (ret) {
6020                 DRM_ERROR("PCode CDCLK freq change notify failed (err %d, freq %d)\n",
6021                           ret, cdclk);
6022                 return;
6023         }
6024
6025         if (dev_priv->cdclk_pll.vco != 0 &&
6026             dev_priv->cdclk_pll.vco != vco)
6027                 bxt_de_pll_disable(dev_priv);
6028
6029         if (dev_priv->cdclk_pll.vco != vco)
6030                 bxt_de_pll_enable(dev_priv, vco);
6031
6032         val = divider | skl_cdclk_decimal(cdclk);
6033         /*
6034          * FIXME if only the cd2x divider needs changing, it could be done
6035          * without shutting off the pipe (if only one pipe is active).
6036          */
6037         val |= BXT_CDCLK_CD2X_PIPE_NONE;
6038         /*
6039          * Disable SSA Precharge when CD clock frequency < 500 MHz,
6040          * enable otherwise.
6041          */
6042         if (cdclk >= 500000)
6043                 val |= BXT_CDCLK_SSA_PRECHARGE_ENABLE;
6044         I915_WRITE(CDCLK_CTL, val);
6045
6046         mutex_lock(&dev_priv->rps.hw_lock);
6047         ret = sandybridge_pcode_write_timeout(dev_priv,
6048                                               HSW_PCODE_DE_WRITE_FREQ_REQ,
6049                                               DIV_ROUND_UP(cdclk, 25000), 2000);
6050         mutex_unlock(&dev_priv->rps.hw_lock);
6051
6052         if (ret) {
6053                 DRM_ERROR("PCode CDCLK freq set failed, (err %d, freq %d)\n",
6054                           ret, cdclk);
6055                 return;
6056         }
6057
6058         intel_update_cdclk(&dev_priv->drm);
6059 }
6060
6061 static void bxt_sanitize_cdclk(struct drm_i915_private *dev_priv)
6062 {
6063         u32 cdctl, expected;
6064
6065         intel_update_cdclk(&dev_priv->drm);
6066
6067         if (dev_priv->cdclk_pll.vco == 0 ||
6068             dev_priv->cdclk_freq == dev_priv->cdclk_pll.ref)
6069                 goto sanitize;
6070
6071         /* DPLL okay; verify the cdclock
6072          *
6073          * Some BIOS versions leave an incorrect decimal frequency value and
6074          * set reserved MBZ bits in CDCLK_CTL at least during exiting from S4,
6075          * so sanitize this register.
6076          */
6077         cdctl = I915_READ(CDCLK_CTL);
6078         /*
6079          * Let's ignore the pipe field, since BIOS could have configured the
6080          * dividers both synching to an active pipe, or asynchronously
6081          * (PIPE_NONE).
6082          */
6083         cdctl &= ~BXT_CDCLK_CD2X_PIPE_NONE;
6084
6085         expected = (cdctl & BXT_CDCLK_CD2X_DIV_SEL_MASK) |
6086                    skl_cdclk_decimal(dev_priv->cdclk_freq);
6087         /*
6088          * Disable SSA Precharge when CD clock frequency < 500 MHz,
6089          * enable otherwise.
6090          */
6091         if (dev_priv->cdclk_freq >= 500000)
6092                 expected |= BXT_CDCLK_SSA_PRECHARGE_ENABLE;
6093
6094         if (cdctl == expected)
6095                 /* All well; nothing to sanitize */
6096                 return;
6097
6098 sanitize:
6099         DRM_DEBUG_KMS("Sanitizing cdclk programmed by pre-os\n");
6100
6101         /* force cdclk programming */
6102         dev_priv->cdclk_freq = 0;
6103
6104         /* force full PLL disable + enable */
6105         dev_priv->cdclk_pll.vco = -1;
6106 }
6107
6108 void bxt_init_cdclk(struct drm_i915_private *dev_priv)
6109 {
6110         bxt_sanitize_cdclk(dev_priv);
6111
6112         if (dev_priv->cdclk_freq != 0 && dev_priv->cdclk_pll.vco != 0)
6113                 return;
6114
6115         /*
6116          * FIXME:
6117          * - The initial CDCLK needs to be read from VBT.
6118          *   Need to make this change after VBT has changes for BXT.
6119          */
6120         bxt_set_cdclk(dev_priv, bxt_calc_cdclk(0));
6121 }
6122
6123 void bxt_uninit_cdclk(struct drm_i915_private *dev_priv)
6124 {
6125         bxt_set_cdclk(dev_priv, dev_priv->cdclk_pll.ref);
6126 }
6127
6128 static int skl_calc_cdclk(int max_pixclk, int vco)
6129 {
6130         if (vco == 8640000) {
6131                 if (max_pixclk > 540000)
6132                         return 617143;
6133                 else if (max_pixclk > 432000)
6134                         return 540000;
6135                 else if (max_pixclk > 308571)
6136                         return 432000;
6137                 else
6138                         return 308571;
6139         } else {
6140                 if (max_pixclk > 540000)
6141                         return 675000;
6142                 else if (max_pixclk > 450000)
6143                         return 540000;
6144                 else if (max_pixclk > 337500)
6145                         return 450000;
6146                 else
6147                         return 337500;
6148         }
6149 }
6150
6151 static void
6152 skl_dpll0_update(struct drm_i915_private *dev_priv)
6153 {
6154         u32 val;
6155
6156         dev_priv->cdclk_pll.ref = 24000;
6157         dev_priv->cdclk_pll.vco = 0;
6158
6159         val = I915_READ(LCPLL1_CTL);
6160         if ((val & LCPLL_PLL_ENABLE) == 0)
6161                 return;
6162
6163         if (WARN_ON((val & LCPLL_PLL_LOCK) == 0))
6164                 return;
6165
6166         val = I915_READ(DPLL_CTRL1);
6167
6168         if (WARN_ON((val & (DPLL_CTRL1_HDMI_MODE(SKL_DPLL0) |
6169                             DPLL_CTRL1_SSC(SKL_DPLL0) |
6170                             DPLL_CTRL1_OVERRIDE(SKL_DPLL0))) !=
6171                     DPLL_CTRL1_OVERRIDE(SKL_DPLL0)))
6172                 return;
6173
6174         switch (val & DPLL_CTRL1_LINK_RATE_MASK(SKL_DPLL0)) {
6175         case DPLL_CTRL1_LINK_RATE(DPLL_CTRL1_LINK_RATE_810, SKL_DPLL0):
6176         case DPLL_CTRL1_LINK_RATE(DPLL_CTRL1_LINK_RATE_1350, SKL_DPLL0):
6177         case DPLL_CTRL1_LINK_RATE(DPLL_CTRL1_LINK_RATE_1620, SKL_DPLL0):
6178         case DPLL_CTRL1_LINK_RATE(DPLL_CTRL1_LINK_RATE_2700, SKL_DPLL0):
6179                 dev_priv->cdclk_pll.vco = 8100000;
6180                 break;
6181         case DPLL_CTRL1_LINK_RATE(DPLL_CTRL1_LINK_RATE_1080, SKL_DPLL0):
6182         case DPLL_CTRL1_LINK_RATE(DPLL_CTRL1_LINK_RATE_2160, SKL_DPLL0):
6183                 dev_priv->cdclk_pll.vco = 8640000;
6184                 break;
6185         default:
6186                 MISSING_CASE(val & DPLL_CTRL1_LINK_RATE_MASK(SKL_DPLL0));
6187                 break;
6188         }
6189 }
6190
6191 void skl_set_preferred_cdclk_vco(struct drm_i915_private *dev_priv, int vco)
6192 {
6193         bool changed = dev_priv->skl_preferred_vco_freq != vco;
6194
6195         dev_priv->skl_preferred_vco_freq = vco;
6196
6197         if (changed)
6198                 intel_update_max_cdclk(&dev_priv->drm);
6199 }
6200
6201 static void
6202 skl_dpll0_enable(struct drm_i915_private *dev_priv, int vco)
6203 {
6204         int min_cdclk = skl_calc_cdclk(0, vco);
6205         u32 val;
6206
6207         WARN_ON(vco != 8100000 && vco != 8640000);
6208
6209         /* select the minimum CDCLK before enabling DPLL 0 */
6210         val = CDCLK_FREQ_337_308 | skl_cdclk_decimal(min_cdclk);
6211         I915_WRITE(CDCLK_CTL, val);
6212         POSTING_READ(CDCLK_CTL);
6213
6214         /*
6215          * We always enable DPLL0 with the lowest link rate possible, but still
6216          * taking into account the VCO required to operate the eDP panel at the
6217          * desired frequency. The usual DP link rates operate with a VCO of
6218          * 8100 while the eDP 1.4 alternate link rates need a VCO of 8640.
6219          * The modeset code is responsible for the selection of the exact link
6220          * rate later on, with the constraint of choosing a frequency that
6221          * works with vco.
6222          */
6223         val = I915_READ(DPLL_CTRL1);
6224
6225         val &= ~(DPLL_CTRL1_HDMI_MODE(SKL_DPLL0) | DPLL_CTRL1_SSC(SKL_DPLL0) |
6226                  DPLL_CTRL1_LINK_RATE_MASK(SKL_DPLL0));
6227         val |= DPLL_CTRL1_OVERRIDE(SKL_DPLL0);
6228         if (vco == 8640000)
6229                 val |= DPLL_CTRL1_LINK_RATE(DPLL_CTRL1_LINK_RATE_1080,
6230                                             SKL_DPLL0);
6231         else
6232                 val |= DPLL_CTRL1_LINK_RATE(DPLL_CTRL1_LINK_RATE_810,
6233                                             SKL_DPLL0);
6234
6235         I915_WRITE(DPLL_CTRL1, val);
6236         POSTING_READ(DPLL_CTRL1);
6237
6238         I915_WRITE(LCPLL1_CTL, I915_READ(LCPLL1_CTL) | LCPLL_PLL_ENABLE);
6239
6240         if (intel_wait_for_register(dev_priv,
6241                                     LCPLL1_CTL, LCPLL_PLL_LOCK, LCPLL_PLL_LOCK,
6242                                     5))
6243                 DRM_ERROR("DPLL0 not locked\n");
6244
6245         dev_priv->cdclk_pll.vco = vco;
6246
6247         /* We'll want to keep using the current vco from now on. */
6248         skl_set_preferred_cdclk_vco(dev_priv, vco);
6249 }
6250
6251 static void
6252 skl_dpll0_disable(struct drm_i915_private *dev_priv)
6253 {
6254         I915_WRITE(LCPLL1_CTL, I915_READ(LCPLL1_CTL) & ~LCPLL_PLL_ENABLE);
6255         if (intel_wait_for_register(dev_priv,
6256                                    LCPLL1_CTL, LCPLL_PLL_LOCK, 0,
6257                                    1))
6258                 DRM_ERROR("Couldn't disable DPLL0\n");
6259
6260         dev_priv->cdclk_pll.vco = 0;
6261 }
6262
6263 static void skl_set_cdclk(struct drm_i915_private *dev_priv, int cdclk, int vco)
6264 {
6265         struct drm_device *dev = &dev_priv->drm;
6266         u32 freq_select, pcu_ack;
6267         int ret;
6268
6269         WARN_ON((cdclk == 24000) != (vco == 0));
6270
6271         DRM_DEBUG_DRIVER("Changing CDCLK to %d kHz (VCO %d kHz)\n", cdclk, vco);
6272
6273         mutex_lock(&dev_priv->rps.hw_lock);
6274         ret = skl_pcode_request(dev_priv, SKL_PCODE_CDCLK_CONTROL,
6275                                 SKL_CDCLK_PREPARE_FOR_CHANGE,
6276                                 SKL_CDCLK_READY_FOR_CHANGE,
6277                                 SKL_CDCLK_READY_FOR_CHANGE, 3);
6278         mutex_unlock(&dev_priv->rps.hw_lock);
6279         if (ret) {
6280                 DRM_ERROR("Failed to inform PCU about cdclk change (%d)\n",
6281                           ret);
6282                 return;
6283         }
6284
6285         /* set CDCLK_CTL */
6286         switch (cdclk) {
6287         case 450000:
6288         case 432000:
6289                 freq_select = CDCLK_FREQ_450_432;
6290                 pcu_ack = 1;
6291                 break;
6292         case 540000:
6293                 freq_select = CDCLK_FREQ_540;
6294                 pcu_ack = 2;
6295                 break;
6296         case 308571:
6297         case 337500:
6298         default:
6299                 freq_select = CDCLK_FREQ_337_308;
6300                 pcu_ack = 0;
6301                 break;
6302         case 617143:
6303         case 675000:
6304                 freq_select = CDCLK_FREQ_675_617;
6305                 pcu_ack = 3;
6306                 break;
6307         }
6308
6309         if (dev_priv->cdclk_pll.vco != 0 &&
6310             dev_priv->cdclk_pll.vco != vco)
6311                 skl_dpll0_disable(dev_priv);
6312
6313         if (dev_priv->cdclk_pll.vco != vco)
6314                 skl_dpll0_enable(dev_priv, vco);
6315
6316         I915_WRITE(CDCLK_CTL, freq_select | skl_cdclk_decimal(cdclk));
6317         POSTING_READ(CDCLK_CTL);
6318
6319         /* inform PCU of the change */
6320         mutex_lock(&dev_priv->rps.hw_lock);
6321         sandybridge_pcode_write(dev_priv, SKL_PCODE_CDCLK_CONTROL, pcu_ack);
6322         mutex_unlock(&dev_priv->rps.hw_lock);
6323
6324         intel_update_cdclk(dev);
6325 }
6326
6327 static void skl_sanitize_cdclk(struct drm_i915_private *dev_priv);
6328
6329 void skl_uninit_cdclk(struct drm_i915_private *dev_priv)
6330 {
6331         skl_set_cdclk(dev_priv, dev_priv->cdclk_pll.ref, 0);
6332 }
6333
6334 void skl_init_cdclk(struct drm_i915_private *dev_priv)
6335 {
6336         int cdclk, vco;
6337
6338         skl_sanitize_cdclk(dev_priv);
6339
6340         if (dev_priv->cdclk_freq != 0 && dev_priv->cdclk_pll.vco != 0) {
6341                 /*
6342                  * Use the current vco as our initial
6343                  * guess as to what the preferred vco is.
6344                  */
6345                 if (dev_priv->skl_preferred_vco_freq == 0)
6346                         skl_set_preferred_cdclk_vco(dev_priv,
6347                                                     dev_priv->cdclk_pll.vco);
6348                 return;
6349         }
6350
6351         vco = dev_priv->skl_preferred_vco_freq;
6352         if (vco == 0)
6353                 vco = 8100000;
6354         cdclk = skl_calc_cdclk(0, vco);
6355
6356         skl_set_cdclk(dev_priv, cdclk, vco);
6357 }
6358
6359 static void skl_sanitize_cdclk(struct drm_i915_private *dev_priv)
6360 {
6361         uint32_t cdctl, expected;
6362
6363         /*
6364          * check if the pre-os intialized the display
6365          * There is SWF18 scratchpad register defined which is set by the
6366          * pre-os which can be used by the OS drivers to check the status
6367          */
6368         if ((I915_READ(SWF_ILK(0x18)) & 0x00FFFFFF) == 0)
6369                 goto sanitize;
6370
6371         intel_update_cdclk(&dev_priv->drm);
6372         /* Is PLL enabled and locked ? */
6373         if (dev_priv->cdclk_pll.vco == 0 ||
6374             dev_priv->cdclk_freq == dev_priv->cdclk_pll.ref)
6375                 goto sanitize;
6376
6377         /* DPLL okay; verify the cdclock
6378          *
6379          * Noticed in some instances that the freq selection is correct but
6380          * decimal part is programmed wrong from BIOS where pre-os does not
6381          * enable display. Verify the same as well.
6382          */
6383         cdctl = I915_READ(CDCLK_CTL);
6384         expected = (cdctl & CDCLK_FREQ_SEL_MASK) |
6385                 skl_cdclk_decimal(dev_priv->cdclk_freq);
6386         if (cdctl == expected)
6387                 /* All well; nothing to sanitize */
6388                 return;
6389
6390 sanitize:
6391         DRM_DEBUG_KMS("Sanitizing cdclk programmed by pre-os\n");
6392
6393         /* force cdclk programming */
6394         dev_priv->cdclk_freq = 0;
6395         /* force full PLL disable + enable */
6396         dev_priv->cdclk_pll.vco = -1;
6397 }
6398
6399 /* Adjust CDclk dividers to allow high res or save power if possible */
6400 static void valleyview_set_cdclk(struct drm_device *dev, int cdclk)
6401 {
6402         struct drm_i915_private *dev_priv = to_i915(dev);
6403         u32 val, cmd;
6404
6405         WARN_ON(dev_priv->display.get_display_clock_speed(dev)
6406                                         != dev_priv->cdclk_freq);
6407
6408         if (cdclk >= 320000) /* jump to highest voltage for 400MHz too */
6409                 cmd = 2;
6410         else if (cdclk == 266667)
6411                 cmd = 1;
6412         else
6413                 cmd = 0;
6414
6415         mutex_lock(&dev_priv->rps.hw_lock);
6416         val = vlv_punit_read(dev_priv, PUNIT_REG_DSPFREQ);
6417         val &= ~DSPFREQGUAR_MASK;
6418         val |= (cmd << DSPFREQGUAR_SHIFT);
6419         vlv_punit_write(dev_priv, PUNIT_REG_DSPFREQ, val);
6420         if (wait_for((vlv_punit_read(dev_priv, PUNIT_REG_DSPFREQ) &
6421                       DSPFREQSTAT_MASK) == (cmd << DSPFREQSTAT_SHIFT),
6422                      50)) {
6423                 DRM_ERROR("timed out waiting for CDclk change\n");
6424         }
6425         mutex_unlock(&dev_priv->rps.hw_lock);
6426
6427         mutex_lock(&dev_priv->sb_lock);
6428
6429         if (cdclk == 400000) {
6430                 u32 divider;
6431
6432                 divider = DIV_ROUND_CLOSEST(dev_priv->hpll_freq << 1, cdclk) - 1;
6433
6434                 /* adjust cdclk divider */
6435                 val = vlv_cck_read(dev_priv, CCK_DISPLAY_CLOCK_CONTROL);
6436                 val &= ~CCK_FREQUENCY_VALUES;
6437                 val |= divider;
6438                 vlv_cck_write(dev_priv, CCK_DISPLAY_CLOCK_CONTROL, val);
6439
6440                 if (wait_for((vlv_cck_read(dev_priv, CCK_DISPLAY_CLOCK_CONTROL) &
6441                               CCK_FREQUENCY_STATUS) == (divider << CCK_FREQUENCY_STATUS_SHIFT),
6442                              50))
6443                         DRM_ERROR("timed out waiting for CDclk change\n");
6444         }
6445
6446         /* adjust self-refresh exit latency value */
6447         val = vlv_bunit_read(dev_priv, BUNIT_REG_BISOC);
6448         val &= ~0x7f;
6449
6450         /*
6451          * For high bandwidth configs, we set a higher latency in the bunit
6452          * so that the core display fetch happens in time to avoid underruns.
6453          */
6454         if (cdclk == 400000)
6455                 val |= 4500 / 250; /* 4.5 usec */
6456         else
6457                 val |= 3000 / 250; /* 3.0 usec */
6458         vlv_bunit_write(dev_priv, BUNIT_REG_BISOC, val);
6459
6460         mutex_unlock(&dev_priv->sb_lock);
6461
6462         intel_update_cdclk(dev);
6463 }
6464
6465 static void cherryview_set_cdclk(struct drm_device *dev, int cdclk)
6466 {
6467         struct drm_i915_private *dev_priv = to_i915(dev);
6468         u32 val, cmd;
6469
6470         WARN_ON(dev_priv->display.get_display_clock_speed(dev)
6471                                                 != dev_priv->cdclk_freq);
6472
6473         switch (cdclk) {
6474         case 333333:
6475         case 320000:
6476         case 266667:
6477         case 200000:
6478                 break;
6479         default:
6480                 MISSING_CASE(cdclk);
6481                 return;
6482         }
6483
6484         /*
6485          * Specs are full of misinformation, but testing on actual
6486          * hardware has shown that we just need to write the desired
6487          * CCK divider into the Punit register.
6488          */
6489         cmd = DIV_ROUND_CLOSEST(dev_priv->hpll_freq << 1, cdclk) - 1;
6490
6491         mutex_lock(&dev_priv->rps.hw_lock);
6492         val = vlv_punit_read(dev_priv, PUNIT_REG_DSPFREQ);
6493         val &= ~DSPFREQGUAR_MASK_CHV;
6494         val |= (cmd << DSPFREQGUAR_SHIFT_CHV);
6495         vlv_punit_write(dev_priv, PUNIT_REG_DSPFREQ, val);
6496         if (wait_for((vlv_punit_read(dev_priv, PUNIT_REG_DSPFREQ) &
6497                       DSPFREQSTAT_MASK_CHV) == (cmd << DSPFREQSTAT_SHIFT_CHV),
6498                      50)) {
6499                 DRM_ERROR("timed out waiting for CDclk change\n");
6500         }
6501         mutex_unlock(&dev_priv->rps.hw_lock);
6502
6503         intel_update_cdclk(dev);
6504 }
6505
6506 static int valleyview_calc_cdclk(struct drm_i915_private *dev_priv,
6507                                  int max_pixclk)
6508 {
6509         int freq_320 = (dev_priv->hpll_freq <<  1) % 320000 != 0 ? 333333 : 320000;
6510         int limit = IS_CHERRYVIEW(dev_priv) ? 95 : 90;
6511
6512         /*
6513          * Really only a few cases to deal with, as only 4 CDclks are supported:
6514          *   200MHz
6515          *   267MHz
6516          *   320/333MHz (depends on HPLL freq)
6517          *   400MHz (VLV only)
6518          * So we check to see whether we're above 90% (VLV) or 95% (CHV)
6519          * of the lower bin and adjust if needed.
6520          *
6521          * We seem to get an unstable or solid color picture at 200MHz.
6522          * Not sure what's wrong. For now use 200MHz only when all pipes
6523          * are off.
6524          */
6525         if (!IS_CHERRYVIEW(dev_priv) &&
6526             max_pixclk > freq_320*limit/100)
6527                 return 400000;
6528         else if (max_pixclk > 266667*limit/100)
6529                 return freq_320;
6530         else if (max_pixclk > 0)
6531                 return 266667;
6532         else
6533                 return 200000;
6534 }
6535
6536 static int bxt_calc_cdclk(int max_pixclk)
6537 {
6538         if (max_pixclk > 576000)
6539                 return 624000;
6540         else if (max_pixclk > 384000)
6541                 return 576000;
6542         else if (max_pixclk > 288000)
6543                 return 384000;
6544         else if (max_pixclk > 144000)
6545                 return 288000;
6546         else
6547                 return 144000;
6548 }
6549
6550 /* Compute the max pixel clock for new configuration. */
6551 static int intel_mode_max_pixclk(struct drm_device *dev,
6552                                  struct drm_atomic_state *state)
6553 {
6554         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
6555         struct drm_i915_private *dev_priv = to_i915(dev);
6556         struct drm_crtc *crtc;
6557         struct drm_crtc_state *crtc_state;
6558         unsigned max_pixclk = 0, i;
6559         enum pipe pipe;
6560
6561         memcpy(intel_state->min_pixclk, dev_priv->min_pixclk,
6562                sizeof(intel_state->min_pixclk));
6563
6564         for_each_crtc_in_state(state, crtc, crtc_state, i) {
6565                 int pixclk = 0;
6566
6567                 if (crtc_state->enable)
6568                         pixclk = crtc_state->adjusted_mode.crtc_clock;
6569
6570                 intel_state->min_pixclk[i] = pixclk;
6571         }
6572
6573         for_each_pipe(dev_priv, pipe)
6574                 max_pixclk = max(intel_state->min_pixclk[pipe], max_pixclk);
6575
6576         return max_pixclk;
6577 }
6578
6579 static int valleyview_modeset_calc_cdclk(struct drm_atomic_state *state)
6580 {
6581         struct drm_device *dev = state->dev;
6582         struct drm_i915_private *dev_priv = to_i915(dev);
6583         int max_pixclk = intel_mode_max_pixclk(dev, state);
6584         struct intel_atomic_state *intel_state =
6585                 to_intel_atomic_state(state);
6586
6587         intel_state->cdclk = intel_state->dev_cdclk =
6588                 valleyview_calc_cdclk(dev_priv, max_pixclk);
6589
6590         if (!intel_state->active_crtcs)
6591                 intel_state->dev_cdclk = valleyview_calc_cdclk(dev_priv, 0);
6592
6593         return 0;
6594 }
6595
6596 static int bxt_modeset_calc_cdclk(struct drm_atomic_state *state)
6597 {
6598         int max_pixclk = ilk_max_pixel_rate(state);
6599         struct intel_atomic_state *intel_state =
6600                 to_intel_atomic_state(state);
6601
6602         intel_state->cdclk = intel_state->dev_cdclk =
6603                 bxt_calc_cdclk(max_pixclk);
6604
6605         if (!intel_state->active_crtcs)
6606                 intel_state->dev_cdclk = bxt_calc_cdclk(0);
6607
6608         return 0;
6609 }
6610
6611 static void vlv_program_pfi_credits(struct drm_i915_private *dev_priv)
6612 {
6613         unsigned int credits, default_credits;
6614
6615         if (IS_CHERRYVIEW(dev_priv))
6616                 default_credits = PFI_CREDIT(12);
6617         else
6618                 default_credits = PFI_CREDIT(8);
6619
6620         if (dev_priv->cdclk_freq >= dev_priv->czclk_freq) {
6621                 /* CHV suggested value is 31 or 63 */
6622                 if (IS_CHERRYVIEW(dev_priv))
6623                         credits = PFI_CREDIT_63;
6624                 else
6625                         credits = PFI_CREDIT(15);
6626         } else {
6627                 credits = default_credits;
6628         }
6629
6630         /*
6631          * WA - write default credits before re-programming
6632          * FIXME: should we also set the resend bit here?
6633          */
6634         I915_WRITE(GCI_CONTROL, VGA_FAST_MODE_DISABLE |
6635                    default_credits);
6636
6637         I915_WRITE(GCI_CONTROL, VGA_FAST_MODE_DISABLE |
6638                    credits | PFI_CREDIT_RESEND);
6639
6640         /*
6641          * FIXME is this guaranteed to clear
6642          * immediately or should we poll for it?
6643          */
6644         WARN_ON(I915_READ(GCI_CONTROL) & PFI_CREDIT_RESEND);
6645 }
6646
6647 static void valleyview_modeset_commit_cdclk(struct drm_atomic_state *old_state)
6648 {
6649         struct drm_device *dev = old_state->dev;
6650         struct drm_i915_private *dev_priv = to_i915(dev);
6651         struct intel_atomic_state *old_intel_state =
6652                 to_intel_atomic_state(old_state);
6653         unsigned req_cdclk = old_intel_state->dev_cdclk;
6654
6655         /*
6656          * FIXME: We can end up here with all power domains off, yet
6657          * with a CDCLK frequency other than the minimum. To account
6658          * for this take the PIPE-A power domain, which covers the HW
6659          * blocks needed for the following programming. This can be
6660          * removed once it's guaranteed that we get here either with
6661          * the minimum CDCLK set, or the required power domains
6662          * enabled.
6663          */
6664         intel_display_power_get(dev_priv, POWER_DOMAIN_PIPE_A);
6665
6666         if (IS_CHERRYVIEW(dev))
6667                 cherryview_set_cdclk(dev, req_cdclk);
6668         else
6669                 valleyview_set_cdclk(dev, req_cdclk);
6670
6671         vlv_program_pfi_credits(dev_priv);
6672
6673         intel_display_power_put(dev_priv, POWER_DOMAIN_PIPE_A);
6674 }
6675
6676 static void valleyview_crtc_enable(struct intel_crtc_state *pipe_config,
6677                                    struct drm_atomic_state *old_state)
6678 {
6679         struct drm_crtc *crtc = pipe_config->base.crtc;
6680         struct drm_device *dev = crtc->dev;
6681         struct drm_i915_private *dev_priv = to_i915(dev);
6682         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
6683         int pipe = intel_crtc->pipe;
6684
6685         if (WARN_ON(intel_crtc->active))
6686                 return;
6687
6688         if (intel_crtc_has_dp_encoder(intel_crtc->config))
6689                 intel_dp_set_m_n(intel_crtc, M1_N1);
6690
6691         intel_set_pipe_timings(intel_crtc);
6692         intel_set_pipe_src_size(intel_crtc);
6693
6694         if (IS_CHERRYVIEW(dev) && pipe == PIPE_B) {
6695                 struct drm_i915_private *dev_priv = to_i915(dev);
6696
6697                 I915_WRITE(CHV_BLEND(pipe), CHV_BLEND_LEGACY);
6698                 I915_WRITE(CHV_CANVAS(pipe), 0);
6699         }
6700
6701         i9xx_set_pipeconf(intel_crtc);
6702
6703         intel_crtc->active = true;
6704
6705         intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
6706
6707         intel_encoders_pre_pll_enable(crtc, pipe_config, old_state);
6708
6709         if (IS_CHERRYVIEW(dev)) {
6710                 chv_prepare_pll(intel_crtc, intel_crtc->config);
6711                 chv_enable_pll(intel_crtc, intel_crtc->config);
6712         } else {
6713                 vlv_prepare_pll(intel_crtc, intel_crtc->config);
6714                 vlv_enable_pll(intel_crtc, intel_crtc->config);
6715         }
6716
6717         intel_encoders_pre_enable(crtc, pipe_config, old_state);
6718
6719         i9xx_pfit_enable(intel_crtc);
6720
6721         intel_color_load_luts(&pipe_config->base);
6722
6723         intel_update_watermarks(crtc);
6724         intel_enable_pipe(intel_crtc);
6725
6726         assert_vblank_disabled(crtc);
6727         drm_crtc_vblank_on(crtc);
6728
6729         intel_encoders_enable(crtc, pipe_config, old_state);
6730 }
6731
6732 static void i9xx_set_pll_dividers(struct intel_crtc *crtc)
6733 {
6734         struct drm_device *dev = crtc->base.dev;
6735         struct drm_i915_private *dev_priv = to_i915(dev);
6736
6737         I915_WRITE(FP0(crtc->pipe), crtc->config->dpll_hw_state.fp0);
6738         I915_WRITE(FP1(crtc->pipe), crtc->config->dpll_hw_state.fp1);
6739 }
6740
6741 static void i9xx_crtc_enable(struct intel_crtc_state *pipe_config,
6742                              struct drm_atomic_state *old_state)
6743 {
6744         struct drm_crtc *crtc = pipe_config->base.crtc;
6745         struct drm_device *dev = crtc->dev;
6746         struct drm_i915_private *dev_priv = to_i915(dev);
6747         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
6748         enum pipe pipe = intel_crtc->pipe;
6749
6750         if (WARN_ON(intel_crtc->active))
6751                 return;
6752
6753         i9xx_set_pll_dividers(intel_crtc);
6754
6755         if (intel_crtc_has_dp_encoder(intel_crtc->config))
6756                 intel_dp_set_m_n(intel_crtc, M1_N1);
6757
6758         intel_set_pipe_timings(intel_crtc);
6759         intel_set_pipe_src_size(intel_crtc);
6760
6761         i9xx_set_pipeconf(intel_crtc);
6762
6763         intel_crtc->active = true;
6764
6765         if (!IS_GEN2(dev))
6766                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
6767
6768         intel_encoders_pre_enable(crtc, pipe_config, old_state);
6769
6770         i9xx_enable_pll(intel_crtc);
6771
6772         i9xx_pfit_enable(intel_crtc);
6773
6774         intel_color_load_luts(&pipe_config->base);
6775
6776         intel_update_watermarks(crtc);
6777         intel_enable_pipe(intel_crtc);
6778
6779         assert_vblank_disabled(crtc);
6780         drm_crtc_vblank_on(crtc);
6781
6782         intel_encoders_enable(crtc, pipe_config, old_state);
6783 }
6784
6785 static void i9xx_pfit_disable(struct intel_crtc *crtc)
6786 {
6787         struct drm_device *dev = crtc->base.dev;
6788         struct drm_i915_private *dev_priv = to_i915(dev);
6789
6790         if (!crtc->config->gmch_pfit.control)
6791                 return;
6792
6793         assert_pipe_disabled(dev_priv, crtc->pipe);
6794
6795         DRM_DEBUG_DRIVER("disabling pfit, current: 0x%08x\n",
6796                          I915_READ(PFIT_CONTROL));
6797         I915_WRITE(PFIT_CONTROL, 0);
6798 }
6799
6800 static void i9xx_crtc_disable(struct intel_crtc_state *old_crtc_state,
6801                               struct drm_atomic_state *old_state)
6802 {
6803         struct drm_crtc *crtc = old_crtc_state->base.crtc;
6804         struct drm_device *dev = crtc->dev;
6805         struct drm_i915_private *dev_priv = to_i915(dev);
6806         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
6807         int pipe = intel_crtc->pipe;
6808
6809         /*
6810          * On gen2 planes are double buffered but the pipe isn't, so we must
6811          * wait for planes to fully turn off before disabling the pipe.
6812          */
6813         if (IS_GEN2(dev))
6814                 intel_wait_for_vblank(dev, pipe);
6815
6816         intel_encoders_disable(crtc, old_crtc_state, old_state);
6817
6818         drm_crtc_vblank_off(crtc);
6819         assert_vblank_disabled(crtc);
6820
6821         intel_disable_pipe(intel_crtc);
6822
6823         i9xx_pfit_disable(intel_crtc);
6824
6825         intel_encoders_post_disable(crtc, old_crtc_state, old_state);
6826
6827         if (!intel_crtc_has_type(intel_crtc->config, INTEL_OUTPUT_DSI)) {
6828                 if (IS_CHERRYVIEW(dev))
6829                         chv_disable_pll(dev_priv, pipe);
6830                 else if (IS_VALLEYVIEW(dev))
6831                         vlv_disable_pll(dev_priv, pipe);
6832                 else
6833                         i9xx_disable_pll(intel_crtc);
6834         }
6835
6836         intel_encoders_post_pll_disable(crtc, old_crtc_state, old_state);
6837
6838         if (!IS_GEN2(dev))
6839                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
6840 }
6841
6842 static void intel_crtc_disable_noatomic(struct drm_crtc *crtc)
6843 {
6844         struct intel_encoder *encoder;
6845         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
6846         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
6847         enum intel_display_power_domain domain;
6848         unsigned long domains;
6849         struct drm_atomic_state *state;
6850         struct intel_crtc_state *crtc_state;
6851         int ret;
6852
6853         if (!intel_crtc->active)
6854                 return;
6855
6856         if (to_intel_plane_state(crtc->primary->state)->base.visible) {
6857                 WARN_ON(intel_crtc->flip_work);
6858
6859                 intel_pre_disable_primary_noatomic(crtc);
6860
6861                 intel_crtc_disable_planes(crtc, 1 << drm_plane_index(crtc->primary));
6862                 to_intel_plane_state(crtc->primary->state)->base.visible = false;
6863         }
6864
6865         state = drm_atomic_state_alloc(crtc->dev);
6866         if (!state) {
6867                 DRM_DEBUG_KMS("failed to disable [CRTC:%d:%s], out of memory",
6868                               crtc->base.id, crtc->name);
6869                 return;
6870         }
6871
6872         state->acquire_ctx = crtc->dev->mode_config.acquire_ctx;
6873
6874         /* Everything's already locked, -EDEADLK can't happen. */
6875         crtc_state = intel_atomic_get_crtc_state(state, intel_crtc);
6876         ret = drm_atomic_add_affected_connectors(state, crtc);
6877
6878         WARN_ON(IS_ERR(crtc_state) || ret);
6879
6880         dev_priv->display.crtc_disable(crtc_state, state);
6881
6882         drm_atomic_state_free(state);
6883
6884         DRM_DEBUG_KMS("[CRTC:%d:%s] hw state adjusted, was enabled, now disabled\n",
6885                       crtc->base.id, crtc->name);
6886
6887         WARN_ON(drm_atomic_set_mode_for_crtc(crtc->state, NULL) < 0);
6888         crtc->state->active = false;
6889         intel_crtc->active = false;
6890         crtc->enabled = false;
6891         crtc->state->connector_mask = 0;
6892         crtc->state->encoder_mask = 0;
6893
6894         for_each_encoder_on_crtc(crtc->dev, crtc, encoder)
6895                 encoder->base.crtc = NULL;
6896
6897         intel_fbc_disable(intel_crtc);
6898         intel_update_watermarks(crtc);
6899         intel_disable_shared_dpll(intel_crtc);
6900
6901         domains = intel_crtc->enabled_power_domains;
6902         for_each_power_domain(domain, domains)
6903                 intel_display_power_put(dev_priv, domain);
6904         intel_crtc->enabled_power_domains = 0;
6905
6906         dev_priv->active_crtcs &= ~(1 << intel_crtc->pipe);
6907         dev_priv->min_pixclk[intel_crtc->pipe] = 0;
6908 }
6909
6910 /*
6911  * turn all crtc's off, but do not adjust state
6912  * This has to be paired with a call to intel_modeset_setup_hw_state.
6913  */
6914 int intel_display_suspend(struct drm_device *dev)
6915 {
6916         struct drm_i915_private *dev_priv = to_i915(dev);
6917         struct drm_atomic_state *state;
6918         int ret;
6919
6920         state = drm_atomic_helper_suspend(dev);
6921         ret = PTR_ERR_OR_ZERO(state);
6922         if (ret)
6923                 DRM_ERROR("Suspending crtc's failed with %i\n", ret);
6924         else
6925                 dev_priv->modeset_restore_state = state;
6926         return ret;
6927 }
6928
6929 void intel_encoder_destroy(struct drm_encoder *encoder)
6930 {
6931         struct intel_encoder *intel_encoder = to_intel_encoder(encoder);
6932
6933         drm_encoder_cleanup(encoder);
6934         kfree(intel_encoder);
6935 }
6936
6937 /* Cross check the actual hw state with our own modeset state tracking (and it's
6938  * internal consistency). */
6939 static void intel_connector_verify_state(struct intel_connector *connector)
6940 {
6941         struct drm_crtc *crtc = connector->base.state->crtc;
6942
6943         DRM_DEBUG_KMS("[CONNECTOR:%d:%s]\n",
6944                       connector->base.base.id,
6945                       connector->base.name);
6946
6947         if (connector->get_hw_state(connector)) {
6948                 struct intel_encoder *encoder = connector->encoder;
6949                 struct drm_connector_state *conn_state = connector->base.state;
6950
6951                 I915_STATE_WARN(!crtc,
6952                          "connector enabled without attached crtc\n");
6953
6954                 if (!crtc)
6955                         return;
6956
6957                 I915_STATE_WARN(!crtc->state->active,
6958                       "connector is active, but attached crtc isn't\n");
6959
6960                 if (!encoder || encoder->type == INTEL_OUTPUT_DP_MST)
6961                         return;
6962
6963                 I915_STATE_WARN(conn_state->best_encoder != &encoder->base,
6964                         "atomic encoder doesn't match attached encoder\n");
6965
6966                 I915_STATE_WARN(conn_state->crtc != encoder->base.crtc,
6967                         "attached encoder crtc differs from connector crtc\n");
6968         } else {
6969                 I915_STATE_WARN(crtc && crtc->state->active,
6970                         "attached crtc is active, but connector isn't\n");
6971                 I915_STATE_WARN(!crtc && connector->base.state->best_encoder,
6972                         "best encoder set without crtc!\n");
6973         }
6974 }
6975
6976 int intel_connector_init(struct intel_connector *connector)
6977 {
6978         drm_atomic_helper_connector_reset(&connector->base);
6979
6980         if (!connector->base.state)
6981                 return -ENOMEM;
6982
6983         return 0;
6984 }
6985
6986 struct intel_connector *intel_connector_alloc(void)
6987 {
6988         struct intel_connector *connector;
6989
6990         connector = kzalloc(sizeof *connector, GFP_KERNEL);
6991         if (!connector)
6992                 return NULL;
6993
6994         if (intel_connector_init(connector) < 0) {
6995                 kfree(connector);
6996                 return NULL;
6997         }
6998
6999         return connector;
7000 }
7001
7002 /* Simple connector->get_hw_state implementation for encoders that support only
7003  * one connector and no cloning and hence the encoder state determines the state
7004  * of the connector. */
7005 bool intel_connector_get_hw_state(struct intel_connector *connector)
7006 {
7007         enum pipe pipe = 0;
7008         struct intel_encoder *encoder = connector->encoder;
7009
7010         return encoder->get_hw_state(encoder, &pipe);
7011 }
7012
7013 static int pipe_required_fdi_lanes(struct intel_crtc_state *crtc_state)
7014 {
7015         if (crtc_state->base.enable && crtc_state->has_pch_encoder)
7016                 return crtc_state->fdi_lanes;
7017
7018         return 0;
7019 }
7020
7021 static int ironlake_check_fdi_lanes(struct drm_device *dev, enum pipe pipe,
7022                                      struct intel_crtc_state *pipe_config)
7023 {
7024         struct drm_atomic_state *state = pipe_config->base.state;
7025         struct intel_crtc *other_crtc;
7026         struct intel_crtc_state *other_crtc_state;
7027
7028         DRM_DEBUG_KMS("checking fdi config on pipe %c, lanes %i\n",
7029                       pipe_name(pipe), pipe_config->fdi_lanes);
7030         if (pipe_config->fdi_lanes > 4) {
7031                 DRM_DEBUG_KMS("invalid fdi lane config on pipe %c: %i lanes\n",
7032                               pipe_name(pipe), pipe_config->fdi_lanes);
7033                 return -EINVAL;
7034         }
7035
7036         if (IS_HASWELL(dev) || IS_BROADWELL(dev)) {
7037                 if (pipe_config->fdi_lanes > 2) {
7038                         DRM_DEBUG_KMS("only 2 lanes on haswell, required: %i lanes\n",
7039                                       pipe_config->fdi_lanes);
7040                         return -EINVAL;
7041                 } else {
7042                         return 0;
7043                 }
7044         }
7045
7046         if (INTEL_INFO(dev)->num_pipes == 2)
7047                 return 0;
7048
7049         /* Ivybridge 3 pipe is really complicated */
7050         switch (pipe) {
7051         case PIPE_A:
7052                 return 0;
7053         case PIPE_B:
7054                 if (pipe_config->fdi_lanes <= 2)
7055                         return 0;
7056
7057                 other_crtc = to_intel_crtc(intel_get_crtc_for_pipe(dev, PIPE_C));
7058                 other_crtc_state =
7059                         intel_atomic_get_crtc_state(state, other_crtc);
7060                 if (IS_ERR(other_crtc_state))
7061                         return PTR_ERR(other_crtc_state);
7062
7063                 if (pipe_required_fdi_lanes(other_crtc_state) > 0) {
7064                         DRM_DEBUG_KMS("invalid shared fdi lane config on pipe %c: %i lanes\n",
7065                                       pipe_name(pipe), pipe_config->fdi_lanes);
7066                         return -EINVAL;
7067                 }
7068                 return 0;
7069         case PIPE_C:
7070                 if (pipe_config->fdi_lanes > 2) {
7071                         DRM_DEBUG_KMS("only 2 lanes on pipe %c: required %i lanes\n",
7072                                       pipe_name(pipe), pipe_config->fdi_lanes);
7073                         return -EINVAL;
7074                 }
7075
7076                 other_crtc = to_intel_crtc(intel_get_crtc_for_pipe(dev, PIPE_B));
7077                 other_crtc_state =
7078                         intel_atomic_get_crtc_state(state, other_crtc);
7079                 if (IS_ERR(other_crtc_state))
7080                         return PTR_ERR(other_crtc_state);
7081
7082                 if (pipe_required_fdi_lanes(other_crtc_state) > 2) {
7083                         DRM_DEBUG_KMS("fdi link B uses too many lanes to enable link C\n");
7084                         return -EINVAL;
7085                 }
7086                 return 0;
7087         default:
7088                 BUG();
7089         }
7090 }
7091
7092 #define RETRY 1
7093 static int ironlake_fdi_compute_config(struct intel_crtc *intel_crtc,
7094                                        struct intel_crtc_state *pipe_config)
7095 {
7096         struct drm_device *dev = intel_crtc->base.dev;
7097         const struct drm_display_mode *adjusted_mode = &pipe_config->base.adjusted_mode;
7098         int lane, link_bw, fdi_dotclock, ret;
7099         bool needs_recompute = false;
7100
7101 retry:
7102         /* FDI is a binary signal running at ~2.7GHz, encoding
7103          * each output octet as 10 bits. The actual frequency
7104          * is stored as a divider into a 100MHz clock, and the
7105          * mode pixel clock is stored in units of 1KHz.
7106          * Hence the bw of each lane in terms of the mode signal
7107          * is:
7108          */
7109         link_bw = intel_fdi_link_freq(to_i915(dev), pipe_config);
7110
7111         fdi_dotclock = adjusted_mode->crtc_clock;
7112
7113         lane = ironlake_get_lanes_required(fdi_dotclock, link_bw,
7114                                            pipe_config->pipe_bpp);
7115
7116         pipe_config->fdi_lanes = lane;
7117
7118         intel_link_compute_m_n(pipe_config->pipe_bpp, lane, fdi_dotclock,
7119                                link_bw, &pipe_config->fdi_m_n);
7120
7121         ret = ironlake_check_fdi_lanes(dev, intel_crtc->pipe, pipe_config);
7122         if (ret == -EINVAL && pipe_config->pipe_bpp > 6*3) {
7123                 pipe_config->pipe_bpp -= 2*3;
7124                 DRM_DEBUG_KMS("fdi link bw constraint, reducing pipe bpp to %i\n",
7125                               pipe_config->pipe_bpp);
7126                 needs_recompute = true;
7127                 pipe_config->bw_constrained = true;
7128
7129                 goto retry;
7130         }
7131
7132         if (needs_recompute)
7133                 return RETRY;
7134
7135         return ret;
7136 }
7137
7138 static bool pipe_config_supports_ips(struct drm_i915_private *dev_priv,
7139                                      struct intel_crtc_state *pipe_config)
7140 {
7141         if (pipe_config->pipe_bpp > 24)
7142                 return false;
7143
7144         /* HSW can handle pixel rate up to cdclk? */
7145         if (IS_HASWELL(dev_priv))
7146                 return true;
7147
7148         /*
7149          * We compare against max which means we must take
7150          * the increased cdclk requirement into account when
7151          * calculating the new cdclk.
7152          *
7153          * Should measure whether using a lower cdclk w/o IPS
7154          */
7155         return ilk_pipe_pixel_rate(pipe_config) <=
7156                 dev_priv->max_cdclk_freq * 95 / 100;
7157 }
7158
7159 static void hsw_compute_ips_config(struct intel_crtc *crtc,
7160                                    struct intel_crtc_state *pipe_config)
7161 {
7162         struct drm_device *dev = crtc->base.dev;
7163         struct drm_i915_private *dev_priv = to_i915(dev);
7164
7165         pipe_config->ips_enabled = i915.enable_ips &&
7166                 hsw_crtc_supports_ips(crtc) &&
7167                 pipe_config_supports_ips(dev_priv, pipe_config);
7168 }
7169
7170 static bool intel_crtc_supports_double_wide(const struct intel_crtc *crtc)
7171 {
7172         const struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
7173
7174         /* GDG double wide on either pipe, otherwise pipe A only */
7175         return INTEL_INFO(dev_priv)->gen < 4 &&
7176                 (crtc->pipe == PIPE_A || IS_I915G(dev_priv));
7177 }
7178
7179 static int intel_crtc_compute_config(struct intel_crtc *crtc,
7180                                      struct intel_crtc_state *pipe_config)
7181 {
7182         struct drm_device *dev = crtc->base.dev;
7183         struct drm_i915_private *dev_priv = to_i915(dev);
7184         const struct drm_display_mode *adjusted_mode = &pipe_config->base.adjusted_mode;
7185         int clock_limit = dev_priv->max_dotclk_freq;
7186
7187         if (INTEL_INFO(dev)->gen < 4) {
7188                 clock_limit = dev_priv->max_cdclk_freq * 9 / 10;
7189
7190                 /*
7191                  * Enable double wide mode when the dot clock
7192                  * is > 90% of the (display) core speed.
7193                  */
7194                 if (intel_crtc_supports_double_wide(crtc) &&
7195                     adjusted_mode->crtc_clock > clock_limit) {
7196                         clock_limit = dev_priv->max_dotclk_freq;
7197                         pipe_config->double_wide = true;
7198                 }
7199         }
7200
7201         if (adjusted_mode->crtc_clock > clock_limit) {
7202                 DRM_DEBUG_KMS("requested pixel clock (%d kHz) too high (max: %d kHz, double wide: %s)\n",
7203                               adjusted_mode->crtc_clock, clock_limit,
7204                               yesno(pipe_config->double_wide));
7205                 return -EINVAL;
7206         }
7207
7208         /*
7209          * Pipe horizontal size must be even in:
7210          * - DVO ganged mode
7211          * - LVDS dual channel mode
7212          * - Double wide pipe
7213          */
7214         if ((intel_crtc_has_type(pipe_config, INTEL_OUTPUT_LVDS) &&
7215              intel_is_dual_link_lvds(dev)) || pipe_config->double_wide)
7216                 pipe_config->pipe_src_w &= ~1;
7217
7218         /* Cantiga+ cannot handle modes with a hsync front porch of 0.
7219          * WaPruneModeWithIncorrectHsyncOffset:ctg,elk,ilk,snb,ivb,vlv,hsw.
7220          */
7221         if ((INTEL_INFO(dev)->gen > 4 || IS_G4X(dev)) &&
7222                 adjusted_mode->crtc_hsync_start == adjusted_mode->crtc_hdisplay)
7223                 return -EINVAL;
7224
7225         if (HAS_IPS(dev))
7226                 hsw_compute_ips_config(crtc, pipe_config);
7227
7228         if (pipe_config->has_pch_encoder)
7229                 return ironlake_fdi_compute_config(crtc, pipe_config);
7230
7231         return 0;
7232 }
7233
7234 static int skylake_get_display_clock_speed(struct drm_device *dev)
7235 {
7236         struct drm_i915_private *dev_priv = to_i915(dev);
7237         uint32_t cdctl;
7238
7239         skl_dpll0_update(dev_priv);
7240
7241         if (dev_priv->cdclk_pll.vco == 0)
7242                 return dev_priv->cdclk_pll.ref;
7243
7244         cdctl = I915_READ(CDCLK_CTL);
7245
7246         if (dev_priv->cdclk_pll.vco == 8640000) {
7247                 switch (cdctl & CDCLK_FREQ_SEL_MASK) {
7248                 case CDCLK_FREQ_450_432:
7249                         return 432000;
7250                 case CDCLK_FREQ_337_308:
7251                         return 308571;
7252                 case CDCLK_FREQ_540:
7253                         return 540000;
7254                 case CDCLK_FREQ_675_617:
7255                         return 617143;
7256                 default:
7257                         MISSING_CASE(cdctl & CDCLK_FREQ_SEL_MASK);
7258                 }
7259         } else {
7260                 switch (cdctl & CDCLK_FREQ_SEL_MASK) {
7261                 case CDCLK_FREQ_450_432:
7262                         return 450000;
7263                 case CDCLK_FREQ_337_308:
7264                         return 337500;
7265                 case CDCLK_FREQ_540:
7266                         return 540000;
7267                 case CDCLK_FREQ_675_617:
7268                         return 675000;
7269                 default:
7270                         MISSING_CASE(cdctl & CDCLK_FREQ_SEL_MASK);
7271                 }
7272         }
7273
7274         return dev_priv->cdclk_pll.ref;
7275 }
7276
7277 static void bxt_de_pll_update(struct drm_i915_private *dev_priv)
7278 {
7279         u32 val;
7280
7281         dev_priv->cdclk_pll.ref = 19200;
7282         dev_priv->cdclk_pll.vco = 0;
7283
7284         val = I915_READ(BXT_DE_PLL_ENABLE);
7285         if ((val & BXT_DE_PLL_PLL_ENABLE) == 0)
7286                 return;
7287
7288         if (WARN_ON((val & BXT_DE_PLL_LOCK) == 0))
7289                 return;
7290
7291         val = I915_READ(BXT_DE_PLL_CTL);
7292         dev_priv->cdclk_pll.vco = (val & BXT_DE_PLL_RATIO_MASK) *
7293                 dev_priv->cdclk_pll.ref;
7294 }
7295
7296 static int broxton_get_display_clock_speed(struct drm_device *dev)
7297 {
7298         struct drm_i915_private *dev_priv = to_i915(dev);
7299         u32 divider;
7300         int div, vco;
7301
7302         bxt_de_pll_update(dev_priv);
7303
7304         vco = dev_priv->cdclk_pll.vco;
7305         if (vco == 0)
7306                 return dev_priv->cdclk_pll.ref;
7307
7308         divider = I915_READ(CDCLK_CTL) & BXT_CDCLK_CD2X_DIV_SEL_MASK;
7309
7310         switch (divider) {
7311         case BXT_CDCLK_CD2X_DIV_SEL_1:
7312                 div = 2;
7313                 break;
7314         case BXT_CDCLK_CD2X_DIV_SEL_1_5:
7315                 div = 3;
7316                 break;
7317         case BXT_CDCLK_CD2X_DIV_SEL_2:
7318                 div = 4;
7319                 break;
7320         case BXT_CDCLK_CD2X_DIV_SEL_4:
7321                 div = 8;
7322                 break;
7323         default:
7324                 MISSING_CASE(divider);
7325                 return dev_priv->cdclk_pll.ref;
7326         }
7327
7328         return DIV_ROUND_CLOSEST(vco, div);
7329 }
7330
7331 static int broadwell_get_display_clock_speed(struct drm_device *dev)
7332 {
7333         struct drm_i915_private *dev_priv = to_i915(dev);
7334         uint32_t lcpll = I915_READ(LCPLL_CTL);
7335         uint32_t freq = lcpll & LCPLL_CLK_FREQ_MASK;
7336
7337         if (lcpll & LCPLL_CD_SOURCE_FCLK)
7338                 return 800000;
7339         else if (I915_READ(FUSE_STRAP) & HSW_CDCLK_LIMIT)
7340                 return 450000;
7341         else if (freq == LCPLL_CLK_FREQ_450)
7342                 return 450000;
7343         else if (freq == LCPLL_CLK_FREQ_54O_BDW)
7344                 return 540000;
7345         else if (freq == LCPLL_CLK_FREQ_337_5_BDW)
7346                 return 337500;
7347         else
7348                 return 675000;
7349 }
7350
7351 static int haswell_get_display_clock_speed(struct drm_device *dev)
7352 {
7353         struct drm_i915_private *dev_priv = to_i915(dev);
7354         uint32_t lcpll = I915_READ(LCPLL_CTL);
7355         uint32_t freq = lcpll & LCPLL_CLK_FREQ_MASK;
7356
7357         if (lcpll & LCPLL_CD_SOURCE_FCLK)
7358                 return 800000;
7359         else if (I915_READ(FUSE_STRAP) & HSW_CDCLK_LIMIT)
7360                 return 450000;
7361         else if (freq == LCPLL_CLK_FREQ_450)
7362                 return 450000;
7363         else if (IS_HSW_ULT(dev))
7364                 return 337500;
7365         else
7366                 return 540000;
7367 }
7368
7369 static int valleyview_get_display_clock_speed(struct drm_device *dev)
7370 {
7371         return vlv_get_cck_clock_hpll(to_i915(dev), "cdclk",
7372                                       CCK_DISPLAY_CLOCK_CONTROL);
7373 }
7374
7375 static int ilk_get_display_clock_speed(struct drm_device *dev)
7376 {
7377         return 450000;
7378 }
7379
7380 static int i945_get_display_clock_speed(struct drm_device *dev)
7381 {
7382         return 400000;
7383 }
7384
7385 static int i915_get_display_clock_speed(struct drm_device *dev)
7386 {
7387         return 333333;
7388 }
7389
7390 static int i9xx_misc_get_display_clock_speed(struct drm_device *dev)
7391 {
7392         return 200000;
7393 }
7394
7395 static int pnv_get_display_clock_speed(struct drm_device *dev)
7396 {
7397         struct pci_dev *pdev = dev->pdev;
7398         u16 gcfgc = 0;
7399
7400         pci_read_config_word(pdev, GCFGC, &gcfgc);
7401
7402         switch (gcfgc & GC_DISPLAY_CLOCK_MASK) {
7403         case GC_DISPLAY_CLOCK_267_MHZ_PNV:
7404                 return 266667;
7405         case GC_DISPLAY_CLOCK_333_MHZ_PNV:
7406                 return 333333;
7407         case GC_DISPLAY_CLOCK_444_MHZ_PNV:
7408                 return 444444;
7409         case GC_DISPLAY_CLOCK_200_MHZ_PNV:
7410                 return 200000;
7411         default:
7412                 DRM_ERROR("Unknown pnv display core clock 0x%04x\n", gcfgc);
7413         case GC_DISPLAY_CLOCK_133_MHZ_PNV:
7414                 return 133333;
7415         case GC_DISPLAY_CLOCK_167_MHZ_PNV:
7416                 return 166667;
7417         }
7418 }
7419
7420 static int i915gm_get_display_clock_speed(struct drm_device *dev)
7421 {
7422         struct pci_dev *pdev = dev->pdev;
7423         u16 gcfgc = 0;
7424
7425         pci_read_config_word(pdev, GCFGC, &gcfgc);
7426
7427         if (gcfgc & GC_LOW_FREQUENCY_ENABLE)
7428                 return 133333;
7429         else {
7430                 switch (gcfgc & GC_DISPLAY_CLOCK_MASK) {
7431                 case GC_DISPLAY_CLOCK_333_MHZ:
7432                         return 333333;
7433                 default:
7434                 case GC_DISPLAY_CLOCK_190_200_MHZ:
7435                         return 190000;
7436                 }
7437         }
7438 }
7439
7440 static int i865_get_display_clock_speed(struct drm_device *dev)
7441 {
7442         return 266667;
7443 }
7444
7445 static int i85x_get_display_clock_speed(struct drm_device *dev)
7446 {
7447         struct pci_dev *pdev = dev->pdev;
7448         u16 hpllcc = 0;
7449
7450         /*
7451          * 852GM/852GMV only supports 133 MHz and the HPLLCC
7452          * encoding is different :(
7453          * FIXME is this the right way to detect 852GM/852GMV?
7454          */
7455         if (pdev->revision == 0x1)
7456                 return 133333;
7457
7458         pci_bus_read_config_word(pdev->bus,
7459                                  PCI_DEVFN(0, 3), HPLLCC, &hpllcc);
7460
7461         /* Assume that the hardware is in the high speed state.  This
7462          * should be the default.
7463          */
7464         switch (hpllcc & GC_CLOCK_CONTROL_MASK) {
7465         case GC_CLOCK_133_200:
7466         case GC_CLOCK_133_200_2:
7467         case GC_CLOCK_100_200:
7468                 return 200000;
7469         case GC_CLOCK_166_250:
7470                 return 250000;
7471         case GC_CLOCK_100_133:
7472                 return 133333;
7473         case GC_CLOCK_133_266:
7474         case GC_CLOCK_133_266_2:
7475         case GC_CLOCK_166_266:
7476                 return 266667;
7477         }
7478
7479         /* Shouldn't happen */
7480         return 0;
7481 }
7482
7483 static int i830_get_display_clock_speed(struct drm_device *dev)
7484 {
7485         return 133333;
7486 }
7487
7488 static unsigned int intel_hpll_vco(struct drm_device *dev)
7489 {
7490         struct drm_i915_private *dev_priv = to_i915(dev);
7491         static const unsigned int blb_vco[8] = {
7492                 [0] = 3200000,
7493                 [1] = 4000000,
7494                 [2] = 5333333,
7495                 [3] = 4800000,
7496                 [4] = 6400000,
7497         };
7498         static const unsigned int pnv_vco[8] = {
7499                 [0] = 3200000,
7500                 [1] = 4000000,
7501                 [2] = 5333333,
7502                 [3] = 4800000,
7503                 [4] = 2666667,
7504         };
7505         static const unsigned int cl_vco[8] = {
7506                 [0] = 3200000,
7507                 [1] = 4000000,
7508                 [2] = 5333333,
7509                 [3] = 6400000,
7510                 [4] = 3333333,
7511                 [5] = 3566667,
7512                 [6] = 4266667,
7513         };
7514         static const unsigned int elk_vco[8] = {
7515                 [0] = 3200000,
7516                 [1] = 4000000,
7517                 [2] = 5333333,
7518                 [3] = 4800000,
7519         };
7520         static const unsigned int ctg_vco[8] = {
7521                 [0] = 3200000,
7522                 [1] = 4000000,
7523                 [2] = 5333333,
7524                 [3] = 6400000,
7525                 [4] = 2666667,
7526                 [5] = 4266667,
7527         };
7528         const unsigned int *vco_table;
7529         unsigned int vco;
7530         uint8_t tmp = 0;
7531
7532         /* FIXME other chipsets? */
7533         if (IS_GM45(dev))
7534                 vco_table = ctg_vco;
7535         else if (IS_G4X(dev))
7536                 vco_table = elk_vco;
7537         else if (IS_CRESTLINE(dev))
7538                 vco_table = cl_vco;
7539         else if (IS_PINEVIEW(dev))
7540                 vco_table = pnv_vco;
7541         else if (IS_G33(dev))
7542                 vco_table = blb_vco;
7543         else
7544                 return 0;
7545
7546         tmp = I915_READ(IS_MOBILE(dev) ? HPLLVCO_MOBILE : HPLLVCO);
7547
7548         vco = vco_table[tmp & 0x7];
7549         if (vco == 0)
7550                 DRM_ERROR("Bad HPLL VCO (HPLLVCO=0x%02x)\n", tmp);
7551         else
7552                 DRM_DEBUG_KMS("HPLL VCO %u kHz\n", vco);
7553
7554         return vco;
7555 }
7556
7557 static int gm45_get_display_clock_speed(struct drm_device *dev)
7558 {
7559         struct pci_dev *pdev = dev->pdev;
7560         unsigned int cdclk_sel, vco = intel_hpll_vco(dev);
7561         uint16_t tmp = 0;
7562
7563         pci_read_config_word(pdev, GCFGC, &tmp);
7564
7565         cdclk_sel = (tmp >> 12) & 0x1;
7566
7567         switch (vco) {
7568         case 2666667:
7569         case 4000000:
7570         case 5333333:
7571                 return cdclk_sel ? 333333 : 222222;
7572         case 3200000:
7573                 return cdclk_sel ? 320000 : 228571;
7574         default:
7575                 DRM_ERROR("Unable to determine CDCLK. HPLL VCO=%u, CFGC=0x%04x\n", vco, tmp);
7576                 return 222222;
7577         }
7578 }
7579
7580 static int i965gm_get_display_clock_speed(struct drm_device *dev)
7581 {
7582         struct pci_dev *pdev = dev->pdev;
7583         static const uint8_t div_3200[] = { 16, 10,  8 };
7584         static const uint8_t div_4000[] = { 20, 12, 10 };
7585         static const uint8_t div_5333[] = { 24, 16, 14 };
7586         const uint8_t *div_table;
7587         unsigned int cdclk_sel, vco = intel_hpll_vco(dev);
7588         uint16_t tmp = 0;
7589
7590         pci_read_config_word(pdev, GCFGC, &tmp);
7591
7592         cdclk_sel = ((tmp >> 8) & 0x1f) - 1;
7593
7594         if (cdclk_sel >= ARRAY_SIZE(div_3200))
7595                 goto fail;
7596
7597         switch (vco) {
7598         case 3200000:
7599                 div_table = div_3200;
7600                 break;
7601         case 4000000:
7602                 div_table = div_4000;
7603                 break;
7604         case 5333333:
7605                 div_table = div_5333;
7606                 break;
7607         default:
7608                 goto fail;
7609         }
7610
7611         return DIV_ROUND_CLOSEST(vco, div_table[cdclk_sel]);
7612
7613 fail:
7614         DRM_ERROR("Unable to determine CDCLK. HPLL VCO=%u kHz, CFGC=0x%04x\n", vco, tmp);
7615         return 200000;
7616 }
7617
7618 static int g33_get_display_clock_speed(struct drm_device *dev)
7619 {
7620         struct pci_dev *pdev = dev->pdev;
7621         static const uint8_t div_3200[] = { 12, 10,  8,  7, 5, 16 };
7622         static const uint8_t div_4000[] = { 14, 12, 10,  8, 6, 20 };
7623         static const uint8_t div_4800[] = { 20, 14, 12, 10, 8, 24 };
7624         static const uint8_t div_5333[] = { 20, 16, 12, 12, 8, 28 };
7625         const uint8_t *div_table;
7626         unsigned int cdclk_sel, vco = intel_hpll_vco(dev);
7627         uint16_t tmp = 0;
7628
7629         pci_read_config_word(pdev, GCFGC, &tmp);
7630
7631         cdclk_sel = (tmp >> 4) & 0x7;
7632
7633         if (cdclk_sel >= ARRAY_SIZE(div_3200))
7634                 goto fail;
7635
7636         switch (vco) {
7637         case 3200000:
7638                 div_table = div_3200;
7639                 break;
7640         case 4000000:
7641                 div_table = div_4000;
7642                 break;
7643         case 4800000:
7644                 div_table = div_4800;
7645                 break;
7646         case 5333333:
7647                 div_table = div_5333;
7648                 break;
7649         default:
7650                 goto fail;
7651         }
7652
7653         return DIV_ROUND_CLOSEST(vco, div_table[cdclk_sel]);
7654
7655 fail:
7656         DRM_ERROR("Unable to determine CDCLK. HPLL VCO=%u kHz, CFGC=0x%08x\n", vco, tmp);
7657         return 190476;
7658 }
7659
7660 static void
7661 intel_reduce_m_n_ratio(uint32_t *num, uint32_t *den)
7662 {
7663         while (*num > DATA_LINK_M_N_MASK ||
7664                *den > DATA_LINK_M_N_MASK) {
7665                 *num >>= 1;
7666                 *den >>= 1;
7667         }
7668 }
7669
7670 static void compute_m_n(unsigned int m, unsigned int n,
7671                         uint32_t *ret_m, uint32_t *ret_n)
7672 {
7673         *ret_n = min_t(unsigned int, roundup_pow_of_two(n), DATA_LINK_N_MAX);
7674         *ret_m = div_u64((uint64_t) m * *ret_n, n);
7675         intel_reduce_m_n_ratio(ret_m, ret_n);
7676 }
7677
7678 void
7679 intel_link_compute_m_n(int bits_per_pixel, int nlanes,
7680                        int pixel_clock, int link_clock,
7681                        struct intel_link_m_n *m_n)
7682 {
7683         m_n->tu = 64;
7684
7685         compute_m_n(bits_per_pixel * pixel_clock,
7686                     link_clock * nlanes * 8,
7687                     &m_n->gmch_m, &m_n->gmch_n);
7688
7689         compute_m_n(pixel_clock, link_clock,
7690                     &m_n->link_m, &m_n->link_n);
7691 }
7692
7693 static inline bool intel_panel_use_ssc(struct drm_i915_private *dev_priv)
7694 {
7695         if (i915.panel_use_ssc >= 0)
7696                 return i915.panel_use_ssc != 0;
7697         return dev_priv->vbt.lvds_use_ssc
7698                 && !(dev_priv->quirks & QUIRK_LVDS_SSC_DISABLE);
7699 }
7700
7701 static uint32_t pnv_dpll_compute_fp(struct dpll *dpll)
7702 {
7703         return (1 << dpll->n) << 16 | dpll->m2;
7704 }
7705
7706 static uint32_t i9xx_dpll_compute_fp(struct dpll *dpll)
7707 {
7708         return dpll->n << 16 | dpll->m1 << 8 | dpll->m2;
7709 }
7710
7711 static void i9xx_update_pll_dividers(struct intel_crtc *crtc,
7712                                      struct intel_crtc_state *crtc_state,
7713                                      struct dpll *reduced_clock)
7714 {
7715         struct drm_device *dev = crtc->base.dev;
7716         u32 fp, fp2 = 0;
7717
7718         if (IS_PINEVIEW(dev)) {
7719                 fp = pnv_dpll_compute_fp(&crtc_state->dpll);
7720                 if (reduced_clock)
7721                         fp2 = pnv_dpll_compute_fp(reduced_clock);
7722         } else {
7723                 fp = i9xx_dpll_compute_fp(&crtc_state->dpll);
7724                 if (reduced_clock)
7725                         fp2 = i9xx_dpll_compute_fp(reduced_clock);
7726         }
7727
7728         crtc_state->dpll_hw_state.fp0 = fp;
7729
7730         crtc->lowfreq_avail = false;
7731         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS) &&
7732             reduced_clock) {
7733                 crtc_state->dpll_hw_state.fp1 = fp2;
7734                 crtc->lowfreq_avail = true;
7735         } else {
7736                 crtc_state->dpll_hw_state.fp1 = fp;
7737         }
7738 }
7739
7740 static void vlv_pllb_recal_opamp(struct drm_i915_private *dev_priv, enum pipe
7741                 pipe)
7742 {
7743         u32 reg_val;
7744
7745         /*
7746          * PLLB opamp always calibrates to max value of 0x3f, force enable it
7747          * and set it to a reasonable value instead.
7748          */
7749         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW9(1));
7750         reg_val &= 0xffffff00;
7751         reg_val |= 0x00000030;
7752         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW9(1), reg_val);
7753
7754         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_REF_DW13);
7755         reg_val &= 0x8cffffff;
7756         reg_val = 0x8c000000;
7757         vlv_dpio_write(dev_priv, pipe, VLV_REF_DW13, reg_val);
7758
7759         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW9(1));
7760         reg_val &= 0xffffff00;
7761         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW9(1), reg_val);
7762
7763         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_REF_DW13);
7764         reg_val &= 0x00ffffff;
7765         reg_val |= 0xb0000000;
7766         vlv_dpio_write(dev_priv, pipe, VLV_REF_DW13, reg_val);
7767 }
7768
7769 static void intel_pch_transcoder_set_m_n(struct intel_crtc *crtc,
7770                                          struct intel_link_m_n *m_n)
7771 {
7772         struct drm_device *dev = crtc->base.dev;
7773         struct drm_i915_private *dev_priv = to_i915(dev);
7774         int pipe = crtc->pipe;
7775
7776         I915_WRITE(PCH_TRANS_DATA_M1(pipe), TU_SIZE(m_n->tu) | m_n->gmch_m);
7777         I915_WRITE(PCH_TRANS_DATA_N1(pipe), m_n->gmch_n);
7778         I915_WRITE(PCH_TRANS_LINK_M1(pipe), m_n->link_m);
7779         I915_WRITE(PCH_TRANS_LINK_N1(pipe), m_n->link_n);
7780 }
7781
7782 static void intel_cpu_transcoder_set_m_n(struct intel_crtc *crtc,
7783                                          struct intel_link_m_n *m_n,
7784                                          struct intel_link_m_n *m2_n2)
7785 {
7786         struct drm_device *dev = crtc->base.dev;
7787         struct drm_i915_private *dev_priv = to_i915(dev);
7788         int pipe = crtc->pipe;
7789         enum transcoder transcoder = crtc->config->cpu_transcoder;
7790
7791         if (INTEL_INFO(dev)->gen >= 5) {
7792                 I915_WRITE(PIPE_DATA_M1(transcoder), TU_SIZE(m_n->tu) | m_n->gmch_m);
7793                 I915_WRITE(PIPE_DATA_N1(transcoder), m_n->gmch_n);
7794                 I915_WRITE(PIPE_LINK_M1(transcoder), m_n->link_m);
7795                 I915_WRITE(PIPE_LINK_N1(transcoder), m_n->link_n);
7796                 /* M2_N2 registers to be set only for gen < 8 (M2_N2 available
7797                  * for gen < 8) and if DRRS is supported (to make sure the
7798                  * registers are not unnecessarily accessed).
7799                  */
7800                 if (m2_n2 && (IS_CHERRYVIEW(dev) || INTEL_INFO(dev)->gen < 8) &&
7801                         crtc->config->has_drrs) {
7802                         I915_WRITE(PIPE_DATA_M2(transcoder),
7803                                         TU_SIZE(m2_n2->tu) | m2_n2->gmch_m);
7804                         I915_WRITE(PIPE_DATA_N2(transcoder), m2_n2->gmch_n);
7805                         I915_WRITE(PIPE_LINK_M2(transcoder), m2_n2->link_m);
7806                         I915_WRITE(PIPE_LINK_N2(transcoder), m2_n2->link_n);
7807                 }
7808         } else {
7809                 I915_WRITE(PIPE_DATA_M_G4X(pipe), TU_SIZE(m_n->tu) | m_n->gmch_m);
7810                 I915_WRITE(PIPE_DATA_N_G4X(pipe), m_n->gmch_n);
7811                 I915_WRITE(PIPE_LINK_M_G4X(pipe), m_n->link_m);
7812                 I915_WRITE(PIPE_LINK_N_G4X(pipe), m_n->link_n);
7813         }
7814 }
7815
7816 void intel_dp_set_m_n(struct intel_crtc *crtc, enum link_m_n_set m_n)
7817 {
7818         struct intel_link_m_n *dp_m_n, *dp_m2_n2 = NULL;
7819
7820         if (m_n == M1_N1) {
7821                 dp_m_n = &crtc->config->dp_m_n;
7822                 dp_m2_n2 = &crtc->config->dp_m2_n2;
7823         } else if (m_n == M2_N2) {
7824
7825                 /*
7826                  * M2_N2 registers are not supported. Hence m2_n2 divider value
7827                  * needs to be programmed into M1_N1.
7828                  */
7829                 dp_m_n = &crtc->config->dp_m2_n2;
7830         } else {
7831                 DRM_ERROR("Unsupported divider value\n");
7832                 return;
7833         }
7834
7835         if (crtc->config->has_pch_encoder)
7836                 intel_pch_transcoder_set_m_n(crtc, &crtc->config->dp_m_n);
7837         else
7838                 intel_cpu_transcoder_set_m_n(crtc, dp_m_n, dp_m2_n2);
7839 }
7840
7841 static void vlv_compute_dpll(struct intel_crtc *crtc,
7842                              struct intel_crtc_state *pipe_config)
7843 {
7844         pipe_config->dpll_hw_state.dpll = DPLL_INTEGRATED_REF_CLK_VLV |
7845                 DPLL_REF_CLK_ENABLE_VLV | DPLL_VGA_MODE_DIS;
7846         if (crtc->pipe != PIPE_A)
7847                 pipe_config->dpll_hw_state.dpll |= DPLL_INTEGRATED_CRI_CLK_VLV;
7848
7849         /* DPLL not used with DSI, but still need the rest set up */
7850         if (!intel_crtc_has_type(pipe_config, INTEL_OUTPUT_DSI))
7851                 pipe_config->dpll_hw_state.dpll |= DPLL_VCO_ENABLE |
7852                         DPLL_EXT_BUFFER_ENABLE_VLV;
7853
7854         pipe_config->dpll_hw_state.dpll_md =
7855                 (pipe_config->pixel_multiplier - 1) << DPLL_MD_UDI_MULTIPLIER_SHIFT;
7856 }
7857
7858 static void chv_compute_dpll(struct intel_crtc *crtc,
7859                              struct intel_crtc_state *pipe_config)
7860 {
7861         pipe_config->dpll_hw_state.dpll = DPLL_SSC_REF_CLK_CHV |
7862                 DPLL_REF_CLK_ENABLE_VLV | DPLL_VGA_MODE_DIS;
7863         if (crtc->pipe != PIPE_A)
7864                 pipe_config->dpll_hw_state.dpll |= DPLL_INTEGRATED_CRI_CLK_VLV;
7865
7866         /* DPLL not used with DSI, but still need the rest set up */
7867         if (!intel_crtc_has_type(pipe_config, INTEL_OUTPUT_DSI))
7868                 pipe_config->dpll_hw_state.dpll |= DPLL_VCO_ENABLE;
7869
7870         pipe_config->dpll_hw_state.dpll_md =
7871                 (pipe_config->pixel_multiplier - 1) << DPLL_MD_UDI_MULTIPLIER_SHIFT;
7872 }
7873
7874 static void vlv_prepare_pll(struct intel_crtc *crtc,
7875                             const struct intel_crtc_state *pipe_config)
7876 {
7877         struct drm_device *dev = crtc->base.dev;
7878         struct drm_i915_private *dev_priv = to_i915(dev);
7879         enum pipe pipe = crtc->pipe;
7880         u32 mdiv;
7881         u32 bestn, bestm1, bestm2, bestp1, bestp2;
7882         u32 coreclk, reg_val;
7883
7884         /* Enable Refclk */
7885         I915_WRITE(DPLL(pipe),
7886                    pipe_config->dpll_hw_state.dpll &
7887                    ~(DPLL_VCO_ENABLE | DPLL_EXT_BUFFER_ENABLE_VLV));
7888
7889         /* No need to actually set up the DPLL with DSI */
7890         if ((pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE) == 0)
7891                 return;
7892
7893         mutex_lock(&dev_priv->sb_lock);
7894
7895         bestn = pipe_config->dpll.n;
7896         bestm1 = pipe_config->dpll.m1;
7897         bestm2 = pipe_config->dpll.m2;
7898         bestp1 = pipe_config->dpll.p1;
7899         bestp2 = pipe_config->dpll.p2;
7900
7901         /* See eDP HDMI DPIO driver vbios notes doc */
7902
7903         /* PLL B needs special handling */
7904         if (pipe == PIPE_B)
7905                 vlv_pllb_recal_opamp(dev_priv, pipe);
7906
7907         /* Set up Tx target for periodic Rcomp update */
7908         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW9_BCAST, 0x0100000f);
7909
7910         /* Disable target IRef on PLL */
7911         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW8(pipe));
7912         reg_val &= 0x00ffffff;
7913         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW8(pipe), reg_val);
7914
7915         /* Disable fast lock */
7916         vlv_dpio_write(dev_priv, pipe, VLV_CMN_DW0, 0x610);
7917
7918         /* Set idtafcrecal before PLL is enabled */
7919         mdiv = ((bestm1 << DPIO_M1DIV_SHIFT) | (bestm2 & DPIO_M2DIV_MASK));
7920         mdiv |= ((bestp1 << DPIO_P1_SHIFT) | (bestp2 << DPIO_P2_SHIFT));
7921         mdiv |= ((bestn << DPIO_N_SHIFT));
7922         mdiv |= (1 << DPIO_K_SHIFT);
7923
7924         /*
7925          * Post divider depends on pixel clock rate, DAC vs digital (and LVDS,
7926          * but we don't support that).
7927          * Note: don't use the DAC post divider as it seems unstable.
7928          */
7929         mdiv |= (DPIO_POST_DIV_HDMIDP << DPIO_POST_DIV_SHIFT);
7930         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW3(pipe), mdiv);
7931
7932         mdiv |= DPIO_ENABLE_CALIBRATION;
7933         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW3(pipe), mdiv);
7934
7935         /* Set HBR and RBR LPF coefficients */
7936         if (pipe_config->port_clock == 162000 ||
7937             intel_crtc_has_type(crtc->config, INTEL_OUTPUT_ANALOG) ||
7938             intel_crtc_has_type(crtc->config, INTEL_OUTPUT_HDMI))
7939                 vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW10(pipe),
7940                                  0x009f0003);
7941         else
7942                 vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW10(pipe),
7943                                  0x00d0000f);
7944
7945         if (intel_crtc_has_dp_encoder(pipe_config)) {
7946                 /* Use SSC source */
7947                 if (pipe == PIPE_A)
7948                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
7949                                          0x0df40000);
7950                 else
7951                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
7952                                          0x0df70000);
7953         } else { /* HDMI or VGA */
7954                 /* Use bend source */
7955                 if (pipe == PIPE_A)
7956                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
7957                                          0x0df70000);
7958                 else
7959                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
7960                                          0x0df40000);
7961         }
7962
7963         coreclk = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW7(pipe));
7964         coreclk = (coreclk & 0x0000ff00) | 0x01c00000;
7965         if (intel_crtc_has_dp_encoder(crtc->config))
7966                 coreclk |= 0x01000000;
7967         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW7(pipe), coreclk);
7968
7969         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW11(pipe), 0x87871000);
7970         mutex_unlock(&dev_priv->sb_lock);
7971 }
7972
7973 static void chv_prepare_pll(struct intel_crtc *crtc,
7974                             const struct intel_crtc_state *pipe_config)
7975 {
7976         struct drm_device *dev = crtc->base.dev;
7977         struct drm_i915_private *dev_priv = to_i915(dev);
7978         enum pipe pipe = crtc->pipe;
7979         enum dpio_channel port = vlv_pipe_to_channel(pipe);
7980         u32 loopfilter, tribuf_calcntr;
7981         u32 bestn, bestm1, bestm2, bestp1, bestp2, bestm2_frac;
7982         u32 dpio_val;
7983         int vco;
7984
7985         /* Enable Refclk and SSC */
7986         I915_WRITE(DPLL(pipe),
7987                    pipe_config->dpll_hw_state.dpll & ~DPLL_VCO_ENABLE);
7988
7989         /* No need to actually set up the DPLL with DSI */
7990         if ((pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE) == 0)
7991                 return;
7992
7993         bestn = pipe_config->dpll.n;
7994         bestm2_frac = pipe_config->dpll.m2 & 0x3fffff;
7995         bestm1 = pipe_config->dpll.m1;
7996         bestm2 = pipe_config->dpll.m2 >> 22;
7997         bestp1 = pipe_config->dpll.p1;
7998         bestp2 = pipe_config->dpll.p2;
7999         vco = pipe_config->dpll.vco;
8000         dpio_val = 0;
8001         loopfilter = 0;
8002
8003         mutex_lock(&dev_priv->sb_lock);
8004
8005         /* p1 and p2 divider */
8006         vlv_dpio_write(dev_priv, pipe, CHV_CMN_DW13(port),
8007                         5 << DPIO_CHV_S1_DIV_SHIFT |
8008                         bestp1 << DPIO_CHV_P1_DIV_SHIFT |
8009                         bestp2 << DPIO_CHV_P2_DIV_SHIFT |
8010                         1 << DPIO_CHV_K_DIV_SHIFT);
8011
8012         /* Feedback post-divider - m2 */
8013         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW0(port), bestm2);
8014
8015         /* Feedback refclk divider - n and m1 */
8016         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW1(port),
8017                         DPIO_CHV_M1_DIV_BY_2 |
8018                         1 << DPIO_CHV_N_DIV_SHIFT);
8019
8020         /* M2 fraction division */
8021         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW2(port), bestm2_frac);
8022
8023         /* M2 fraction division enable */
8024         dpio_val = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW3(port));
8025         dpio_val &= ~(DPIO_CHV_FEEDFWD_GAIN_MASK | DPIO_CHV_FRAC_DIV_EN);
8026         dpio_val |= (2 << DPIO_CHV_FEEDFWD_GAIN_SHIFT);
8027         if (bestm2_frac)
8028                 dpio_val |= DPIO_CHV_FRAC_DIV_EN;
8029         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW3(port), dpio_val);
8030
8031         /* Program digital lock detect threshold */
8032         dpio_val = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW9(port));
8033         dpio_val &= ~(DPIO_CHV_INT_LOCK_THRESHOLD_MASK |
8034                                         DPIO_CHV_INT_LOCK_THRESHOLD_SEL_COARSE);
8035         dpio_val |= (0x5 << DPIO_CHV_INT_LOCK_THRESHOLD_SHIFT);
8036         if (!bestm2_frac)
8037                 dpio_val |= DPIO_CHV_INT_LOCK_THRESHOLD_SEL_COARSE;
8038         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW9(port), dpio_val);
8039
8040         /* Loop filter */
8041         if (vco == 5400000) {
8042                 loopfilter |= (0x3 << DPIO_CHV_PROP_COEFF_SHIFT);
8043                 loopfilter |= (0x8 << DPIO_CHV_INT_COEFF_SHIFT);
8044                 loopfilter |= (0x1 << DPIO_CHV_GAIN_CTRL_SHIFT);
8045                 tribuf_calcntr = 0x9;
8046         } else if (vco <= 6200000) {
8047                 loopfilter |= (0x5 << DPIO_CHV_PROP_COEFF_SHIFT);
8048                 loopfilter |= (0xB << DPIO_CHV_INT_COEFF_SHIFT);
8049                 loopfilter |= (0x3 << DPIO_CHV_GAIN_CTRL_SHIFT);
8050                 tribuf_calcntr = 0x9;
8051         } else if (vco <= 6480000) {
8052                 loopfilter |= (0x4 << DPIO_CHV_PROP_COEFF_SHIFT);
8053                 loopfilter |= (0x9 << DPIO_CHV_INT_COEFF_SHIFT);
8054                 loopfilter |= (0x3 << DPIO_CHV_GAIN_CTRL_SHIFT);
8055                 tribuf_calcntr = 0x8;
8056         } else {
8057                 /* Not supported. Apply the same limits as in the max case */
8058                 loopfilter |= (0x4 << DPIO_CHV_PROP_COEFF_SHIFT);
8059                 loopfilter |= (0x9 << DPIO_CHV_INT_COEFF_SHIFT);
8060                 loopfilter |= (0x3 << DPIO_CHV_GAIN_CTRL_SHIFT);
8061                 tribuf_calcntr = 0;
8062         }
8063         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW6(port), loopfilter);
8064
8065         dpio_val = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW8(port));
8066         dpio_val &= ~DPIO_CHV_TDC_TARGET_CNT_MASK;
8067         dpio_val |= (tribuf_calcntr << DPIO_CHV_TDC_TARGET_CNT_SHIFT);
8068         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW8(port), dpio_val);
8069
8070         /* AFC Recal */
8071         vlv_dpio_write(dev_priv, pipe, CHV_CMN_DW14(port),
8072                         vlv_dpio_read(dev_priv, pipe, CHV_CMN_DW14(port)) |
8073                         DPIO_AFC_RECAL);
8074
8075         mutex_unlock(&dev_priv->sb_lock);
8076 }
8077
8078 /**
8079  * vlv_force_pll_on - forcibly enable just the PLL
8080  * @dev_priv: i915 private structure
8081  * @pipe: pipe PLL to enable
8082  * @dpll: PLL configuration
8083  *
8084  * Enable the PLL for @pipe using the supplied @dpll config. To be used
8085  * in cases where we need the PLL enabled even when @pipe is not going to
8086  * be enabled.
8087  */
8088 int vlv_force_pll_on(struct drm_device *dev, enum pipe pipe,
8089                      const struct dpll *dpll)
8090 {
8091         struct intel_crtc *crtc =
8092                 to_intel_crtc(intel_get_crtc_for_pipe(dev, pipe));
8093         struct intel_crtc_state *pipe_config;
8094
8095         pipe_config = kzalloc(sizeof(*pipe_config), GFP_KERNEL);
8096         if (!pipe_config)
8097                 return -ENOMEM;
8098
8099         pipe_config->base.crtc = &crtc->base;
8100         pipe_config->pixel_multiplier = 1;
8101         pipe_config->dpll = *dpll;
8102
8103         if (IS_CHERRYVIEW(dev)) {
8104                 chv_compute_dpll(crtc, pipe_config);
8105                 chv_prepare_pll(crtc, pipe_config);
8106                 chv_enable_pll(crtc, pipe_config);
8107         } else {
8108                 vlv_compute_dpll(crtc, pipe_config);
8109                 vlv_prepare_pll(crtc, pipe_config);
8110                 vlv_enable_pll(crtc, pipe_config);
8111         }
8112
8113         kfree(pipe_config);
8114
8115         return 0;
8116 }
8117
8118 /**
8119  * vlv_force_pll_off - forcibly disable just the PLL
8120  * @dev_priv: i915 private structure
8121  * @pipe: pipe PLL to disable
8122  *
8123  * Disable the PLL for @pipe. To be used in cases where we need
8124  * the PLL enabled even when @pipe is not going to be enabled.
8125  */
8126 void vlv_force_pll_off(struct drm_device *dev, enum pipe pipe)
8127 {
8128         if (IS_CHERRYVIEW(dev))
8129                 chv_disable_pll(to_i915(dev), pipe);
8130         else
8131                 vlv_disable_pll(to_i915(dev), pipe);
8132 }
8133
8134 static void i9xx_compute_dpll(struct intel_crtc *crtc,
8135                               struct intel_crtc_state *crtc_state,
8136                               struct dpll *reduced_clock)
8137 {
8138         struct drm_device *dev = crtc->base.dev;
8139         struct drm_i915_private *dev_priv = to_i915(dev);
8140         u32 dpll;
8141         struct dpll *clock = &crtc_state->dpll;
8142
8143         i9xx_update_pll_dividers(crtc, crtc_state, reduced_clock);
8144
8145         dpll = DPLL_VGA_MODE_DIS;
8146
8147         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS))
8148                 dpll |= DPLLB_MODE_LVDS;
8149         else
8150                 dpll |= DPLLB_MODE_DAC_SERIAL;
8151
8152         if (IS_I945G(dev) || IS_I945GM(dev) || IS_G33(dev)) {
8153                 dpll |= (crtc_state->pixel_multiplier - 1)
8154                         << SDVO_MULTIPLIER_SHIFT_HIRES;
8155         }
8156
8157         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_SDVO) ||
8158             intel_crtc_has_type(crtc_state, INTEL_OUTPUT_HDMI))
8159                 dpll |= DPLL_SDVO_HIGH_SPEED;
8160
8161         if (intel_crtc_has_dp_encoder(crtc_state))
8162                 dpll |= DPLL_SDVO_HIGH_SPEED;
8163
8164         /* compute bitmask from p1 value */
8165         if (IS_PINEVIEW(dev))
8166                 dpll |= (1 << (clock->p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT_PINEVIEW;
8167         else {
8168                 dpll |= (1 << (clock->p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT;
8169                 if (IS_G4X(dev) && reduced_clock)
8170                         dpll |= (1 << (reduced_clock->p1 - 1)) << DPLL_FPA1_P1_POST_DIV_SHIFT;
8171         }
8172         switch (clock->p2) {
8173         case 5:
8174                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_5;
8175                 break;
8176         case 7:
8177                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_7;
8178                 break;
8179         case 10:
8180                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_10;
8181                 break;
8182         case 14:
8183                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_14;
8184                 break;
8185         }
8186         if (INTEL_INFO(dev)->gen >= 4)
8187                 dpll |= (6 << PLL_LOAD_PULSE_PHASE_SHIFT);
8188
8189         if (crtc_state->sdvo_tv_clock)
8190                 dpll |= PLL_REF_INPUT_TVCLKINBC;
8191         else if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS) &&
8192                  intel_panel_use_ssc(dev_priv))
8193                 dpll |= PLLB_REF_INPUT_SPREADSPECTRUMIN;
8194         else
8195                 dpll |= PLL_REF_INPUT_DREFCLK;
8196
8197         dpll |= DPLL_VCO_ENABLE;
8198         crtc_state->dpll_hw_state.dpll = dpll;
8199
8200         if (INTEL_INFO(dev)->gen >= 4) {
8201                 u32 dpll_md = (crtc_state->pixel_multiplier - 1)
8202                         << DPLL_MD_UDI_MULTIPLIER_SHIFT;
8203                 crtc_state->dpll_hw_state.dpll_md = dpll_md;
8204         }
8205 }
8206
8207 static void i8xx_compute_dpll(struct intel_crtc *crtc,
8208                               struct intel_crtc_state *crtc_state,
8209                               struct dpll *reduced_clock)
8210 {
8211         struct drm_device *dev = crtc->base.dev;
8212         struct drm_i915_private *dev_priv = to_i915(dev);
8213         u32 dpll;
8214         struct dpll *clock = &crtc_state->dpll;
8215
8216         i9xx_update_pll_dividers(crtc, crtc_state, reduced_clock);
8217
8218         dpll = DPLL_VGA_MODE_DIS;
8219
8220         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
8221                 dpll |= (1 << (clock->p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT;
8222         } else {
8223                 if (clock->p1 == 2)
8224                         dpll |= PLL_P1_DIVIDE_BY_TWO;
8225                 else
8226                         dpll |= (clock->p1 - 2) << DPLL_FPA01_P1_POST_DIV_SHIFT;
8227                 if (clock->p2 == 4)
8228                         dpll |= PLL_P2_DIVIDE_BY_4;
8229         }
8230
8231         if (!IS_I830(dev) && intel_crtc_has_type(crtc_state, INTEL_OUTPUT_DVO))
8232                 dpll |= DPLL_DVO_2X_MODE;
8233
8234         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS) &&
8235             intel_panel_use_ssc(dev_priv))
8236                 dpll |= PLLB_REF_INPUT_SPREADSPECTRUMIN;
8237         else
8238                 dpll |= PLL_REF_INPUT_DREFCLK;
8239
8240         dpll |= DPLL_VCO_ENABLE;
8241         crtc_state->dpll_hw_state.dpll = dpll;
8242 }
8243
8244 static void intel_set_pipe_timings(struct intel_crtc *intel_crtc)
8245 {
8246         struct drm_device *dev = intel_crtc->base.dev;
8247         struct drm_i915_private *dev_priv = to_i915(dev);
8248         enum pipe pipe = intel_crtc->pipe;
8249         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
8250         const struct drm_display_mode *adjusted_mode = &intel_crtc->config->base.adjusted_mode;
8251         uint32_t crtc_vtotal, crtc_vblank_end;
8252         int vsyncshift = 0;
8253
8254         /* We need to be careful not to changed the adjusted mode, for otherwise
8255          * the hw state checker will get angry at the mismatch. */
8256         crtc_vtotal = adjusted_mode->crtc_vtotal;
8257         crtc_vblank_end = adjusted_mode->crtc_vblank_end;
8258
8259         if (adjusted_mode->flags & DRM_MODE_FLAG_INTERLACE) {
8260                 /* the chip adds 2 halflines automatically */
8261                 crtc_vtotal -= 1;
8262                 crtc_vblank_end -= 1;
8263
8264                 if (intel_crtc_has_type(intel_crtc->config, INTEL_OUTPUT_SDVO))
8265                         vsyncshift = (adjusted_mode->crtc_htotal - 1) / 2;
8266                 else
8267                         vsyncshift = adjusted_mode->crtc_hsync_start -
8268                                 adjusted_mode->crtc_htotal / 2;
8269                 if (vsyncshift < 0)
8270                         vsyncshift += adjusted_mode->crtc_htotal;
8271         }
8272
8273         if (INTEL_INFO(dev)->gen > 3)
8274                 I915_WRITE(VSYNCSHIFT(cpu_transcoder), vsyncshift);
8275
8276         I915_WRITE(HTOTAL(cpu_transcoder),
8277                    (adjusted_mode->crtc_hdisplay - 1) |
8278                    ((adjusted_mode->crtc_htotal - 1) << 16));
8279         I915_WRITE(HBLANK(cpu_transcoder),
8280                    (adjusted_mode->crtc_hblank_start - 1) |
8281                    ((adjusted_mode->crtc_hblank_end - 1) << 16));
8282         I915_WRITE(HSYNC(cpu_transcoder),
8283                    (adjusted_mode->crtc_hsync_start - 1) |
8284                    ((adjusted_mode->crtc_hsync_end - 1) << 16));
8285
8286         I915_WRITE(VTOTAL(cpu_transcoder),
8287                    (adjusted_mode->crtc_vdisplay - 1) |
8288                    ((crtc_vtotal - 1) << 16));
8289         I915_WRITE(VBLANK(cpu_transcoder),
8290                    (adjusted_mode->crtc_vblank_start - 1) |
8291                    ((crtc_vblank_end - 1) << 16));
8292         I915_WRITE(VSYNC(cpu_transcoder),
8293                    (adjusted_mode->crtc_vsync_start - 1) |
8294                    ((adjusted_mode->crtc_vsync_end - 1) << 16));
8295
8296         /* Workaround: when the EDP input selection is B, the VTOTAL_B must be
8297          * programmed with the VTOTAL_EDP value. Same for VTOTAL_C. This is
8298          * documented on the DDI_FUNC_CTL register description, EDP Input Select
8299          * bits. */
8300         if (IS_HASWELL(dev) && cpu_transcoder == TRANSCODER_EDP &&
8301             (pipe == PIPE_B || pipe == PIPE_C))
8302                 I915_WRITE(VTOTAL(pipe), I915_READ(VTOTAL(cpu_transcoder)));
8303
8304 }
8305
8306 static void intel_set_pipe_src_size(struct intel_crtc *intel_crtc)
8307 {
8308         struct drm_device *dev = intel_crtc->base.dev;
8309         struct drm_i915_private *dev_priv = to_i915(dev);
8310         enum pipe pipe = intel_crtc->pipe;
8311
8312         /* pipesrc controls the size that is scaled from, which should
8313          * always be the user's requested size.
8314          */
8315         I915_WRITE(PIPESRC(pipe),
8316                    ((intel_crtc->config->pipe_src_w - 1) << 16) |
8317                    (intel_crtc->config->pipe_src_h - 1));
8318 }
8319
8320 static void intel_get_pipe_timings(struct intel_crtc *crtc,
8321                                    struct intel_crtc_state *pipe_config)
8322 {
8323         struct drm_device *dev = crtc->base.dev;
8324         struct drm_i915_private *dev_priv = to_i915(dev);
8325         enum transcoder cpu_transcoder = pipe_config->cpu_transcoder;
8326         uint32_t tmp;
8327
8328         tmp = I915_READ(HTOTAL(cpu_transcoder));
8329         pipe_config->base.adjusted_mode.crtc_hdisplay = (tmp & 0xffff) + 1;
8330         pipe_config->base.adjusted_mode.crtc_htotal = ((tmp >> 16) & 0xffff) + 1;
8331         tmp = I915_READ(HBLANK(cpu_transcoder));
8332         pipe_config->base.adjusted_mode.crtc_hblank_start = (tmp & 0xffff) + 1;
8333         pipe_config->base.adjusted_mode.crtc_hblank_end = ((tmp >> 16) & 0xffff) + 1;
8334         tmp = I915_READ(HSYNC(cpu_transcoder));
8335         pipe_config->base.adjusted_mode.crtc_hsync_start = (tmp & 0xffff) + 1;
8336         pipe_config->base.adjusted_mode.crtc_hsync_end = ((tmp >> 16) & 0xffff) + 1;
8337
8338         tmp = I915_READ(VTOTAL(cpu_transcoder));
8339         pipe_config->base.adjusted_mode.crtc_vdisplay = (tmp & 0xffff) + 1;
8340         pipe_config->base.adjusted_mode.crtc_vtotal = ((tmp >> 16) & 0xffff) + 1;
8341         tmp = I915_READ(VBLANK(cpu_transcoder));
8342         pipe_config->base.adjusted_mode.crtc_vblank_start = (tmp & 0xffff) + 1;
8343         pipe_config->base.adjusted_mode.crtc_vblank_end = ((tmp >> 16) & 0xffff) + 1;
8344         tmp = I915_READ(VSYNC(cpu_transcoder));
8345         pipe_config->base.adjusted_mode.crtc_vsync_start = (tmp & 0xffff) + 1;
8346         pipe_config->base.adjusted_mode.crtc_vsync_end = ((tmp >> 16) & 0xffff) + 1;
8347
8348         if (I915_READ(PIPECONF(cpu_transcoder)) & PIPECONF_INTERLACE_MASK) {
8349                 pipe_config->base.adjusted_mode.flags |= DRM_MODE_FLAG_INTERLACE;
8350                 pipe_config->base.adjusted_mode.crtc_vtotal += 1;
8351                 pipe_config->base.adjusted_mode.crtc_vblank_end += 1;
8352         }
8353 }
8354
8355 static void intel_get_pipe_src_size(struct intel_crtc *crtc,
8356                                     struct intel_crtc_state *pipe_config)
8357 {
8358         struct drm_device *dev = crtc->base.dev;
8359         struct drm_i915_private *dev_priv = to_i915(dev);
8360         u32 tmp;
8361
8362         tmp = I915_READ(PIPESRC(crtc->pipe));
8363         pipe_config->pipe_src_h = (tmp & 0xffff) + 1;
8364         pipe_config->pipe_src_w = ((tmp >> 16) & 0xffff) + 1;
8365
8366         pipe_config->base.mode.vdisplay = pipe_config->pipe_src_h;
8367         pipe_config->base.mode.hdisplay = pipe_config->pipe_src_w;
8368 }
8369
8370 void intel_mode_from_pipe_config(struct drm_display_mode *mode,
8371                                  struct intel_crtc_state *pipe_config)
8372 {
8373         mode->hdisplay = pipe_config->base.adjusted_mode.crtc_hdisplay;
8374         mode->htotal = pipe_config->base.adjusted_mode.crtc_htotal;
8375         mode->hsync_start = pipe_config->base.adjusted_mode.crtc_hsync_start;
8376         mode->hsync_end = pipe_config->base.adjusted_mode.crtc_hsync_end;
8377
8378         mode->vdisplay = pipe_config->base.adjusted_mode.crtc_vdisplay;
8379         mode->vtotal = pipe_config->base.adjusted_mode.crtc_vtotal;
8380         mode->vsync_start = pipe_config->base.adjusted_mode.crtc_vsync_start;
8381         mode->vsync_end = pipe_config->base.adjusted_mode.crtc_vsync_end;
8382
8383         mode->flags = pipe_config->base.adjusted_mode.flags;
8384         mode->type = DRM_MODE_TYPE_DRIVER;
8385
8386         mode->clock = pipe_config->base.adjusted_mode.crtc_clock;
8387         mode->flags |= pipe_config->base.adjusted_mode.flags;
8388
8389         mode->hsync = drm_mode_hsync(mode);
8390         mode->vrefresh = drm_mode_vrefresh(mode);
8391         drm_mode_set_name(mode);
8392 }
8393
8394 static void i9xx_set_pipeconf(struct intel_crtc *intel_crtc)
8395 {
8396         struct drm_device *dev = intel_crtc->base.dev;
8397         struct drm_i915_private *dev_priv = to_i915(dev);
8398         uint32_t pipeconf;
8399
8400         pipeconf = 0;
8401
8402         if ((intel_crtc->pipe == PIPE_A && dev_priv->quirks & QUIRK_PIPEA_FORCE) ||
8403             (intel_crtc->pipe == PIPE_B && dev_priv->quirks & QUIRK_PIPEB_FORCE))
8404                 pipeconf |= I915_READ(PIPECONF(intel_crtc->pipe)) & PIPECONF_ENABLE;
8405
8406         if (intel_crtc->config->double_wide)
8407                 pipeconf |= PIPECONF_DOUBLE_WIDE;
8408
8409         /* only g4x and later have fancy bpc/dither controls */
8410         if (IS_G4X(dev) || IS_VALLEYVIEW(dev) || IS_CHERRYVIEW(dev)) {
8411                 /* Bspec claims that we can't use dithering for 30bpp pipes. */
8412                 if (intel_crtc->config->dither && intel_crtc->config->pipe_bpp != 30)
8413                         pipeconf |= PIPECONF_DITHER_EN |
8414                                     PIPECONF_DITHER_TYPE_SP;
8415
8416                 switch (intel_crtc->config->pipe_bpp) {
8417                 case 18:
8418                         pipeconf |= PIPECONF_6BPC;
8419                         break;
8420                 case 24:
8421                         pipeconf |= PIPECONF_8BPC;
8422                         break;
8423                 case 30:
8424                         pipeconf |= PIPECONF_10BPC;
8425                         break;
8426                 default:
8427                         /* Case prevented by intel_choose_pipe_bpp_dither. */
8428                         BUG();
8429                 }
8430         }
8431
8432         if (HAS_PIPE_CXSR(dev)) {
8433                 if (intel_crtc->lowfreq_avail) {
8434                         DRM_DEBUG_KMS("enabling CxSR downclocking\n");
8435                         pipeconf |= PIPECONF_CXSR_DOWNCLOCK;
8436                 } else {
8437                         DRM_DEBUG_KMS("disabling CxSR downclocking\n");
8438                 }
8439         }
8440
8441         if (intel_crtc->config->base.adjusted_mode.flags & DRM_MODE_FLAG_INTERLACE) {
8442                 if (INTEL_INFO(dev)->gen < 4 ||
8443                     intel_crtc_has_type(intel_crtc->config, INTEL_OUTPUT_SDVO))
8444                         pipeconf |= PIPECONF_INTERLACE_W_FIELD_INDICATION;
8445                 else
8446                         pipeconf |= PIPECONF_INTERLACE_W_SYNC_SHIFT;
8447         } else
8448                 pipeconf |= PIPECONF_PROGRESSIVE;
8449
8450         if ((IS_VALLEYVIEW(dev) || IS_CHERRYVIEW(dev)) &&
8451              intel_crtc->config->limited_color_range)
8452                 pipeconf |= PIPECONF_COLOR_RANGE_SELECT;
8453
8454         I915_WRITE(PIPECONF(intel_crtc->pipe), pipeconf);
8455         POSTING_READ(PIPECONF(intel_crtc->pipe));
8456 }
8457
8458 static int i8xx_crtc_compute_clock(struct intel_crtc *crtc,
8459                                    struct intel_crtc_state *crtc_state)
8460 {
8461         struct drm_device *dev = crtc->base.dev;
8462         struct drm_i915_private *dev_priv = to_i915(dev);
8463         const struct intel_limit *limit;
8464         int refclk = 48000;
8465
8466         memset(&crtc_state->dpll_hw_state, 0,
8467                sizeof(crtc_state->dpll_hw_state));
8468
8469         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
8470                 if (intel_panel_use_ssc(dev_priv)) {
8471                         refclk = dev_priv->vbt.lvds_ssc_freq;
8472                         DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n", refclk);
8473                 }
8474
8475                 limit = &intel_limits_i8xx_lvds;
8476         } else if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_DVO)) {
8477                 limit = &intel_limits_i8xx_dvo;
8478         } else {
8479                 limit = &intel_limits_i8xx_dac;
8480         }
8481
8482         if (!crtc_state->clock_set &&
8483             !i9xx_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
8484                                  refclk, NULL, &crtc_state->dpll)) {
8485                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
8486                 return -EINVAL;
8487         }
8488
8489         i8xx_compute_dpll(crtc, crtc_state, NULL);
8490
8491         return 0;
8492 }
8493
8494 static int g4x_crtc_compute_clock(struct intel_crtc *crtc,
8495                                   struct intel_crtc_state *crtc_state)
8496 {
8497         struct drm_device *dev = crtc->base.dev;
8498         struct drm_i915_private *dev_priv = to_i915(dev);
8499         const struct intel_limit *limit;
8500         int refclk = 96000;
8501
8502         memset(&crtc_state->dpll_hw_state, 0,
8503                sizeof(crtc_state->dpll_hw_state));
8504
8505         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
8506                 if (intel_panel_use_ssc(dev_priv)) {
8507                         refclk = dev_priv->vbt.lvds_ssc_freq;
8508                         DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n", refclk);
8509                 }
8510
8511                 if (intel_is_dual_link_lvds(dev))
8512                         limit = &intel_limits_g4x_dual_channel_lvds;
8513                 else
8514                         limit = &intel_limits_g4x_single_channel_lvds;
8515         } else if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_HDMI) ||
8516                    intel_crtc_has_type(crtc_state, INTEL_OUTPUT_ANALOG)) {
8517                 limit = &intel_limits_g4x_hdmi;
8518         } else if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_SDVO)) {
8519                 limit = &intel_limits_g4x_sdvo;
8520         } else {
8521                 /* The option is for other outputs */
8522                 limit = &intel_limits_i9xx_sdvo;
8523         }
8524
8525         if (!crtc_state->clock_set &&
8526             !g4x_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
8527                                 refclk, NULL, &crtc_state->dpll)) {
8528                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
8529                 return -EINVAL;
8530         }
8531
8532         i9xx_compute_dpll(crtc, crtc_state, NULL);
8533
8534         return 0;
8535 }
8536
8537 static int pnv_crtc_compute_clock(struct intel_crtc *crtc,
8538                                   struct intel_crtc_state *crtc_state)
8539 {
8540         struct drm_device *dev = crtc->base.dev;
8541         struct drm_i915_private *dev_priv = to_i915(dev);
8542         const struct intel_limit *limit;
8543         int refclk = 96000;
8544
8545         memset(&crtc_state->dpll_hw_state, 0,
8546                sizeof(crtc_state->dpll_hw_state));
8547
8548         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
8549                 if (intel_panel_use_ssc(dev_priv)) {
8550                         refclk = dev_priv->vbt.lvds_ssc_freq;
8551                         DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n", refclk);
8552                 }
8553
8554                 limit = &intel_limits_pineview_lvds;
8555         } else {
8556                 limit = &intel_limits_pineview_sdvo;
8557         }
8558
8559         if (!crtc_state->clock_set &&
8560             !pnv_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
8561                                 refclk, NULL, &crtc_state->dpll)) {
8562                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
8563                 return -EINVAL;
8564         }
8565
8566         i9xx_compute_dpll(crtc, crtc_state, NULL);
8567
8568         return 0;
8569 }
8570
8571 static int i9xx_crtc_compute_clock(struct intel_crtc *crtc,
8572                                    struct intel_crtc_state *crtc_state)
8573 {
8574         struct drm_device *dev = crtc->base.dev;
8575         struct drm_i915_private *dev_priv = to_i915(dev);
8576         const struct intel_limit *limit;
8577         int refclk = 96000;
8578
8579         memset(&crtc_state->dpll_hw_state, 0,
8580                sizeof(crtc_state->dpll_hw_state));
8581
8582         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
8583                 if (intel_panel_use_ssc(dev_priv)) {
8584                         refclk = dev_priv->vbt.lvds_ssc_freq;
8585                         DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n", refclk);
8586                 }
8587
8588                 limit = &intel_limits_i9xx_lvds;
8589         } else {
8590                 limit = &intel_limits_i9xx_sdvo;
8591         }
8592
8593         if (!crtc_state->clock_set &&
8594             !i9xx_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
8595                                  refclk, NULL, &crtc_state->dpll)) {
8596                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
8597                 return -EINVAL;
8598         }
8599
8600         i9xx_compute_dpll(crtc, crtc_state, NULL);
8601
8602         return 0;
8603 }
8604
8605 static int chv_crtc_compute_clock(struct intel_crtc *crtc,
8606                                   struct intel_crtc_state *crtc_state)
8607 {
8608         int refclk = 100000;
8609         const struct intel_limit *limit = &intel_limits_chv;
8610
8611         memset(&crtc_state->dpll_hw_state, 0,
8612                sizeof(crtc_state->dpll_hw_state));
8613
8614         if (!crtc_state->clock_set &&
8615             !chv_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
8616                                 refclk, NULL, &crtc_state->dpll)) {
8617                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
8618                 return -EINVAL;
8619         }
8620
8621         chv_compute_dpll(crtc, crtc_state);
8622
8623         return 0;
8624 }
8625
8626 static int vlv_crtc_compute_clock(struct intel_crtc *crtc,
8627                                   struct intel_crtc_state *crtc_state)
8628 {
8629         int refclk = 100000;
8630         const struct intel_limit *limit = &intel_limits_vlv;
8631
8632         memset(&crtc_state->dpll_hw_state, 0,
8633                sizeof(crtc_state->dpll_hw_state));
8634
8635         if (!crtc_state->clock_set &&
8636             !vlv_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
8637                                 refclk, NULL, &crtc_state->dpll)) {
8638                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
8639                 return -EINVAL;
8640         }
8641
8642         vlv_compute_dpll(crtc, crtc_state);
8643
8644         return 0;
8645 }
8646
8647 static void i9xx_get_pfit_config(struct intel_crtc *crtc,
8648                                  struct intel_crtc_state *pipe_config)
8649 {
8650         struct drm_device *dev = crtc->base.dev;
8651         struct drm_i915_private *dev_priv = to_i915(dev);
8652         uint32_t tmp;
8653
8654         if (INTEL_INFO(dev)->gen <= 3 && (IS_I830(dev) || !IS_MOBILE(dev)))
8655                 return;
8656
8657         tmp = I915_READ(PFIT_CONTROL);
8658         if (!(tmp & PFIT_ENABLE))
8659                 return;
8660
8661         /* Check whether the pfit is attached to our pipe. */
8662         if (INTEL_INFO(dev)->gen < 4) {
8663                 if (crtc->pipe != PIPE_B)
8664                         return;
8665         } else {
8666                 if ((tmp & PFIT_PIPE_MASK) != (crtc->pipe << PFIT_PIPE_SHIFT))
8667                         return;
8668         }
8669
8670         pipe_config->gmch_pfit.control = tmp;
8671         pipe_config->gmch_pfit.pgm_ratios = I915_READ(PFIT_PGM_RATIOS);
8672 }
8673
8674 static void vlv_crtc_clock_get(struct intel_crtc *crtc,
8675                                struct intel_crtc_state *pipe_config)
8676 {
8677         struct drm_device *dev = crtc->base.dev;
8678         struct drm_i915_private *dev_priv = to_i915(dev);
8679         int pipe = pipe_config->cpu_transcoder;
8680         struct dpll clock;
8681         u32 mdiv;
8682         int refclk = 100000;
8683
8684         /* In case of DSI, DPLL will not be used */
8685         if ((pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE) == 0)
8686                 return;
8687
8688         mutex_lock(&dev_priv->sb_lock);
8689         mdiv = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW3(pipe));
8690         mutex_unlock(&dev_priv->sb_lock);
8691
8692         clock.m1 = (mdiv >> DPIO_M1DIV_SHIFT) & 7;
8693         clock.m2 = mdiv & DPIO_M2DIV_MASK;
8694         clock.n = (mdiv >> DPIO_N_SHIFT) & 0xf;
8695         clock.p1 = (mdiv >> DPIO_P1_SHIFT) & 7;
8696         clock.p2 = (mdiv >> DPIO_P2_SHIFT) & 0x1f;
8697
8698         pipe_config->port_clock = vlv_calc_dpll_params(refclk, &clock);
8699 }
8700
8701 static void
8702 i9xx_get_initial_plane_config(struct intel_crtc *crtc,
8703                               struct intel_initial_plane_config *plane_config)
8704 {
8705         struct drm_device *dev = crtc->base.dev;
8706         struct drm_i915_private *dev_priv = to_i915(dev);
8707         u32 val, base, offset;
8708         int pipe = crtc->pipe, plane = crtc->plane;
8709         int fourcc, pixel_format;
8710         unsigned int aligned_height;
8711         struct drm_framebuffer *fb;
8712         struct intel_framebuffer *intel_fb;
8713
8714         val = I915_READ(DSPCNTR(plane));
8715         if (!(val & DISPLAY_PLANE_ENABLE))
8716                 return;
8717
8718         intel_fb = kzalloc(sizeof(*intel_fb), GFP_KERNEL);
8719         if (!intel_fb) {
8720                 DRM_DEBUG_KMS("failed to alloc fb\n");
8721                 return;
8722         }
8723
8724         fb = &intel_fb->base;
8725
8726         if (INTEL_INFO(dev)->gen >= 4) {
8727                 if (val & DISPPLANE_TILED) {
8728                         plane_config->tiling = I915_TILING_X;
8729                         fb->modifier[0] = I915_FORMAT_MOD_X_TILED;
8730                 }
8731         }
8732
8733         pixel_format = val & DISPPLANE_PIXFORMAT_MASK;
8734         fourcc = i9xx_format_to_fourcc(pixel_format);
8735         fb->pixel_format = fourcc;
8736         fb->bits_per_pixel = drm_format_plane_cpp(fourcc, 0) * 8;
8737
8738         if (INTEL_INFO(dev)->gen >= 4) {
8739                 if (plane_config->tiling)
8740                         offset = I915_READ(DSPTILEOFF(plane));
8741                 else
8742                         offset = I915_READ(DSPLINOFF(plane));
8743                 base = I915_READ(DSPSURF(plane)) & 0xfffff000;
8744         } else {
8745                 base = I915_READ(DSPADDR(plane));
8746         }
8747         plane_config->base = base;
8748
8749         val = I915_READ(PIPESRC(pipe));
8750         fb->width = ((val >> 16) & 0xfff) + 1;
8751         fb->height = ((val >> 0) & 0xfff) + 1;
8752
8753         val = I915_READ(DSPSTRIDE(pipe));
8754         fb->pitches[0] = val & 0xffffffc0;
8755
8756         aligned_height = intel_fb_align_height(dev, fb->height,
8757                                                fb->pixel_format,
8758                                                fb->modifier[0]);
8759
8760         plane_config->size = fb->pitches[0] * aligned_height;
8761
8762         DRM_DEBUG_KMS("pipe/plane %c/%d with fb: size=%dx%d@%d, offset=%x, pitch %d, size 0x%x\n",
8763                       pipe_name(pipe), plane, fb->width, fb->height,
8764                       fb->bits_per_pixel, base, fb->pitches[0],
8765                       plane_config->size);
8766
8767         plane_config->fb = intel_fb;
8768 }
8769
8770 static void chv_crtc_clock_get(struct intel_crtc *crtc,
8771                                struct intel_crtc_state *pipe_config)
8772 {
8773         struct drm_device *dev = crtc->base.dev;
8774         struct drm_i915_private *dev_priv = to_i915(dev);
8775         int pipe = pipe_config->cpu_transcoder;
8776         enum dpio_channel port = vlv_pipe_to_channel(pipe);
8777         struct dpll clock;
8778         u32 cmn_dw13, pll_dw0, pll_dw1, pll_dw2, pll_dw3;
8779         int refclk = 100000;
8780
8781         /* In case of DSI, DPLL will not be used */
8782         if ((pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE) == 0)
8783                 return;
8784
8785         mutex_lock(&dev_priv->sb_lock);
8786         cmn_dw13 = vlv_dpio_read(dev_priv, pipe, CHV_CMN_DW13(port));
8787         pll_dw0 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW0(port));
8788         pll_dw1 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW1(port));
8789         pll_dw2 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW2(port));
8790         pll_dw3 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW3(port));
8791         mutex_unlock(&dev_priv->sb_lock);
8792
8793         clock.m1 = (pll_dw1 & 0x7) == DPIO_CHV_M1_DIV_BY_2 ? 2 : 0;
8794         clock.m2 = (pll_dw0 & 0xff) << 22;
8795         if (pll_dw3 & DPIO_CHV_FRAC_DIV_EN)
8796                 clock.m2 |= pll_dw2 & 0x3fffff;
8797         clock.n = (pll_dw1 >> DPIO_CHV_N_DIV_SHIFT) & 0xf;
8798         clock.p1 = (cmn_dw13 >> DPIO_CHV_P1_DIV_SHIFT) & 0x7;
8799         clock.p2 = (cmn_dw13 >> DPIO_CHV_P2_DIV_SHIFT) & 0x1f;
8800
8801         pipe_config->port_clock = chv_calc_dpll_params(refclk, &clock);
8802 }
8803
8804 static bool i9xx_get_pipe_config(struct intel_crtc *crtc,
8805                                  struct intel_crtc_state *pipe_config)
8806 {
8807         struct drm_device *dev = crtc->base.dev;
8808         struct drm_i915_private *dev_priv = to_i915(dev);
8809         enum intel_display_power_domain power_domain;
8810         uint32_t tmp;
8811         bool ret;
8812
8813         power_domain = POWER_DOMAIN_PIPE(crtc->pipe);
8814         if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
8815                 return false;
8816
8817         pipe_config->cpu_transcoder = (enum transcoder) crtc->pipe;
8818         pipe_config->shared_dpll = NULL;
8819
8820         ret = false;
8821
8822         tmp = I915_READ(PIPECONF(crtc->pipe));
8823         if (!(tmp & PIPECONF_ENABLE))
8824                 goto out;
8825
8826         if (IS_G4X(dev) || IS_VALLEYVIEW(dev) || IS_CHERRYVIEW(dev)) {
8827                 switch (tmp & PIPECONF_BPC_MASK) {
8828                 case PIPECONF_6BPC:
8829                         pipe_config->pipe_bpp = 18;
8830                         break;
8831                 case PIPECONF_8BPC:
8832                         pipe_config->pipe_bpp = 24;
8833                         break;
8834                 case PIPECONF_10BPC:
8835                         pipe_config->pipe_bpp = 30;
8836                         break;
8837                 default:
8838                         break;
8839                 }
8840         }
8841
8842         if ((IS_VALLEYVIEW(dev) || IS_CHERRYVIEW(dev)) &&
8843             (tmp & PIPECONF_COLOR_RANGE_SELECT))
8844                 pipe_config->limited_color_range = true;
8845
8846         if (INTEL_INFO(dev)->gen < 4)
8847                 pipe_config->double_wide = tmp & PIPECONF_DOUBLE_WIDE;
8848
8849         intel_get_pipe_timings(crtc, pipe_config);
8850         intel_get_pipe_src_size(crtc, pipe_config);
8851
8852         i9xx_get_pfit_config(crtc, pipe_config);
8853
8854         if (INTEL_INFO(dev)->gen >= 4) {
8855                 /* No way to read it out on pipes B and C */
8856                 if (IS_CHERRYVIEW(dev) && crtc->pipe != PIPE_A)
8857                         tmp = dev_priv->chv_dpll_md[crtc->pipe];
8858                 else
8859                         tmp = I915_READ(DPLL_MD(crtc->pipe));
8860                 pipe_config->pixel_multiplier =
8861                         ((tmp & DPLL_MD_UDI_MULTIPLIER_MASK)
8862                          >> DPLL_MD_UDI_MULTIPLIER_SHIFT) + 1;
8863                 pipe_config->dpll_hw_state.dpll_md = tmp;
8864         } else if (IS_I945G(dev) || IS_I945GM(dev) || IS_G33(dev)) {
8865                 tmp = I915_READ(DPLL(crtc->pipe));
8866                 pipe_config->pixel_multiplier =
8867                         ((tmp & SDVO_MULTIPLIER_MASK)
8868                          >> SDVO_MULTIPLIER_SHIFT_HIRES) + 1;
8869         } else {
8870                 /* Note that on i915G/GM the pixel multiplier is in the sdvo
8871                  * port and will be fixed up in the encoder->get_config
8872                  * function. */
8873                 pipe_config->pixel_multiplier = 1;
8874         }
8875         pipe_config->dpll_hw_state.dpll = I915_READ(DPLL(crtc->pipe));
8876         if (!IS_VALLEYVIEW(dev) && !IS_CHERRYVIEW(dev)) {
8877                 /*
8878                  * DPLL_DVO_2X_MODE must be enabled for both DPLLs
8879                  * on 830. Filter it out here so that we don't
8880                  * report errors due to that.
8881                  */
8882                 if (IS_I830(dev))
8883                         pipe_config->dpll_hw_state.dpll &= ~DPLL_DVO_2X_MODE;
8884
8885                 pipe_config->dpll_hw_state.fp0 = I915_READ(FP0(crtc->pipe));
8886                 pipe_config->dpll_hw_state.fp1 = I915_READ(FP1(crtc->pipe));
8887         } else {
8888                 /* Mask out read-only status bits. */
8889                 pipe_config->dpll_hw_state.dpll &= ~(DPLL_LOCK_VLV |
8890                                                      DPLL_PORTC_READY_MASK |
8891                                                      DPLL_PORTB_READY_MASK);
8892         }
8893
8894         if (IS_CHERRYVIEW(dev))
8895                 chv_crtc_clock_get(crtc, pipe_config);
8896         else if (IS_VALLEYVIEW(dev))
8897                 vlv_crtc_clock_get(crtc, pipe_config);
8898         else
8899                 i9xx_crtc_clock_get(crtc, pipe_config);
8900
8901         /*
8902          * Normally the dotclock is filled in by the encoder .get_config()
8903          * but in case the pipe is enabled w/o any ports we need a sane
8904          * default.
8905          */
8906         pipe_config->base.adjusted_mode.crtc_clock =
8907                 pipe_config->port_clock / pipe_config->pixel_multiplier;
8908
8909         ret = true;
8910
8911 out:
8912         intel_display_power_put(dev_priv, power_domain);
8913
8914         return ret;
8915 }
8916
8917 static void ironlake_init_pch_refclk(struct drm_device *dev)
8918 {
8919         struct drm_i915_private *dev_priv = to_i915(dev);
8920         struct intel_encoder *encoder;
8921         int i;
8922         u32 val, final;
8923         bool has_lvds = false;
8924         bool has_cpu_edp = false;
8925         bool has_panel = false;
8926         bool has_ck505 = false;
8927         bool can_ssc = false;
8928         bool using_ssc_source = false;
8929
8930         /* We need to take the global config into account */
8931         for_each_intel_encoder(dev, encoder) {
8932                 switch (encoder->type) {
8933                 case INTEL_OUTPUT_LVDS:
8934                         has_panel = true;
8935                         has_lvds = true;
8936                         break;
8937                 case INTEL_OUTPUT_EDP:
8938                         has_panel = true;
8939                         if (enc_to_dig_port(&encoder->base)->port == PORT_A)
8940                                 has_cpu_edp = true;
8941                         break;
8942                 default:
8943                         break;
8944                 }
8945         }
8946
8947         if (HAS_PCH_IBX(dev)) {
8948                 has_ck505 = dev_priv->vbt.display_clock_mode;
8949                 can_ssc = has_ck505;
8950         } else {
8951                 has_ck505 = false;
8952                 can_ssc = true;
8953         }
8954
8955         /* Check if any DPLLs are using the SSC source */
8956         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
8957                 u32 temp = I915_READ(PCH_DPLL(i));
8958
8959                 if (!(temp & DPLL_VCO_ENABLE))
8960                         continue;
8961
8962                 if ((temp & PLL_REF_INPUT_MASK) ==
8963                     PLLB_REF_INPUT_SPREADSPECTRUMIN) {
8964                         using_ssc_source = true;
8965                         break;
8966                 }
8967         }
8968
8969         DRM_DEBUG_KMS("has_panel %d has_lvds %d has_ck505 %d using_ssc_source %d\n",
8970                       has_panel, has_lvds, has_ck505, using_ssc_source);
8971
8972         /* Ironlake: try to setup display ref clock before DPLL
8973          * enabling. This is only under driver's control after
8974          * PCH B stepping, previous chipset stepping should be
8975          * ignoring this setting.
8976          */
8977         val = I915_READ(PCH_DREF_CONTROL);
8978
8979         /* As we must carefully and slowly disable/enable each source in turn,
8980          * compute the final state we want first and check if we need to
8981          * make any changes at all.
8982          */
8983         final = val;
8984         final &= ~DREF_NONSPREAD_SOURCE_MASK;
8985         if (has_ck505)
8986                 final |= DREF_NONSPREAD_CK505_ENABLE;
8987         else
8988                 final |= DREF_NONSPREAD_SOURCE_ENABLE;
8989
8990         final &= ~DREF_SSC_SOURCE_MASK;
8991         final &= ~DREF_CPU_SOURCE_OUTPUT_MASK;
8992         final &= ~DREF_SSC1_ENABLE;
8993
8994         if (has_panel) {
8995                 final |= DREF_SSC_SOURCE_ENABLE;
8996
8997                 if (intel_panel_use_ssc(dev_priv) && can_ssc)
8998                         final |= DREF_SSC1_ENABLE;
8999
9000                 if (has_cpu_edp) {
9001                         if (intel_panel_use_ssc(dev_priv) && can_ssc)
9002                                 final |= DREF_CPU_SOURCE_OUTPUT_DOWNSPREAD;
9003                         else
9004                                 final |= DREF_CPU_SOURCE_OUTPUT_NONSPREAD;
9005                 } else
9006                         final |= DREF_CPU_SOURCE_OUTPUT_DISABLE;
9007         } else if (using_ssc_source) {
9008                 final |= DREF_SSC_SOURCE_ENABLE;
9009                 final |= DREF_SSC1_ENABLE;
9010         }
9011
9012         if (final == val)
9013                 return;
9014
9015         /* Always enable nonspread source */
9016         val &= ~DREF_NONSPREAD_SOURCE_MASK;
9017
9018         if (has_ck505)
9019                 val |= DREF_NONSPREAD_CK505_ENABLE;
9020         else
9021                 val |= DREF_NONSPREAD_SOURCE_ENABLE;
9022
9023         if (has_panel) {
9024                 val &= ~DREF_SSC_SOURCE_MASK;
9025                 val |= DREF_SSC_SOURCE_ENABLE;
9026
9027                 /* SSC must be turned on before enabling the CPU output  */
9028                 if (intel_panel_use_ssc(dev_priv) && can_ssc) {
9029                         DRM_DEBUG_KMS("Using SSC on panel\n");
9030                         val |= DREF_SSC1_ENABLE;
9031                 } else
9032                         val &= ~DREF_SSC1_ENABLE;
9033
9034                 /* Get SSC going before enabling the outputs */
9035                 I915_WRITE(PCH_DREF_CONTROL, val);
9036                 POSTING_READ(PCH_DREF_CONTROL);
9037                 udelay(200);
9038
9039                 val &= ~DREF_CPU_SOURCE_OUTPUT_MASK;
9040
9041                 /* Enable CPU source on CPU attached eDP */
9042                 if (has_cpu_edp) {
9043                         if (intel_panel_use_ssc(dev_priv) && can_ssc) {
9044                                 DRM_DEBUG_KMS("Using SSC on eDP\n");
9045                                 val |= DREF_CPU_SOURCE_OUTPUT_DOWNSPREAD;
9046                         } else
9047                                 val |= DREF_CPU_SOURCE_OUTPUT_NONSPREAD;
9048                 } else
9049                         val |= DREF_CPU_SOURCE_OUTPUT_DISABLE;
9050
9051                 I915_WRITE(PCH_DREF_CONTROL, val);
9052                 POSTING_READ(PCH_DREF_CONTROL);
9053                 udelay(200);
9054         } else {
9055                 DRM_DEBUG_KMS("Disabling CPU source output\n");
9056
9057                 val &= ~DREF_CPU_SOURCE_OUTPUT_MASK;
9058
9059                 /* Turn off CPU output */
9060                 val |= DREF_CPU_SOURCE_OUTPUT_DISABLE;
9061
9062                 I915_WRITE(PCH_DREF_CONTROL, val);
9063                 POSTING_READ(PCH_DREF_CONTROL);
9064                 udelay(200);
9065
9066                 if (!using_ssc_source) {
9067                         DRM_DEBUG_KMS("Disabling SSC source\n");
9068
9069                         /* Turn off the SSC source */
9070                         val &= ~DREF_SSC_SOURCE_MASK;
9071                         val |= DREF_SSC_SOURCE_DISABLE;
9072
9073                         /* Turn off SSC1 */
9074                         val &= ~DREF_SSC1_ENABLE;
9075
9076                         I915_WRITE(PCH_DREF_CONTROL, val);
9077                         POSTING_READ(PCH_DREF_CONTROL);
9078                         udelay(200);
9079                 }
9080         }
9081
9082         BUG_ON(val != final);
9083 }
9084
9085 static void lpt_reset_fdi_mphy(struct drm_i915_private *dev_priv)
9086 {
9087         uint32_t tmp;
9088
9089         tmp = I915_READ(SOUTH_CHICKEN2);
9090         tmp |= FDI_MPHY_IOSFSB_RESET_CTL;
9091         I915_WRITE(SOUTH_CHICKEN2, tmp);
9092
9093         if (wait_for_us(I915_READ(SOUTH_CHICKEN2) &
9094                         FDI_MPHY_IOSFSB_RESET_STATUS, 100))
9095                 DRM_ERROR("FDI mPHY reset assert timeout\n");
9096
9097         tmp = I915_READ(SOUTH_CHICKEN2);
9098         tmp &= ~FDI_MPHY_IOSFSB_RESET_CTL;
9099         I915_WRITE(SOUTH_CHICKEN2, tmp);
9100
9101         if (wait_for_us((I915_READ(SOUTH_CHICKEN2) &
9102                          FDI_MPHY_IOSFSB_RESET_STATUS) == 0, 100))
9103                 DRM_ERROR("FDI mPHY reset de-assert timeout\n");
9104 }
9105
9106 /* WaMPhyProgramming:hsw */
9107 static void lpt_program_fdi_mphy(struct drm_i915_private *dev_priv)
9108 {
9109         uint32_t tmp;
9110
9111         tmp = intel_sbi_read(dev_priv, 0x8008, SBI_MPHY);
9112         tmp &= ~(0xFF << 24);
9113         tmp |= (0x12 << 24);
9114         intel_sbi_write(dev_priv, 0x8008, tmp, SBI_MPHY);
9115
9116         tmp = intel_sbi_read(dev_priv, 0x2008, SBI_MPHY);
9117         tmp |= (1 << 11);
9118         intel_sbi_write(dev_priv, 0x2008, tmp, SBI_MPHY);
9119
9120         tmp = intel_sbi_read(dev_priv, 0x2108, SBI_MPHY);
9121         tmp |= (1 << 11);
9122         intel_sbi_write(dev_priv, 0x2108, tmp, SBI_MPHY);
9123
9124         tmp = intel_sbi_read(dev_priv, 0x206C, SBI_MPHY);
9125         tmp |= (1 << 24) | (1 << 21) | (1 << 18);
9126         intel_sbi_write(dev_priv, 0x206C, tmp, SBI_MPHY);
9127
9128         tmp = intel_sbi_read(dev_priv, 0x216C, SBI_MPHY);
9129         tmp |= (1 << 24) | (1 << 21) | (1 << 18);
9130         intel_sbi_write(dev_priv, 0x216C, tmp, SBI_MPHY);
9131
9132         tmp = intel_sbi_read(dev_priv, 0x2080, SBI_MPHY);
9133         tmp &= ~(7 << 13);
9134         tmp |= (5 << 13);
9135         intel_sbi_write(dev_priv, 0x2080, tmp, SBI_MPHY);
9136
9137         tmp = intel_sbi_read(dev_priv, 0x2180, SBI_MPHY);
9138         tmp &= ~(7 << 13);
9139         tmp |= (5 << 13);
9140         intel_sbi_write(dev_priv, 0x2180, tmp, SBI_MPHY);
9141
9142         tmp = intel_sbi_read(dev_priv, 0x208C, SBI_MPHY);
9143         tmp &= ~0xFF;
9144         tmp |= 0x1C;
9145         intel_sbi_write(dev_priv, 0x208C, tmp, SBI_MPHY);
9146
9147         tmp = intel_sbi_read(dev_priv, 0x218C, SBI_MPHY);
9148         tmp &= ~0xFF;
9149         tmp |= 0x1C;
9150         intel_sbi_write(dev_priv, 0x218C, tmp, SBI_MPHY);
9151
9152         tmp = intel_sbi_read(dev_priv, 0x2098, SBI_MPHY);
9153         tmp &= ~(0xFF << 16);
9154         tmp |= (0x1C << 16);
9155         intel_sbi_write(dev_priv, 0x2098, tmp, SBI_MPHY);
9156
9157         tmp = intel_sbi_read(dev_priv, 0x2198, SBI_MPHY);
9158         tmp &= ~(0xFF << 16);
9159         tmp |= (0x1C << 16);
9160         intel_sbi_write(dev_priv, 0x2198, tmp, SBI_MPHY);
9161
9162         tmp = intel_sbi_read(dev_priv, 0x20C4, SBI_MPHY);
9163         tmp |= (1 << 27);
9164         intel_sbi_write(dev_priv, 0x20C4, tmp, SBI_MPHY);
9165
9166         tmp = intel_sbi_read(dev_priv, 0x21C4, SBI_MPHY);
9167         tmp |= (1 << 27);
9168         intel_sbi_write(dev_priv, 0x21C4, tmp, SBI_MPHY);
9169
9170         tmp = intel_sbi_read(dev_priv, 0x20EC, SBI_MPHY);
9171         tmp &= ~(0xF << 28);
9172         tmp |= (4 << 28);
9173         intel_sbi_write(dev_priv, 0x20EC, tmp, SBI_MPHY);
9174
9175         tmp = intel_sbi_read(dev_priv, 0x21EC, SBI_MPHY);
9176         tmp &= ~(0xF << 28);
9177         tmp |= (4 << 28);
9178         intel_sbi_write(dev_priv, 0x21EC, tmp, SBI_MPHY);
9179 }
9180
9181 /* Implements 3 different sequences from BSpec chapter "Display iCLK
9182  * Programming" based on the parameters passed:
9183  * - Sequence to enable CLKOUT_DP
9184  * - Sequence to enable CLKOUT_DP without spread
9185  * - Sequence to enable CLKOUT_DP for FDI usage and configure PCH FDI I/O
9186  */
9187 static void lpt_enable_clkout_dp(struct drm_device *dev, bool with_spread,
9188                                  bool with_fdi)
9189 {
9190         struct drm_i915_private *dev_priv = to_i915(dev);
9191         uint32_t reg, tmp;
9192
9193         if (WARN(with_fdi && !with_spread, "FDI requires downspread\n"))
9194                 with_spread = true;
9195         if (WARN(HAS_PCH_LPT_LP(dev) && with_fdi, "LP PCH doesn't have FDI\n"))
9196                 with_fdi = false;
9197
9198         mutex_lock(&dev_priv->sb_lock);
9199
9200         tmp = intel_sbi_read(dev_priv, SBI_SSCCTL, SBI_ICLK);
9201         tmp &= ~SBI_SSCCTL_DISABLE;
9202         tmp |= SBI_SSCCTL_PATHALT;
9203         intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
9204
9205         udelay(24);
9206
9207         if (with_spread) {
9208                 tmp = intel_sbi_read(dev_priv, SBI_SSCCTL, SBI_ICLK);
9209                 tmp &= ~SBI_SSCCTL_PATHALT;
9210                 intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
9211
9212                 if (with_fdi) {
9213                         lpt_reset_fdi_mphy(dev_priv);
9214                         lpt_program_fdi_mphy(dev_priv);
9215                 }
9216         }
9217
9218         reg = HAS_PCH_LPT_LP(dev) ? SBI_GEN0 : SBI_DBUFF0;
9219         tmp = intel_sbi_read(dev_priv, reg, SBI_ICLK);
9220         tmp |= SBI_GEN0_CFG_BUFFENABLE_DISABLE;
9221         intel_sbi_write(dev_priv, reg, tmp, SBI_ICLK);
9222
9223         mutex_unlock(&dev_priv->sb_lock);
9224 }
9225
9226 /* Sequence to disable CLKOUT_DP */
9227 static void lpt_disable_clkout_dp(struct drm_device *dev)
9228 {
9229         struct drm_i915_private *dev_priv = to_i915(dev);
9230         uint32_t reg, tmp;
9231
9232         mutex_lock(&dev_priv->sb_lock);
9233
9234         reg = HAS_PCH_LPT_LP(dev) ? SBI_GEN0 : SBI_DBUFF0;
9235         tmp = intel_sbi_read(dev_priv, reg, SBI_ICLK);
9236         tmp &= ~SBI_GEN0_CFG_BUFFENABLE_DISABLE;
9237         intel_sbi_write(dev_priv, reg, tmp, SBI_ICLK);
9238
9239         tmp = intel_sbi_read(dev_priv, SBI_SSCCTL, SBI_ICLK);
9240         if (!(tmp & SBI_SSCCTL_DISABLE)) {
9241                 if (!(tmp & SBI_SSCCTL_PATHALT)) {
9242                         tmp |= SBI_SSCCTL_PATHALT;
9243                         intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
9244                         udelay(32);
9245                 }
9246                 tmp |= SBI_SSCCTL_DISABLE;
9247                 intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
9248         }
9249
9250         mutex_unlock(&dev_priv->sb_lock);
9251 }
9252
9253 #define BEND_IDX(steps) ((50 + (steps)) / 5)
9254
9255 static const uint16_t sscdivintphase[] = {
9256         [BEND_IDX( 50)] = 0x3B23,
9257         [BEND_IDX( 45)] = 0x3B23,
9258         [BEND_IDX( 40)] = 0x3C23,
9259         [BEND_IDX( 35)] = 0x3C23,
9260         [BEND_IDX( 30)] = 0x3D23,
9261         [BEND_IDX( 25)] = 0x3D23,
9262         [BEND_IDX( 20)] = 0x3E23,
9263         [BEND_IDX( 15)] = 0x3E23,
9264         [BEND_IDX( 10)] = 0x3F23,
9265         [BEND_IDX(  5)] = 0x3F23,
9266         [BEND_IDX(  0)] = 0x0025,
9267         [BEND_IDX( -5)] = 0x0025,
9268         [BEND_IDX(-10)] = 0x0125,
9269         [BEND_IDX(-15)] = 0x0125,
9270         [BEND_IDX(-20)] = 0x0225,
9271         [BEND_IDX(-25)] = 0x0225,
9272         [BEND_IDX(-30)] = 0x0325,
9273         [BEND_IDX(-35)] = 0x0325,
9274         [BEND_IDX(-40)] = 0x0425,
9275         [BEND_IDX(-45)] = 0x0425,
9276         [BEND_IDX(-50)] = 0x0525,
9277 };
9278
9279 /*
9280  * Bend CLKOUT_DP
9281  * steps -50 to 50 inclusive, in steps of 5
9282  * < 0 slow down the clock, > 0 speed up the clock, 0 == no bend (135MHz)
9283  * change in clock period = -(steps / 10) * 5.787 ps
9284  */
9285 static void lpt_bend_clkout_dp(struct drm_i915_private *dev_priv, int steps)
9286 {
9287         uint32_t tmp;
9288         int idx = BEND_IDX(steps);
9289
9290         if (WARN_ON(steps % 5 != 0))
9291                 return;
9292
9293         if (WARN_ON(idx >= ARRAY_SIZE(sscdivintphase)))
9294                 return;
9295
9296         mutex_lock(&dev_priv->sb_lock);
9297
9298         if (steps % 10 != 0)
9299                 tmp = 0xAAAAAAAB;
9300         else
9301                 tmp = 0x00000000;
9302         intel_sbi_write(dev_priv, SBI_SSCDITHPHASE, tmp, SBI_ICLK);
9303
9304         tmp = intel_sbi_read(dev_priv, SBI_SSCDIVINTPHASE, SBI_ICLK);
9305         tmp &= 0xffff0000;
9306         tmp |= sscdivintphase[idx];
9307         intel_sbi_write(dev_priv, SBI_SSCDIVINTPHASE, tmp, SBI_ICLK);
9308
9309         mutex_unlock(&dev_priv->sb_lock);
9310 }
9311
9312 #undef BEND_IDX
9313
9314 static void lpt_init_pch_refclk(struct drm_device *dev)
9315 {
9316         struct intel_encoder *encoder;
9317         bool has_vga = false;
9318
9319         for_each_intel_encoder(dev, encoder) {
9320                 switch (encoder->type) {
9321                 case INTEL_OUTPUT_ANALOG:
9322                         has_vga = true;
9323                         break;
9324                 default:
9325                         break;
9326                 }
9327         }
9328
9329         if (has_vga) {
9330                 lpt_bend_clkout_dp(to_i915(dev), 0);
9331                 lpt_enable_clkout_dp(dev, true, true);
9332         } else {
9333                 lpt_disable_clkout_dp(dev);
9334         }
9335 }
9336
9337 /*
9338  * Initialize reference clocks when the driver loads
9339  */
9340 void intel_init_pch_refclk(struct drm_device *dev)
9341 {
9342         if (HAS_PCH_IBX(dev) || HAS_PCH_CPT(dev))
9343                 ironlake_init_pch_refclk(dev);
9344         else if (HAS_PCH_LPT(dev))
9345                 lpt_init_pch_refclk(dev);
9346 }
9347
9348 static void ironlake_set_pipeconf(struct drm_crtc *crtc)
9349 {
9350         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
9351         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
9352         int pipe = intel_crtc->pipe;
9353         uint32_t val;
9354
9355         val = 0;
9356
9357         switch (intel_crtc->config->pipe_bpp) {
9358         case 18:
9359                 val |= PIPECONF_6BPC;
9360                 break;
9361         case 24:
9362                 val |= PIPECONF_8BPC;
9363                 break;
9364         case 30:
9365                 val |= PIPECONF_10BPC;
9366                 break;
9367         case 36:
9368                 val |= PIPECONF_12BPC;
9369                 break;
9370         default:
9371                 /* Case prevented by intel_choose_pipe_bpp_dither. */
9372                 BUG();
9373         }
9374
9375         if (intel_crtc->config->dither)
9376                 val |= (PIPECONF_DITHER_EN | PIPECONF_DITHER_TYPE_SP);
9377
9378         if (intel_crtc->config->base.adjusted_mode.flags & DRM_MODE_FLAG_INTERLACE)
9379                 val |= PIPECONF_INTERLACED_ILK;
9380         else
9381                 val |= PIPECONF_PROGRESSIVE;
9382
9383         if (intel_crtc->config->limited_color_range)
9384                 val |= PIPECONF_COLOR_RANGE_SELECT;
9385
9386         I915_WRITE(PIPECONF(pipe), val);
9387         POSTING_READ(PIPECONF(pipe));
9388 }
9389
9390 static void haswell_set_pipeconf(struct drm_crtc *crtc)
9391 {
9392         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
9393         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
9394         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
9395         u32 val = 0;
9396
9397         if (IS_HASWELL(dev_priv) && intel_crtc->config->dither)
9398                 val |= (PIPECONF_DITHER_EN | PIPECONF_DITHER_TYPE_SP);
9399
9400         if (intel_crtc->config->base.adjusted_mode.flags & DRM_MODE_FLAG_INTERLACE)
9401                 val |= PIPECONF_INTERLACED_ILK;
9402         else
9403                 val |= PIPECONF_PROGRESSIVE;
9404
9405         I915_WRITE(PIPECONF(cpu_transcoder), val);
9406         POSTING_READ(PIPECONF(cpu_transcoder));
9407 }
9408
9409 static void haswell_set_pipemisc(struct drm_crtc *crtc)
9410 {
9411         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
9412         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
9413
9414         if (IS_BROADWELL(dev_priv) || INTEL_INFO(dev_priv)->gen >= 9) {
9415                 u32 val = 0;
9416
9417                 switch (intel_crtc->config->pipe_bpp) {
9418                 case 18:
9419                         val |= PIPEMISC_DITHER_6_BPC;
9420                         break;
9421                 case 24:
9422                         val |= PIPEMISC_DITHER_8_BPC;
9423                         break;
9424                 case 30:
9425                         val |= PIPEMISC_DITHER_10_BPC;
9426                         break;
9427                 case 36:
9428                         val |= PIPEMISC_DITHER_12_BPC;
9429                         break;
9430                 default:
9431                         /* Case prevented by pipe_config_set_bpp. */
9432                         BUG();
9433                 }
9434
9435                 if (intel_crtc->config->dither)
9436                         val |= PIPEMISC_DITHER_ENABLE | PIPEMISC_DITHER_TYPE_SP;
9437
9438                 I915_WRITE(PIPEMISC(intel_crtc->pipe), val);
9439         }
9440 }
9441
9442 int ironlake_get_lanes_required(int target_clock, int link_bw, int bpp)
9443 {
9444         /*
9445          * Account for spread spectrum to avoid
9446          * oversubscribing the link. Max center spread
9447          * is 2.5%; use 5% for safety's sake.
9448          */
9449         u32 bps = target_clock * bpp * 21 / 20;
9450         return DIV_ROUND_UP(bps, link_bw * 8);
9451 }
9452
9453 static bool ironlake_needs_fb_cb_tune(struct dpll *dpll, int factor)
9454 {
9455         return i9xx_dpll_compute_m(dpll) < factor * dpll->n;
9456 }
9457
9458 static void ironlake_compute_dpll(struct intel_crtc *intel_crtc,
9459                                   struct intel_crtc_state *crtc_state,
9460                                   struct dpll *reduced_clock)
9461 {
9462         struct drm_crtc *crtc = &intel_crtc->base;
9463         struct drm_device *dev = crtc->dev;
9464         struct drm_i915_private *dev_priv = to_i915(dev);
9465         u32 dpll, fp, fp2;
9466         int factor;
9467
9468         /* Enable autotuning of the PLL clock (if permissible) */
9469         factor = 21;
9470         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
9471                 if ((intel_panel_use_ssc(dev_priv) &&
9472                      dev_priv->vbt.lvds_ssc_freq == 100000) ||
9473                     (HAS_PCH_IBX(dev) && intel_is_dual_link_lvds(dev)))
9474                         factor = 25;
9475         } else if (crtc_state->sdvo_tv_clock)
9476                 factor = 20;
9477
9478         fp = i9xx_dpll_compute_fp(&crtc_state->dpll);
9479
9480         if (ironlake_needs_fb_cb_tune(&crtc_state->dpll, factor))
9481                 fp |= FP_CB_TUNE;
9482
9483         if (reduced_clock) {
9484                 fp2 = i9xx_dpll_compute_fp(reduced_clock);
9485
9486                 if (reduced_clock->m < factor * reduced_clock->n)
9487                         fp2 |= FP_CB_TUNE;
9488         } else {
9489                 fp2 = fp;
9490         }
9491
9492         dpll = 0;
9493
9494         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS))
9495                 dpll |= DPLLB_MODE_LVDS;
9496         else
9497                 dpll |= DPLLB_MODE_DAC_SERIAL;
9498
9499         dpll |= (crtc_state->pixel_multiplier - 1)
9500                 << PLL_REF_SDVO_HDMI_MULTIPLIER_SHIFT;
9501
9502         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_SDVO) ||
9503             intel_crtc_has_type(crtc_state, INTEL_OUTPUT_HDMI))
9504                 dpll |= DPLL_SDVO_HIGH_SPEED;
9505
9506         if (intel_crtc_has_dp_encoder(crtc_state))
9507                 dpll |= DPLL_SDVO_HIGH_SPEED;
9508
9509         /*
9510          * The high speed IO clock is only really required for
9511          * SDVO/HDMI/DP, but we also enable it for CRT to make it
9512          * possible to share the DPLL between CRT and HDMI. Enabling
9513          * the clock needlessly does no real harm, except use up a
9514          * bit of power potentially.
9515          *
9516          * We'll limit this to IVB with 3 pipes, since it has only two
9517          * DPLLs and so DPLL sharing is the only way to get three pipes
9518          * driving PCH ports at the same time. On SNB we could do this,
9519          * and potentially avoid enabling the second DPLL, but it's not
9520          * clear if it''s a win or loss power wise. No point in doing
9521          * this on ILK at all since it has a fixed DPLL<->pipe mapping.
9522          */
9523         if (INTEL_INFO(dev_priv)->num_pipes == 3 &&
9524             intel_crtc_has_type(crtc_state, INTEL_OUTPUT_ANALOG))
9525                 dpll |= DPLL_SDVO_HIGH_SPEED;
9526
9527         /* compute bitmask from p1 value */
9528         dpll |= (1 << (crtc_state->dpll.p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT;
9529         /* also FPA1 */
9530         dpll |= (1 << (crtc_state->dpll.p1 - 1)) << DPLL_FPA1_P1_POST_DIV_SHIFT;
9531
9532         switch (crtc_state->dpll.p2) {
9533         case 5:
9534                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_5;
9535                 break;
9536         case 7:
9537                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_7;
9538                 break;
9539         case 10:
9540                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_10;
9541                 break;
9542         case 14:
9543                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_14;
9544                 break;
9545         }
9546
9547         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS) &&
9548             intel_panel_use_ssc(dev_priv))
9549                 dpll |= PLLB_REF_INPUT_SPREADSPECTRUMIN;
9550         else
9551                 dpll |= PLL_REF_INPUT_DREFCLK;
9552
9553         dpll |= DPLL_VCO_ENABLE;
9554
9555         crtc_state->dpll_hw_state.dpll = dpll;
9556         crtc_state->dpll_hw_state.fp0 = fp;
9557         crtc_state->dpll_hw_state.fp1 = fp2;
9558 }
9559
9560 static int ironlake_crtc_compute_clock(struct intel_crtc *crtc,
9561                                        struct intel_crtc_state *crtc_state)
9562 {
9563         struct drm_device *dev = crtc->base.dev;
9564         struct drm_i915_private *dev_priv = to_i915(dev);
9565         struct dpll reduced_clock;
9566         bool has_reduced_clock = false;
9567         struct intel_shared_dpll *pll;
9568         const struct intel_limit *limit;
9569         int refclk = 120000;
9570
9571         memset(&crtc_state->dpll_hw_state, 0,
9572                sizeof(crtc_state->dpll_hw_state));
9573
9574         crtc->lowfreq_avail = false;
9575
9576         /* CPU eDP is the only output that doesn't need a PCH PLL of its own. */
9577         if (!crtc_state->has_pch_encoder)
9578                 return 0;
9579
9580         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
9581                 if (intel_panel_use_ssc(dev_priv)) {
9582                         DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n",
9583                                       dev_priv->vbt.lvds_ssc_freq);
9584                         refclk = dev_priv->vbt.lvds_ssc_freq;
9585                 }
9586
9587                 if (intel_is_dual_link_lvds(dev)) {
9588                         if (refclk == 100000)
9589                                 limit = &intel_limits_ironlake_dual_lvds_100m;
9590                         else
9591                                 limit = &intel_limits_ironlake_dual_lvds;
9592                 } else {
9593                         if (refclk == 100000)
9594                                 limit = &intel_limits_ironlake_single_lvds_100m;
9595                         else
9596                                 limit = &intel_limits_ironlake_single_lvds;
9597                 }
9598         } else {
9599                 limit = &intel_limits_ironlake_dac;
9600         }
9601
9602         if (!crtc_state->clock_set &&
9603             !g4x_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
9604                                 refclk, NULL, &crtc_state->dpll)) {
9605                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
9606                 return -EINVAL;
9607         }
9608
9609         ironlake_compute_dpll(crtc, crtc_state,
9610                               has_reduced_clock ? &reduced_clock : NULL);
9611
9612         pll = intel_get_shared_dpll(crtc, crtc_state, NULL);
9613         if (pll == NULL) {
9614                 DRM_DEBUG_DRIVER("failed to find PLL for pipe %c\n",
9615                                  pipe_name(crtc->pipe));
9616                 return -EINVAL;
9617         }
9618
9619         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS) &&
9620             has_reduced_clock)
9621                 crtc->lowfreq_avail = true;
9622
9623         return 0;
9624 }
9625
9626 static void intel_pch_transcoder_get_m_n(struct intel_crtc *crtc,
9627                                          struct intel_link_m_n *m_n)
9628 {
9629         struct drm_device *dev = crtc->base.dev;
9630         struct drm_i915_private *dev_priv = to_i915(dev);
9631         enum pipe pipe = crtc->pipe;
9632
9633         m_n->link_m = I915_READ(PCH_TRANS_LINK_M1(pipe));
9634         m_n->link_n = I915_READ(PCH_TRANS_LINK_N1(pipe));
9635         m_n->gmch_m = I915_READ(PCH_TRANS_DATA_M1(pipe))
9636                 & ~TU_SIZE_MASK;
9637         m_n->gmch_n = I915_READ(PCH_TRANS_DATA_N1(pipe));
9638         m_n->tu = ((I915_READ(PCH_TRANS_DATA_M1(pipe))
9639                     & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
9640 }
9641
9642 static void intel_cpu_transcoder_get_m_n(struct intel_crtc *crtc,
9643                                          enum transcoder transcoder,
9644                                          struct intel_link_m_n *m_n,
9645                                          struct intel_link_m_n *m2_n2)
9646 {
9647         struct drm_device *dev = crtc->base.dev;
9648         struct drm_i915_private *dev_priv = to_i915(dev);
9649         enum pipe pipe = crtc->pipe;
9650
9651         if (INTEL_INFO(dev)->gen >= 5) {
9652                 m_n->link_m = I915_READ(PIPE_LINK_M1(transcoder));
9653                 m_n->link_n = I915_READ(PIPE_LINK_N1(transcoder));
9654                 m_n->gmch_m = I915_READ(PIPE_DATA_M1(transcoder))
9655                         & ~TU_SIZE_MASK;
9656                 m_n->gmch_n = I915_READ(PIPE_DATA_N1(transcoder));
9657                 m_n->tu = ((I915_READ(PIPE_DATA_M1(transcoder))
9658                             & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
9659                 /* Read M2_N2 registers only for gen < 8 (M2_N2 available for
9660                  * gen < 8) and if DRRS is supported (to make sure the
9661                  * registers are not unnecessarily read).
9662                  */
9663                 if (m2_n2 && INTEL_INFO(dev)->gen < 8 &&
9664                         crtc->config->has_drrs) {
9665                         m2_n2->link_m = I915_READ(PIPE_LINK_M2(transcoder));
9666                         m2_n2->link_n = I915_READ(PIPE_LINK_N2(transcoder));
9667                         m2_n2->gmch_m = I915_READ(PIPE_DATA_M2(transcoder))
9668                                         & ~TU_SIZE_MASK;
9669                         m2_n2->gmch_n = I915_READ(PIPE_DATA_N2(transcoder));
9670                         m2_n2->tu = ((I915_READ(PIPE_DATA_M2(transcoder))
9671                                         & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
9672                 }
9673         } else {
9674                 m_n->link_m = I915_READ(PIPE_LINK_M_G4X(pipe));
9675                 m_n->link_n = I915_READ(PIPE_LINK_N_G4X(pipe));
9676                 m_n->gmch_m = I915_READ(PIPE_DATA_M_G4X(pipe))
9677                         & ~TU_SIZE_MASK;
9678                 m_n->gmch_n = I915_READ(PIPE_DATA_N_G4X(pipe));
9679                 m_n->tu = ((I915_READ(PIPE_DATA_M_G4X(pipe))
9680                             & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
9681         }
9682 }
9683
9684 void intel_dp_get_m_n(struct intel_crtc *crtc,
9685                       struct intel_crtc_state *pipe_config)
9686 {
9687         if (pipe_config->has_pch_encoder)
9688                 intel_pch_transcoder_get_m_n(crtc, &pipe_config->dp_m_n);
9689         else
9690                 intel_cpu_transcoder_get_m_n(crtc, pipe_config->cpu_transcoder,
9691                                              &pipe_config->dp_m_n,
9692                                              &pipe_config->dp_m2_n2);
9693 }
9694
9695 static void ironlake_get_fdi_m_n_config(struct intel_crtc *crtc,
9696                                         struct intel_crtc_state *pipe_config)
9697 {
9698         intel_cpu_transcoder_get_m_n(crtc, pipe_config->cpu_transcoder,
9699                                      &pipe_config->fdi_m_n, NULL);
9700 }
9701
9702 static void skylake_get_pfit_config(struct intel_crtc *crtc,
9703                                     struct intel_crtc_state *pipe_config)
9704 {
9705         struct drm_device *dev = crtc->base.dev;
9706         struct drm_i915_private *dev_priv = to_i915(dev);
9707         struct intel_crtc_scaler_state *scaler_state = &pipe_config->scaler_state;
9708         uint32_t ps_ctrl = 0;
9709         int id = -1;
9710         int i;
9711
9712         /* find scaler attached to this pipe */
9713         for (i = 0; i < crtc->num_scalers; i++) {
9714                 ps_ctrl = I915_READ(SKL_PS_CTRL(crtc->pipe, i));
9715                 if (ps_ctrl & PS_SCALER_EN && !(ps_ctrl & PS_PLANE_SEL_MASK)) {
9716                         id = i;
9717                         pipe_config->pch_pfit.enabled = true;
9718                         pipe_config->pch_pfit.pos = I915_READ(SKL_PS_WIN_POS(crtc->pipe, i));
9719                         pipe_config->pch_pfit.size = I915_READ(SKL_PS_WIN_SZ(crtc->pipe, i));
9720                         break;
9721                 }
9722         }
9723
9724         scaler_state->scaler_id = id;
9725         if (id >= 0) {
9726                 scaler_state->scaler_users |= (1 << SKL_CRTC_INDEX);
9727         } else {
9728                 scaler_state->scaler_users &= ~(1 << SKL_CRTC_INDEX);
9729         }
9730 }
9731
9732 static void
9733 skylake_get_initial_plane_config(struct intel_crtc *crtc,
9734                                  struct intel_initial_plane_config *plane_config)
9735 {
9736         struct drm_device *dev = crtc->base.dev;
9737         struct drm_i915_private *dev_priv = to_i915(dev);
9738         u32 val, base, offset, stride_mult, tiling;
9739         int pipe = crtc->pipe;
9740         int fourcc, pixel_format;
9741         unsigned int aligned_height;
9742         struct drm_framebuffer *fb;
9743         struct intel_framebuffer *intel_fb;
9744
9745         intel_fb = kzalloc(sizeof(*intel_fb), GFP_KERNEL);
9746         if (!intel_fb) {
9747                 DRM_DEBUG_KMS("failed to alloc fb\n");
9748                 return;
9749         }
9750
9751         fb = &intel_fb->base;
9752
9753         val = I915_READ(PLANE_CTL(pipe, 0));
9754         if (!(val & PLANE_CTL_ENABLE))
9755                 goto error;
9756
9757         pixel_format = val & PLANE_CTL_FORMAT_MASK;
9758         fourcc = skl_format_to_fourcc(pixel_format,
9759                                       val & PLANE_CTL_ORDER_RGBX,
9760                                       val & PLANE_CTL_ALPHA_MASK);
9761         fb->pixel_format = fourcc;
9762         fb->bits_per_pixel = drm_format_plane_cpp(fourcc, 0) * 8;
9763
9764         tiling = val & PLANE_CTL_TILED_MASK;
9765         switch (tiling) {
9766         case PLANE_CTL_TILED_LINEAR:
9767                 fb->modifier[0] = DRM_FORMAT_MOD_NONE;
9768                 break;
9769         case PLANE_CTL_TILED_X:
9770                 plane_config->tiling = I915_TILING_X;
9771                 fb->modifier[0] = I915_FORMAT_MOD_X_TILED;
9772                 break;
9773         case PLANE_CTL_TILED_Y:
9774                 fb->modifier[0] = I915_FORMAT_MOD_Y_TILED;
9775                 break;
9776         case PLANE_CTL_TILED_YF:
9777                 fb->modifier[0] = I915_FORMAT_MOD_Yf_TILED;
9778                 break;
9779         default:
9780                 MISSING_CASE(tiling);
9781                 goto error;
9782         }
9783
9784         base = I915_READ(PLANE_SURF(pipe, 0)) & 0xfffff000;
9785         plane_config->base = base;
9786
9787         offset = I915_READ(PLANE_OFFSET(pipe, 0));
9788
9789         val = I915_READ(PLANE_SIZE(pipe, 0));
9790         fb->height = ((val >> 16) & 0xfff) + 1;
9791         fb->width = ((val >> 0) & 0x1fff) + 1;
9792
9793         val = I915_READ(PLANE_STRIDE(pipe, 0));
9794         stride_mult = intel_fb_stride_alignment(dev_priv, fb->modifier[0],
9795                                                 fb->pixel_format);
9796         fb->pitches[0] = (val & 0x3ff) * stride_mult;
9797
9798         aligned_height = intel_fb_align_height(dev, fb->height,
9799                                                fb->pixel_format,
9800                                                fb->modifier[0]);
9801
9802         plane_config->size = fb->pitches[0] * aligned_height;
9803
9804         DRM_DEBUG_KMS("pipe %c with fb: size=%dx%d@%d, offset=%x, pitch %d, size 0x%x\n",
9805                       pipe_name(pipe), fb->width, fb->height,
9806                       fb->bits_per_pixel, base, fb->pitches[0],
9807                       plane_config->size);
9808
9809         plane_config->fb = intel_fb;
9810         return;
9811
9812 error:
9813         kfree(intel_fb);
9814 }
9815
9816 static void ironlake_get_pfit_config(struct intel_crtc *crtc,
9817                                      struct intel_crtc_state *pipe_config)
9818 {
9819         struct drm_device *dev = crtc->base.dev;
9820         struct drm_i915_private *dev_priv = to_i915(dev);
9821         uint32_t tmp;
9822
9823         tmp = I915_READ(PF_CTL(crtc->pipe));
9824
9825         if (tmp & PF_ENABLE) {
9826                 pipe_config->pch_pfit.enabled = true;
9827                 pipe_config->pch_pfit.pos = I915_READ(PF_WIN_POS(crtc->pipe));
9828                 pipe_config->pch_pfit.size = I915_READ(PF_WIN_SZ(crtc->pipe));
9829
9830                 /* We currently do not free assignements of panel fitters on
9831                  * ivb/hsw (since we don't use the higher upscaling modes which
9832                  * differentiates them) so just WARN about this case for now. */
9833                 if (IS_GEN7(dev)) {
9834                         WARN_ON((tmp & PF_PIPE_SEL_MASK_IVB) !=
9835                                 PF_PIPE_SEL_IVB(crtc->pipe));
9836                 }
9837         }
9838 }
9839
9840 static void
9841 ironlake_get_initial_plane_config(struct intel_crtc *crtc,
9842                                   struct intel_initial_plane_config *plane_config)
9843 {
9844         struct drm_device *dev = crtc->base.dev;
9845         struct drm_i915_private *dev_priv = to_i915(dev);
9846         u32 val, base, offset;
9847         int pipe = crtc->pipe;
9848         int fourcc, pixel_format;
9849         unsigned int aligned_height;
9850         struct drm_framebuffer *fb;
9851         struct intel_framebuffer *intel_fb;
9852
9853         val = I915_READ(DSPCNTR(pipe));
9854         if (!(val & DISPLAY_PLANE_ENABLE))
9855                 return;
9856
9857         intel_fb = kzalloc(sizeof(*intel_fb), GFP_KERNEL);
9858         if (!intel_fb) {
9859                 DRM_DEBUG_KMS("failed to alloc fb\n");
9860                 return;
9861         }
9862
9863         fb = &intel_fb->base;
9864
9865         if (INTEL_INFO(dev)->gen >= 4) {
9866                 if (val & DISPPLANE_TILED) {
9867                         plane_config->tiling = I915_TILING_X;
9868                         fb->modifier[0] = I915_FORMAT_MOD_X_TILED;
9869                 }
9870         }
9871
9872         pixel_format = val & DISPPLANE_PIXFORMAT_MASK;
9873         fourcc = i9xx_format_to_fourcc(pixel_format);
9874         fb->pixel_format = fourcc;
9875         fb->bits_per_pixel = drm_format_plane_cpp(fourcc, 0) * 8;
9876
9877         base = I915_READ(DSPSURF(pipe)) & 0xfffff000;
9878         if (IS_HASWELL(dev) || IS_BROADWELL(dev)) {
9879                 offset = I915_READ(DSPOFFSET(pipe));
9880         } else {
9881                 if (plane_config->tiling)
9882                         offset = I915_READ(DSPTILEOFF(pipe));
9883                 else
9884                         offset = I915_READ(DSPLINOFF(pipe));
9885         }
9886         plane_config->base = base;
9887
9888         val = I915_READ(PIPESRC(pipe));
9889         fb->width = ((val >> 16) & 0xfff) + 1;
9890         fb->height = ((val >> 0) & 0xfff) + 1;
9891
9892         val = I915_READ(DSPSTRIDE(pipe));
9893         fb->pitches[0] = val & 0xffffffc0;
9894
9895         aligned_height = intel_fb_align_height(dev, fb->height,
9896                                                fb->pixel_format,
9897                                                fb->modifier[0]);
9898
9899         plane_config->size = fb->pitches[0] * aligned_height;
9900
9901         DRM_DEBUG_KMS("pipe %c with fb: size=%dx%d@%d, offset=%x, pitch %d, size 0x%x\n",
9902                       pipe_name(pipe), fb->width, fb->height,
9903                       fb->bits_per_pixel, base, fb->pitches[0],
9904                       plane_config->size);
9905
9906         plane_config->fb = intel_fb;
9907 }
9908
9909 static bool ironlake_get_pipe_config(struct intel_crtc *crtc,
9910                                      struct intel_crtc_state *pipe_config)
9911 {
9912         struct drm_device *dev = crtc->base.dev;
9913         struct drm_i915_private *dev_priv = to_i915(dev);
9914         enum intel_display_power_domain power_domain;
9915         uint32_t tmp;
9916         bool ret;
9917
9918         power_domain = POWER_DOMAIN_PIPE(crtc->pipe);
9919         if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
9920                 return false;
9921
9922         pipe_config->cpu_transcoder = (enum transcoder) crtc->pipe;
9923         pipe_config->shared_dpll = NULL;
9924
9925         ret = false;
9926         tmp = I915_READ(PIPECONF(crtc->pipe));
9927         if (!(tmp & PIPECONF_ENABLE))
9928                 goto out;
9929
9930         switch (tmp & PIPECONF_BPC_MASK) {
9931         case PIPECONF_6BPC:
9932                 pipe_config->pipe_bpp = 18;
9933                 break;
9934         case PIPECONF_8BPC:
9935                 pipe_config->pipe_bpp = 24;
9936                 break;
9937         case PIPECONF_10BPC:
9938                 pipe_config->pipe_bpp = 30;
9939                 break;
9940         case PIPECONF_12BPC:
9941                 pipe_config->pipe_bpp = 36;
9942                 break;
9943         default:
9944                 break;
9945         }
9946
9947         if (tmp & PIPECONF_COLOR_RANGE_SELECT)
9948                 pipe_config->limited_color_range = true;
9949
9950         if (I915_READ(PCH_TRANSCONF(crtc->pipe)) & TRANS_ENABLE) {
9951                 struct intel_shared_dpll *pll;
9952                 enum intel_dpll_id pll_id;
9953
9954                 pipe_config->has_pch_encoder = true;
9955
9956                 tmp = I915_READ(FDI_RX_CTL(crtc->pipe));
9957                 pipe_config->fdi_lanes = ((FDI_DP_PORT_WIDTH_MASK & tmp) >>
9958                                           FDI_DP_PORT_WIDTH_SHIFT) + 1;
9959
9960                 ironlake_get_fdi_m_n_config(crtc, pipe_config);
9961
9962                 if (HAS_PCH_IBX(dev_priv)) {
9963                         /*
9964                          * The pipe->pch transcoder and pch transcoder->pll
9965                          * mapping is fixed.
9966                          */
9967                         pll_id = (enum intel_dpll_id) crtc->pipe;
9968                 } else {
9969                         tmp = I915_READ(PCH_DPLL_SEL);
9970                         if (tmp & TRANS_DPLLB_SEL(crtc->pipe))
9971                                 pll_id = DPLL_ID_PCH_PLL_B;
9972                         else
9973                                 pll_id= DPLL_ID_PCH_PLL_A;
9974                 }
9975
9976                 pipe_config->shared_dpll =
9977                         intel_get_shared_dpll_by_id(dev_priv, pll_id);
9978                 pll = pipe_config->shared_dpll;
9979
9980                 WARN_ON(!pll->funcs.get_hw_state(dev_priv, pll,
9981                                                  &pipe_config->dpll_hw_state));
9982
9983                 tmp = pipe_config->dpll_hw_state.dpll;
9984                 pipe_config->pixel_multiplier =
9985                         ((tmp & PLL_REF_SDVO_HDMI_MULTIPLIER_MASK)
9986                          >> PLL_REF_SDVO_HDMI_MULTIPLIER_SHIFT) + 1;
9987
9988                 ironlake_pch_clock_get(crtc, pipe_config);
9989         } else {
9990                 pipe_config->pixel_multiplier = 1;
9991         }
9992
9993         intel_get_pipe_timings(crtc, pipe_config);
9994         intel_get_pipe_src_size(crtc, pipe_config);
9995
9996         ironlake_get_pfit_config(crtc, pipe_config);
9997
9998         ret = true;
9999
10000 out:
10001         intel_display_power_put(dev_priv, power_domain);
10002
10003         return ret;
10004 }
10005
10006 static void assert_can_disable_lcpll(struct drm_i915_private *dev_priv)
10007 {
10008         struct drm_device *dev = &dev_priv->drm;
10009         struct intel_crtc *crtc;
10010
10011         for_each_intel_crtc(dev, crtc)
10012                 I915_STATE_WARN(crtc->active, "CRTC for pipe %c enabled\n",
10013                      pipe_name(crtc->pipe));
10014
10015         I915_STATE_WARN(I915_READ(HSW_PWR_WELL_DRIVER), "Power well on\n");
10016         I915_STATE_WARN(I915_READ(SPLL_CTL) & SPLL_PLL_ENABLE, "SPLL enabled\n");
10017         I915_STATE_WARN(I915_READ(WRPLL_CTL(0)) & WRPLL_PLL_ENABLE, "WRPLL1 enabled\n");
10018         I915_STATE_WARN(I915_READ(WRPLL_CTL(1)) & WRPLL_PLL_ENABLE, "WRPLL2 enabled\n");
10019         I915_STATE_WARN(I915_READ(PP_STATUS(0)) & PP_ON, "Panel power on\n");
10020         I915_STATE_WARN(I915_READ(BLC_PWM_CPU_CTL2) & BLM_PWM_ENABLE,
10021              "CPU PWM1 enabled\n");
10022         if (IS_HASWELL(dev))
10023                 I915_STATE_WARN(I915_READ(HSW_BLC_PWM2_CTL) & BLM_PWM_ENABLE,
10024                      "CPU PWM2 enabled\n");
10025         I915_STATE_WARN(I915_READ(BLC_PWM_PCH_CTL1) & BLM_PCH_PWM_ENABLE,
10026              "PCH PWM1 enabled\n");
10027         I915_STATE_WARN(I915_READ(UTIL_PIN_CTL) & UTIL_PIN_ENABLE,
10028              "Utility pin enabled\n");
10029         I915_STATE_WARN(I915_READ(PCH_GTC_CTL) & PCH_GTC_ENABLE, "PCH GTC enabled\n");
10030
10031         /*
10032          * In theory we can still leave IRQs enabled, as long as only the HPD
10033          * interrupts remain enabled. We used to check for that, but since it's
10034          * gen-specific and since we only disable LCPLL after we fully disable
10035          * the interrupts, the check below should be enough.
10036          */
10037         I915_STATE_WARN(intel_irqs_enabled(dev_priv), "IRQs enabled\n");
10038 }
10039
10040 static uint32_t hsw_read_dcomp(struct drm_i915_private *dev_priv)
10041 {
10042         struct drm_device *dev = &dev_priv->drm;
10043
10044         if (IS_HASWELL(dev))
10045                 return I915_READ(D_COMP_HSW);
10046         else
10047                 return I915_READ(D_COMP_BDW);
10048 }
10049
10050 static void hsw_write_dcomp(struct drm_i915_private *dev_priv, uint32_t val)
10051 {
10052         struct drm_device *dev = &dev_priv->drm;
10053
10054         if (IS_HASWELL(dev)) {
10055                 mutex_lock(&dev_priv->rps.hw_lock);
10056                 if (sandybridge_pcode_write(dev_priv, GEN6_PCODE_WRITE_D_COMP,
10057                                             val))
10058                         DRM_DEBUG_KMS("Failed to write to D_COMP\n");
10059                 mutex_unlock(&dev_priv->rps.hw_lock);
10060         } else {
10061                 I915_WRITE(D_COMP_BDW, val);
10062                 POSTING_READ(D_COMP_BDW);
10063         }
10064 }
10065
10066 /*
10067  * This function implements pieces of two sequences from BSpec:
10068  * - Sequence for display software to disable LCPLL
10069  * - Sequence for display software to allow package C8+
10070  * The steps implemented here are just the steps that actually touch the LCPLL
10071  * register. Callers should take care of disabling all the display engine
10072  * functions, doing the mode unset, fixing interrupts, etc.
10073  */
10074 static void hsw_disable_lcpll(struct drm_i915_private *dev_priv,
10075                               bool switch_to_fclk, bool allow_power_down)
10076 {
10077         uint32_t val;
10078
10079         assert_can_disable_lcpll(dev_priv);
10080
10081         val = I915_READ(LCPLL_CTL);
10082
10083         if (switch_to_fclk) {
10084                 val |= LCPLL_CD_SOURCE_FCLK;
10085                 I915_WRITE(LCPLL_CTL, val);
10086
10087                 if (wait_for_us(I915_READ(LCPLL_CTL) &
10088                                 LCPLL_CD_SOURCE_FCLK_DONE, 1))
10089                         DRM_ERROR("Switching to FCLK failed\n");
10090
10091                 val = I915_READ(LCPLL_CTL);
10092         }
10093
10094         val |= LCPLL_PLL_DISABLE;
10095         I915_WRITE(LCPLL_CTL, val);
10096         POSTING_READ(LCPLL_CTL);
10097
10098         if (intel_wait_for_register(dev_priv, LCPLL_CTL, LCPLL_PLL_LOCK, 0, 1))
10099                 DRM_ERROR("LCPLL still locked\n");
10100
10101         val = hsw_read_dcomp(dev_priv);
10102         val |= D_COMP_COMP_DISABLE;
10103         hsw_write_dcomp(dev_priv, val);
10104         ndelay(100);
10105
10106         if (wait_for((hsw_read_dcomp(dev_priv) & D_COMP_RCOMP_IN_PROGRESS) == 0,
10107                      1))
10108                 DRM_ERROR("D_COMP RCOMP still in progress\n");
10109
10110         if (allow_power_down) {
10111                 val = I915_READ(LCPLL_CTL);
10112                 val |= LCPLL_POWER_DOWN_ALLOW;
10113                 I915_WRITE(LCPLL_CTL, val);
10114                 POSTING_READ(LCPLL_CTL);
10115         }
10116 }
10117
10118 /*
10119  * Fully restores LCPLL, disallowing power down and switching back to LCPLL
10120  * source.
10121  */
10122 static void hsw_restore_lcpll(struct drm_i915_private *dev_priv)
10123 {
10124         uint32_t val;
10125
10126         val = I915_READ(LCPLL_CTL);
10127
10128         if ((val & (LCPLL_PLL_LOCK | LCPLL_PLL_DISABLE | LCPLL_CD_SOURCE_FCLK |
10129                     LCPLL_POWER_DOWN_ALLOW)) == LCPLL_PLL_LOCK)
10130                 return;
10131
10132         /*
10133          * Make sure we're not on PC8 state before disabling PC8, otherwise
10134          * we'll hang the machine. To prevent PC8 state, just enable force_wake.
10135          */
10136         intel_uncore_forcewake_get(dev_priv, FORCEWAKE_ALL);
10137
10138         if (val & LCPLL_POWER_DOWN_ALLOW) {
10139                 val &= ~LCPLL_POWER_DOWN_ALLOW;
10140                 I915_WRITE(LCPLL_CTL, val);
10141                 POSTING_READ(LCPLL_CTL);
10142         }
10143
10144         val = hsw_read_dcomp(dev_priv);
10145         val |= D_COMP_COMP_FORCE;
10146         val &= ~D_COMP_COMP_DISABLE;
10147         hsw_write_dcomp(dev_priv, val);
10148
10149         val = I915_READ(LCPLL_CTL);
10150         val &= ~LCPLL_PLL_DISABLE;
10151         I915_WRITE(LCPLL_CTL, val);
10152
10153         if (intel_wait_for_register(dev_priv,
10154                                     LCPLL_CTL, LCPLL_PLL_LOCK, LCPLL_PLL_LOCK,
10155                                     5))
10156                 DRM_ERROR("LCPLL not locked yet\n");
10157
10158         if (val & LCPLL_CD_SOURCE_FCLK) {
10159                 val = I915_READ(LCPLL_CTL);
10160                 val &= ~LCPLL_CD_SOURCE_FCLK;
10161                 I915_WRITE(LCPLL_CTL, val);
10162
10163                 if (wait_for_us((I915_READ(LCPLL_CTL) &
10164                                  LCPLL_CD_SOURCE_FCLK_DONE) == 0, 1))
10165                         DRM_ERROR("Switching back to LCPLL failed\n");
10166         }
10167
10168         intel_uncore_forcewake_put(dev_priv, FORCEWAKE_ALL);
10169         intel_update_cdclk(&dev_priv->drm);
10170 }
10171
10172 /*
10173  * Package states C8 and deeper are really deep PC states that can only be
10174  * reached when all the devices on the system allow it, so even if the graphics
10175  * device allows PC8+, it doesn't mean the system will actually get to these
10176  * states. Our driver only allows PC8+ when going into runtime PM.
10177  *
10178  * The requirements for PC8+ are that all the outputs are disabled, the power
10179  * well is disabled and most interrupts are disabled, and these are also
10180  * requirements for runtime PM. When these conditions are met, we manually do
10181  * the other conditions: disable the interrupts, clocks and switch LCPLL refclk
10182  * to Fclk. If we're in PC8+ and we get an non-hotplug interrupt, we can hard
10183  * hang the machine.
10184  *
10185  * When we really reach PC8 or deeper states (not just when we allow it) we lose
10186  * the state of some registers, so when we come back from PC8+ we need to
10187  * restore this state. We don't get into PC8+ if we're not in RC6, so we don't
10188  * need to take care of the registers kept by RC6. Notice that this happens even
10189  * if we don't put the device in PCI D3 state (which is what currently happens
10190  * because of the runtime PM support).
10191  *
10192  * For more, read "Display Sequences for Package C8" on the hardware
10193  * documentation.
10194  */
10195 void hsw_enable_pc8(struct drm_i915_private *dev_priv)
10196 {
10197         struct drm_device *dev = &dev_priv->drm;
10198         uint32_t val;
10199
10200         DRM_DEBUG_KMS("Enabling package C8+\n");
10201
10202         if (HAS_PCH_LPT_LP(dev)) {
10203                 val = I915_READ(SOUTH_DSPCLK_GATE_D);
10204                 val &= ~PCH_LP_PARTITION_LEVEL_DISABLE;
10205                 I915_WRITE(SOUTH_DSPCLK_GATE_D, val);
10206         }
10207
10208         lpt_disable_clkout_dp(dev);
10209         hsw_disable_lcpll(dev_priv, true, true);
10210 }
10211
10212 void hsw_disable_pc8(struct drm_i915_private *dev_priv)
10213 {
10214         struct drm_device *dev = &dev_priv->drm;
10215         uint32_t val;
10216
10217         DRM_DEBUG_KMS("Disabling package C8+\n");
10218
10219         hsw_restore_lcpll(dev_priv);
10220         lpt_init_pch_refclk(dev);
10221
10222         if (HAS_PCH_LPT_LP(dev)) {
10223                 val = I915_READ(SOUTH_DSPCLK_GATE_D);
10224                 val |= PCH_LP_PARTITION_LEVEL_DISABLE;
10225                 I915_WRITE(SOUTH_DSPCLK_GATE_D, val);
10226         }
10227 }
10228
10229 static void bxt_modeset_commit_cdclk(struct drm_atomic_state *old_state)
10230 {
10231         struct drm_device *dev = old_state->dev;
10232         struct intel_atomic_state *old_intel_state =
10233                 to_intel_atomic_state(old_state);
10234         unsigned int req_cdclk = old_intel_state->dev_cdclk;
10235
10236         bxt_set_cdclk(to_i915(dev), req_cdclk);
10237 }
10238
10239 static int bdw_adjust_min_pipe_pixel_rate(struct intel_crtc_state *crtc_state,
10240                                           int pixel_rate)
10241 {
10242         struct drm_i915_private *dev_priv = to_i915(crtc_state->base.crtc->dev);
10243
10244         /* pixel rate mustn't exceed 95% of cdclk with IPS on BDW */
10245         if (IS_BROADWELL(dev_priv) && crtc_state->ips_enabled)
10246                 pixel_rate = DIV_ROUND_UP(pixel_rate * 100, 95);
10247
10248         /* BSpec says "Do not use DisplayPort with CDCLK less than
10249          * 432 MHz, audio enabled, port width x4, and link rate
10250          * HBR2 (5.4 GHz), or else there may be audio corruption or
10251          * screen corruption."
10252          */
10253         if (intel_crtc_has_dp_encoder(crtc_state) &&
10254             crtc_state->has_audio &&
10255             crtc_state->port_clock >= 540000 &&
10256             crtc_state->lane_count == 4)
10257                 pixel_rate = max(432000, pixel_rate);
10258
10259         return pixel_rate;
10260 }
10261
10262 /* compute the max rate for new configuration */
10263 static int ilk_max_pixel_rate(struct drm_atomic_state *state)
10264 {
10265         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
10266         struct drm_i915_private *dev_priv = to_i915(state->dev);
10267         struct drm_crtc *crtc;
10268         struct drm_crtc_state *cstate;
10269         struct intel_crtc_state *crtc_state;
10270         unsigned max_pixel_rate = 0, i;
10271         enum pipe pipe;
10272
10273         memcpy(intel_state->min_pixclk, dev_priv->min_pixclk,
10274                sizeof(intel_state->min_pixclk));
10275
10276         for_each_crtc_in_state(state, crtc, cstate, i) {
10277                 int pixel_rate;
10278
10279                 crtc_state = to_intel_crtc_state(cstate);
10280                 if (!crtc_state->base.enable) {
10281                         intel_state->min_pixclk[i] = 0;
10282                         continue;
10283                 }
10284
10285                 pixel_rate = ilk_pipe_pixel_rate(crtc_state);
10286
10287                 if (IS_BROADWELL(dev_priv) || IS_GEN9(dev_priv))
10288                         pixel_rate = bdw_adjust_min_pipe_pixel_rate(crtc_state,
10289                                                                     pixel_rate);
10290
10291                 intel_state->min_pixclk[i] = pixel_rate;
10292         }
10293
10294         for_each_pipe(dev_priv, pipe)
10295                 max_pixel_rate = max(intel_state->min_pixclk[pipe], max_pixel_rate);
10296
10297         return max_pixel_rate;
10298 }
10299
10300 static void broadwell_set_cdclk(struct drm_device *dev, int cdclk)
10301 {
10302         struct drm_i915_private *dev_priv = to_i915(dev);
10303         uint32_t val, data;
10304         int ret;
10305
10306         if (WARN((I915_READ(LCPLL_CTL) &
10307                   (LCPLL_PLL_DISABLE | LCPLL_PLL_LOCK |
10308                    LCPLL_CD_CLOCK_DISABLE | LCPLL_ROOT_CD_CLOCK_DISABLE |
10309                    LCPLL_CD2X_CLOCK_DISABLE | LCPLL_POWER_DOWN_ALLOW |
10310                    LCPLL_CD_SOURCE_FCLK)) != LCPLL_PLL_LOCK,
10311                  "trying to change cdclk frequency with cdclk not enabled\n"))
10312                 return;
10313
10314         mutex_lock(&dev_priv->rps.hw_lock);
10315         ret = sandybridge_pcode_write(dev_priv,
10316                                       BDW_PCODE_DISPLAY_FREQ_CHANGE_REQ, 0x0);
10317         mutex_unlock(&dev_priv->rps.hw_lock);
10318         if (ret) {
10319                 DRM_ERROR("failed to inform pcode about cdclk change\n");
10320                 return;
10321         }
10322
10323         val = I915_READ(LCPLL_CTL);
10324         val |= LCPLL_CD_SOURCE_FCLK;
10325         I915_WRITE(LCPLL_CTL, val);
10326
10327         if (wait_for_us(I915_READ(LCPLL_CTL) &
10328                         LCPLL_CD_SOURCE_FCLK_DONE, 1))
10329                 DRM_ERROR("Switching to FCLK failed\n");
10330
10331         val = I915_READ(LCPLL_CTL);
10332         val &= ~LCPLL_CLK_FREQ_MASK;
10333
10334         switch (cdclk) {
10335         case 450000:
10336                 val |= LCPLL_CLK_FREQ_450;
10337                 data = 0;
10338                 break;
10339         case 540000:
10340                 val |= LCPLL_CLK_FREQ_54O_BDW;
10341                 data = 1;
10342                 break;
10343         case 337500:
10344                 val |= LCPLL_CLK_FREQ_337_5_BDW;
10345                 data = 2;
10346                 break;
10347         case 675000:
10348                 val |= LCPLL_CLK_FREQ_675_BDW;
10349                 data = 3;
10350                 break;
10351         default:
10352                 WARN(1, "invalid cdclk frequency\n");
10353                 return;
10354         }
10355
10356         I915_WRITE(LCPLL_CTL, val);
10357
10358         val = I915_READ(LCPLL_CTL);
10359         val &= ~LCPLL_CD_SOURCE_FCLK;
10360         I915_WRITE(LCPLL_CTL, val);
10361
10362         if (wait_for_us((I915_READ(LCPLL_CTL) &
10363                         LCPLL_CD_SOURCE_FCLK_DONE) == 0, 1))
10364                 DRM_ERROR("Switching back to LCPLL failed\n");
10365
10366         mutex_lock(&dev_priv->rps.hw_lock);
10367         sandybridge_pcode_write(dev_priv, HSW_PCODE_DE_WRITE_FREQ_REQ, data);
10368         mutex_unlock(&dev_priv->rps.hw_lock);
10369
10370         I915_WRITE(CDCLK_FREQ, DIV_ROUND_CLOSEST(cdclk, 1000) - 1);
10371
10372         intel_update_cdclk(dev);
10373
10374         WARN(cdclk != dev_priv->cdclk_freq,
10375              "cdclk requested %d kHz but got %d kHz\n",
10376              cdclk, dev_priv->cdclk_freq);
10377 }
10378
10379 static int broadwell_calc_cdclk(int max_pixclk)
10380 {
10381         if (max_pixclk > 540000)
10382                 return 675000;
10383         else if (max_pixclk > 450000)
10384                 return 540000;
10385         else if (max_pixclk > 337500)
10386                 return 450000;
10387         else
10388                 return 337500;
10389 }
10390
10391 static int broadwell_modeset_calc_cdclk(struct drm_atomic_state *state)
10392 {
10393         struct drm_i915_private *dev_priv = to_i915(state->dev);
10394         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
10395         int max_pixclk = ilk_max_pixel_rate(state);
10396         int cdclk;
10397
10398         /*
10399          * FIXME should also account for plane ratio
10400          * once 64bpp pixel formats are supported.
10401          */
10402         cdclk = broadwell_calc_cdclk(max_pixclk);
10403
10404         if (cdclk > dev_priv->max_cdclk_freq) {
10405                 DRM_DEBUG_KMS("requested cdclk (%d kHz) exceeds max (%d kHz)\n",
10406                               cdclk, dev_priv->max_cdclk_freq);
10407                 return -EINVAL;
10408         }
10409
10410         intel_state->cdclk = intel_state->dev_cdclk = cdclk;
10411         if (!intel_state->active_crtcs)
10412                 intel_state->dev_cdclk = broadwell_calc_cdclk(0);
10413
10414         return 0;
10415 }
10416
10417 static void broadwell_modeset_commit_cdclk(struct drm_atomic_state *old_state)
10418 {
10419         struct drm_device *dev = old_state->dev;
10420         struct intel_atomic_state *old_intel_state =
10421                 to_intel_atomic_state(old_state);
10422         unsigned req_cdclk = old_intel_state->dev_cdclk;
10423
10424         broadwell_set_cdclk(dev, req_cdclk);
10425 }
10426
10427 static int skl_modeset_calc_cdclk(struct drm_atomic_state *state)
10428 {
10429         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
10430         struct drm_i915_private *dev_priv = to_i915(state->dev);
10431         const int max_pixclk = ilk_max_pixel_rate(state);
10432         int vco = intel_state->cdclk_pll_vco;
10433         int cdclk;
10434
10435         /*
10436          * FIXME should also account for plane ratio
10437          * once 64bpp pixel formats are supported.
10438          */
10439         cdclk = skl_calc_cdclk(max_pixclk, vco);
10440
10441         /*
10442          * FIXME move the cdclk caclulation to
10443          * compute_config() so we can fail gracegully.
10444          */
10445         if (cdclk > dev_priv->max_cdclk_freq) {
10446                 DRM_ERROR("requested cdclk (%d kHz) exceeds max (%d kHz)\n",
10447                           cdclk, dev_priv->max_cdclk_freq);
10448                 cdclk = dev_priv->max_cdclk_freq;
10449         }
10450
10451         intel_state->cdclk = intel_state->dev_cdclk = cdclk;
10452         if (!intel_state->active_crtcs)
10453                 intel_state->dev_cdclk = skl_calc_cdclk(0, vco);
10454
10455         return 0;
10456 }
10457
10458 static void skl_modeset_commit_cdclk(struct drm_atomic_state *old_state)
10459 {
10460         struct drm_i915_private *dev_priv = to_i915(old_state->dev);
10461         struct intel_atomic_state *intel_state = to_intel_atomic_state(old_state);
10462         unsigned int req_cdclk = intel_state->dev_cdclk;
10463         unsigned int req_vco = intel_state->cdclk_pll_vco;
10464
10465         skl_set_cdclk(dev_priv, req_cdclk, req_vco);
10466 }
10467
10468 static int haswell_crtc_compute_clock(struct intel_crtc *crtc,
10469                                       struct intel_crtc_state *crtc_state)
10470 {
10471         if (!intel_crtc_has_type(crtc_state, INTEL_OUTPUT_DSI)) {
10472                 if (!intel_ddi_pll_select(crtc, crtc_state))
10473                         return -EINVAL;
10474         }
10475
10476         crtc->lowfreq_avail = false;
10477
10478         return 0;
10479 }
10480
10481 static void bxt_get_ddi_pll(struct drm_i915_private *dev_priv,
10482                                 enum port port,
10483                                 struct intel_crtc_state *pipe_config)
10484 {
10485         enum intel_dpll_id id;
10486
10487         switch (port) {
10488         case PORT_A:
10489                 id = DPLL_ID_SKL_DPLL0;
10490                 break;
10491         case PORT_B:
10492                 id = DPLL_ID_SKL_DPLL1;
10493                 break;
10494         case PORT_C:
10495                 id = DPLL_ID_SKL_DPLL2;
10496                 break;
10497         default:
10498                 DRM_ERROR("Incorrect port type\n");
10499                 return;
10500         }
10501
10502         pipe_config->shared_dpll = intel_get_shared_dpll_by_id(dev_priv, id);
10503 }
10504
10505 static void skylake_get_ddi_pll(struct drm_i915_private *dev_priv,
10506                                 enum port port,
10507                                 struct intel_crtc_state *pipe_config)
10508 {
10509         enum intel_dpll_id id;
10510         u32 temp;
10511
10512         temp = I915_READ(DPLL_CTRL2) & DPLL_CTRL2_DDI_CLK_SEL_MASK(port);
10513         id = temp >> (port * 3 + 1);
10514
10515         if (WARN_ON(id < SKL_DPLL0 || id > SKL_DPLL3))
10516                 return;
10517
10518         pipe_config->shared_dpll = intel_get_shared_dpll_by_id(dev_priv, id);
10519 }
10520
10521 static void haswell_get_ddi_pll(struct drm_i915_private *dev_priv,
10522                                 enum port port,
10523                                 struct intel_crtc_state *pipe_config)
10524 {
10525         enum intel_dpll_id id;
10526         uint32_t ddi_pll_sel = I915_READ(PORT_CLK_SEL(port));
10527
10528         switch (ddi_pll_sel) {
10529         case PORT_CLK_SEL_WRPLL1:
10530                 id = DPLL_ID_WRPLL1;
10531                 break;
10532         case PORT_CLK_SEL_WRPLL2:
10533                 id = DPLL_ID_WRPLL2;
10534                 break;
10535         case PORT_CLK_SEL_SPLL:
10536                 id = DPLL_ID_SPLL;
10537                 break;
10538         case PORT_CLK_SEL_LCPLL_810:
10539                 id = DPLL_ID_LCPLL_810;
10540                 break;
10541         case PORT_CLK_SEL_LCPLL_1350:
10542                 id = DPLL_ID_LCPLL_1350;
10543                 break;
10544         case PORT_CLK_SEL_LCPLL_2700:
10545                 id = DPLL_ID_LCPLL_2700;
10546                 break;
10547         default:
10548                 MISSING_CASE(ddi_pll_sel);
10549                 /* fall through */
10550         case PORT_CLK_SEL_NONE:
10551                 return;
10552         }
10553
10554         pipe_config->shared_dpll = intel_get_shared_dpll_by_id(dev_priv, id);
10555 }
10556
10557 static bool hsw_get_transcoder_state(struct intel_crtc *crtc,
10558                                      struct intel_crtc_state *pipe_config,
10559                                      unsigned long *power_domain_mask)
10560 {
10561         struct drm_device *dev = crtc->base.dev;
10562         struct drm_i915_private *dev_priv = to_i915(dev);
10563         enum intel_display_power_domain power_domain;
10564         u32 tmp;
10565
10566         /*
10567          * The pipe->transcoder mapping is fixed with the exception of the eDP
10568          * transcoder handled below.
10569          */
10570         pipe_config->cpu_transcoder = (enum transcoder) crtc->pipe;
10571
10572         /*
10573          * XXX: Do intel_display_power_get_if_enabled before reading this (for
10574          * consistency and less surprising code; it's in always on power).
10575          */
10576         tmp = I915_READ(TRANS_DDI_FUNC_CTL(TRANSCODER_EDP));
10577         if (tmp & TRANS_DDI_FUNC_ENABLE) {
10578                 enum pipe trans_edp_pipe;
10579                 switch (tmp & TRANS_DDI_EDP_INPUT_MASK) {
10580                 default:
10581                         WARN(1, "unknown pipe linked to edp transcoder\n");
10582                 case TRANS_DDI_EDP_INPUT_A_ONOFF:
10583                 case TRANS_DDI_EDP_INPUT_A_ON:
10584                         trans_edp_pipe = PIPE_A;
10585                         break;
10586                 case TRANS_DDI_EDP_INPUT_B_ONOFF:
10587                         trans_edp_pipe = PIPE_B;
10588                         break;
10589                 case TRANS_DDI_EDP_INPUT_C_ONOFF:
10590                         trans_edp_pipe = PIPE_C;
10591                         break;
10592                 }
10593
10594                 if (trans_edp_pipe == crtc->pipe)
10595                         pipe_config->cpu_transcoder = TRANSCODER_EDP;
10596         }
10597
10598         power_domain = POWER_DOMAIN_TRANSCODER(pipe_config->cpu_transcoder);
10599         if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
10600                 return false;
10601         *power_domain_mask |= BIT(power_domain);
10602
10603         tmp = I915_READ(PIPECONF(pipe_config->cpu_transcoder));
10604
10605         return tmp & PIPECONF_ENABLE;
10606 }
10607
10608 static bool bxt_get_dsi_transcoder_state(struct intel_crtc *crtc,
10609                                          struct intel_crtc_state *pipe_config,
10610                                          unsigned long *power_domain_mask)
10611 {
10612         struct drm_device *dev = crtc->base.dev;
10613         struct drm_i915_private *dev_priv = to_i915(dev);
10614         enum intel_display_power_domain power_domain;
10615         enum port port;
10616         enum transcoder cpu_transcoder;
10617         u32 tmp;
10618
10619         for_each_port_masked(port, BIT(PORT_A) | BIT(PORT_C)) {
10620                 if (port == PORT_A)
10621                         cpu_transcoder = TRANSCODER_DSI_A;
10622                 else
10623                         cpu_transcoder = TRANSCODER_DSI_C;
10624
10625                 power_domain = POWER_DOMAIN_TRANSCODER(cpu_transcoder);
10626                 if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
10627                         continue;
10628                 *power_domain_mask |= BIT(power_domain);
10629
10630                 /*
10631                  * The PLL needs to be enabled with a valid divider
10632                  * configuration, otherwise accessing DSI registers will hang
10633                  * the machine. See BSpec North Display Engine
10634                  * registers/MIPI[BXT]. We can break out here early, since we
10635                  * need the same DSI PLL to be enabled for both DSI ports.
10636                  */
10637                 if (!intel_dsi_pll_is_enabled(dev_priv))
10638                         break;
10639
10640                 /* XXX: this works for video mode only */
10641                 tmp = I915_READ(BXT_MIPI_PORT_CTRL(port));
10642                 if (!(tmp & DPI_ENABLE))
10643                         continue;
10644
10645                 tmp = I915_READ(MIPI_CTRL(port));
10646                 if ((tmp & BXT_PIPE_SELECT_MASK) != BXT_PIPE_SELECT(crtc->pipe))
10647                         continue;
10648
10649                 pipe_config->cpu_transcoder = cpu_transcoder;
10650                 break;
10651         }
10652
10653         return transcoder_is_dsi(pipe_config->cpu_transcoder);
10654 }
10655
10656 static void haswell_get_ddi_port_state(struct intel_crtc *crtc,
10657                                        struct intel_crtc_state *pipe_config)
10658 {
10659         struct drm_device *dev = crtc->base.dev;
10660         struct drm_i915_private *dev_priv = to_i915(dev);
10661         struct intel_shared_dpll *pll;
10662         enum port port;
10663         uint32_t tmp;
10664
10665         tmp = I915_READ(TRANS_DDI_FUNC_CTL(pipe_config->cpu_transcoder));
10666
10667         port = (tmp & TRANS_DDI_PORT_MASK) >> TRANS_DDI_PORT_SHIFT;
10668
10669         if (IS_SKYLAKE(dev) || IS_KABYLAKE(dev))
10670                 skylake_get_ddi_pll(dev_priv, port, pipe_config);
10671         else if (IS_BROXTON(dev))
10672                 bxt_get_ddi_pll(dev_priv, port, pipe_config);
10673         else
10674                 haswell_get_ddi_pll(dev_priv, port, pipe_config);
10675
10676         pll = pipe_config->shared_dpll;
10677         if (pll) {
10678                 WARN_ON(!pll->funcs.get_hw_state(dev_priv, pll,
10679                                                  &pipe_config->dpll_hw_state));
10680         }
10681
10682         /*
10683          * Haswell has only FDI/PCH transcoder A. It is which is connected to
10684          * DDI E. So just check whether this pipe is wired to DDI E and whether
10685          * the PCH transcoder is on.
10686          */
10687         if (INTEL_INFO(dev)->gen < 9 &&
10688             (port == PORT_E) && I915_READ(LPT_TRANSCONF) & TRANS_ENABLE) {
10689                 pipe_config->has_pch_encoder = true;
10690
10691                 tmp = I915_READ(FDI_RX_CTL(PIPE_A));
10692                 pipe_config->fdi_lanes = ((FDI_DP_PORT_WIDTH_MASK & tmp) >>
10693                                           FDI_DP_PORT_WIDTH_SHIFT) + 1;
10694
10695                 ironlake_get_fdi_m_n_config(crtc, pipe_config);
10696         }
10697 }
10698
10699 static bool haswell_get_pipe_config(struct intel_crtc *crtc,
10700                                     struct intel_crtc_state *pipe_config)
10701 {
10702         struct drm_device *dev = crtc->base.dev;
10703         struct drm_i915_private *dev_priv = to_i915(dev);
10704         enum intel_display_power_domain power_domain;
10705         unsigned long power_domain_mask;
10706         bool active;
10707
10708         power_domain = POWER_DOMAIN_PIPE(crtc->pipe);
10709         if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
10710                 return false;
10711         power_domain_mask = BIT(power_domain);
10712
10713         pipe_config->shared_dpll = NULL;
10714
10715         active = hsw_get_transcoder_state(crtc, pipe_config, &power_domain_mask);
10716
10717         if (IS_BROXTON(dev_priv) &&
10718             bxt_get_dsi_transcoder_state(crtc, pipe_config, &power_domain_mask)) {
10719                 WARN_ON(active);
10720                 active = true;
10721         }
10722
10723         if (!active)
10724                 goto out;
10725
10726         if (!transcoder_is_dsi(pipe_config->cpu_transcoder)) {
10727                 haswell_get_ddi_port_state(crtc, pipe_config);
10728                 intel_get_pipe_timings(crtc, pipe_config);
10729         }
10730
10731         intel_get_pipe_src_size(crtc, pipe_config);
10732
10733         pipe_config->gamma_mode =
10734                 I915_READ(GAMMA_MODE(crtc->pipe)) & GAMMA_MODE_MODE_MASK;
10735
10736         if (INTEL_INFO(dev)->gen >= 9) {
10737                 skl_init_scalers(dev, crtc, pipe_config);
10738         }
10739
10740         if (INTEL_INFO(dev)->gen >= 9) {
10741                 pipe_config->scaler_state.scaler_id = -1;
10742                 pipe_config->scaler_state.scaler_users &= ~(1 << SKL_CRTC_INDEX);
10743         }
10744
10745         power_domain = POWER_DOMAIN_PIPE_PANEL_FITTER(crtc->pipe);
10746         if (intel_display_power_get_if_enabled(dev_priv, power_domain)) {
10747                 power_domain_mask |= BIT(power_domain);
10748                 if (INTEL_INFO(dev)->gen >= 9)
10749                         skylake_get_pfit_config(crtc, pipe_config);
10750                 else
10751                         ironlake_get_pfit_config(crtc, pipe_config);
10752         }
10753
10754         if (IS_HASWELL(dev))
10755                 pipe_config->ips_enabled = hsw_crtc_supports_ips(crtc) &&
10756                         (I915_READ(IPS_CTL) & IPS_ENABLE);
10757
10758         if (pipe_config->cpu_transcoder != TRANSCODER_EDP &&
10759             !transcoder_is_dsi(pipe_config->cpu_transcoder)) {
10760                 pipe_config->pixel_multiplier =
10761                         I915_READ(PIPE_MULT(pipe_config->cpu_transcoder)) + 1;
10762         } else {
10763                 pipe_config->pixel_multiplier = 1;
10764         }
10765
10766 out:
10767         for_each_power_domain(power_domain, power_domain_mask)
10768                 intel_display_power_put(dev_priv, power_domain);
10769
10770         return active;
10771 }
10772
10773 static void i845_update_cursor(struct drm_crtc *crtc, u32 base,
10774                                const struct intel_plane_state *plane_state)
10775 {
10776         struct drm_device *dev = crtc->dev;
10777         struct drm_i915_private *dev_priv = to_i915(dev);
10778         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10779         uint32_t cntl = 0, size = 0;
10780
10781         if (plane_state && plane_state->base.visible) {
10782                 unsigned int width = plane_state->base.crtc_w;
10783                 unsigned int height = plane_state->base.crtc_h;
10784                 unsigned int stride = roundup_pow_of_two(width) * 4;
10785
10786                 switch (stride) {
10787                 default:
10788                         WARN_ONCE(1, "Invalid cursor width/stride, width=%u, stride=%u\n",
10789                                   width, stride);
10790                         stride = 256;
10791                         /* fallthrough */
10792                 case 256:
10793                 case 512:
10794                 case 1024:
10795                 case 2048:
10796                         break;
10797                 }
10798
10799                 cntl |= CURSOR_ENABLE |
10800                         CURSOR_GAMMA_ENABLE |
10801                         CURSOR_FORMAT_ARGB |
10802                         CURSOR_STRIDE(stride);
10803
10804                 size = (height << 12) | width;
10805         }
10806
10807         if (intel_crtc->cursor_cntl != 0 &&
10808             (intel_crtc->cursor_base != base ||
10809              intel_crtc->cursor_size != size ||
10810              intel_crtc->cursor_cntl != cntl)) {
10811                 /* On these chipsets we can only modify the base/size/stride
10812                  * whilst the cursor is disabled.
10813                  */
10814                 I915_WRITE(CURCNTR(PIPE_A), 0);
10815                 POSTING_READ(CURCNTR(PIPE_A));
10816                 intel_crtc->cursor_cntl = 0;
10817         }
10818
10819         if (intel_crtc->cursor_base != base) {
10820                 I915_WRITE(CURBASE(PIPE_A), base);
10821                 intel_crtc->cursor_base = base;
10822         }
10823
10824         if (intel_crtc->cursor_size != size) {
10825                 I915_WRITE(CURSIZE, size);
10826                 intel_crtc->cursor_size = size;
10827         }
10828
10829         if (intel_crtc->cursor_cntl != cntl) {
10830                 I915_WRITE(CURCNTR(PIPE_A), cntl);
10831                 POSTING_READ(CURCNTR(PIPE_A));
10832                 intel_crtc->cursor_cntl = cntl;
10833         }
10834 }
10835
10836 static void i9xx_update_cursor(struct drm_crtc *crtc, u32 base,
10837                                const struct intel_plane_state *plane_state)
10838 {
10839         struct drm_device *dev = crtc->dev;
10840         struct drm_i915_private *dev_priv = to_i915(dev);
10841         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10842         const struct skl_wm_values *wm = &dev_priv->wm.skl_results;
10843         int pipe = intel_crtc->pipe;
10844         uint32_t cntl = 0;
10845
10846         if (INTEL_GEN(dev_priv) >= 9 && wm->dirty_pipes & drm_crtc_mask(crtc))
10847                 skl_write_cursor_wm(intel_crtc, wm);
10848
10849         if (plane_state && plane_state->base.visible) {
10850                 cntl = MCURSOR_GAMMA_ENABLE;
10851                 switch (plane_state->base.crtc_w) {
10852                         case 64:
10853                                 cntl |= CURSOR_MODE_64_ARGB_AX;
10854                                 break;
10855                         case 128:
10856                                 cntl |= CURSOR_MODE_128_ARGB_AX;
10857                                 break;
10858                         case 256:
10859                                 cntl |= CURSOR_MODE_256_ARGB_AX;
10860                                 break;
10861                         default:
10862                                 MISSING_CASE(plane_state->base.crtc_w);
10863                                 return;
10864                 }
10865                 cntl |= pipe << 28; /* Connect to correct pipe */
10866
10867                 if (HAS_DDI(dev))
10868                         cntl |= CURSOR_PIPE_CSC_ENABLE;
10869
10870                 if (plane_state->base.rotation == DRM_ROTATE_180)
10871                         cntl |= CURSOR_ROTATE_180;
10872         }
10873
10874         if (intel_crtc->cursor_cntl != cntl) {
10875                 I915_WRITE(CURCNTR(pipe), cntl);
10876                 POSTING_READ(CURCNTR(pipe));
10877                 intel_crtc->cursor_cntl = cntl;
10878         }
10879
10880         /* and commit changes on next vblank */
10881         I915_WRITE(CURBASE(pipe), base);
10882         POSTING_READ(CURBASE(pipe));
10883
10884         intel_crtc->cursor_base = base;
10885 }
10886
10887 /* If no-part of the cursor is visible on the framebuffer, then the GPU may hang... */
10888 static void intel_crtc_update_cursor(struct drm_crtc *crtc,
10889                                      const struct intel_plane_state *plane_state)
10890 {
10891         struct drm_device *dev = crtc->dev;
10892         struct drm_i915_private *dev_priv = to_i915(dev);
10893         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10894         int pipe = intel_crtc->pipe;
10895         u32 base = intel_crtc->cursor_addr;
10896         u32 pos = 0;
10897
10898         if (plane_state) {
10899                 int x = plane_state->base.crtc_x;
10900                 int y = plane_state->base.crtc_y;
10901
10902                 if (x < 0) {
10903                         pos |= CURSOR_POS_SIGN << CURSOR_X_SHIFT;
10904                         x = -x;
10905                 }
10906                 pos |= x << CURSOR_X_SHIFT;
10907
10908                 if (y < 0) {
10909                         pos |= CURSOR_POS_SIGN << CURSOR_Y_SHIFT;
10910                         y = -y;
10911                 }
10912                 pos |= y << CURSOR_Y_SHIFT;
10913
10914                 /* ILK+ do this automagically */
10915                 if (HAS_GMCH_DISPLAY(dev) &&
10916                     plane_state->base.rotation == DRM_ROTATE_180) {
10917                         base += (plane_state->base.crtc_h *
10918                                  plane_state->base.crtc_w - 1) * 4;
10919                 }
10920         }
10921
10922         I915_WRITE(CURPOS(pipe), pos);
10923
10924         if (IS_845G(dev) || IS_I865G(dev))
10925                 i845_update_cursor(crtc, base, plane_state);
10926         else
10927                 i9xx_update_cursor(crtc, base, plane_state);
10928 }
10929
10930 static bool cursor_size_ok(struct drm_device *dev,
10931                            uint32_t width, uint32_t height)
10932 {
10933         if (width == 0 || height == 0)
10934                 return false;
10935
10936         /*
10937          * 845g/865g are special in that they are only limited by
10938          * the width of their cursors, the height is arbitrary up to
10939          * the precision of the register. Everything else requires
10940          * square cursors, limited to a few power-of-two sizes.
10941          */
10942         if (IS_845G(dev) || IS_I865G(dev)) {
10943                 if ((width & 63) != 0)
10944                         return false;
10945
10946                 if (width > (IS_845G(dev) ? 64 : 512))
10947                         return false;
10948
10949                 if (height > 1023)
10950                         return false;
10951         } else {
10952                 switch (width | height) {
10953                 case 256:
10954                 case 128:
10955                         if (IS_GEN2(dev))
10956                                 return false;
10957                 case 64:
10958                         break;
10959                 default:
10960                         return false;
10961                 }
10962         }
10963
10964         return true;
10965 }
10966
10967 /* VESA 640x480x72Hz mode to set on the pipe */
10968 static struct drm_display_mode load_detect_mode = {
10969         DRM_MODE("640x480", DRM_MODE_TYPE_DEFAULT, 31500, 640, 664,
10970                  704, 832, 0, 480, 489, 491, 520, 0, DRM_MODE_FLAG_NHSYNC | DRM_MODE_FLAG_NVSYNC),
10971 };
10972
10973 struct drm_framebuffer *
10974 __intel_framebuffer_create(struct drm_device *dev,
10975                            struct drm_mode_fb_cmd2 *mode_cmd,
10976                            struct drm_i915_gem_object *obj)
10977 {
10978         struct intel_framebuffer *intel_fb;
10979         int ret;
10980
10981         intel_fb = kzalloc(sizeof(*intel_fb), GFP_KERNEL);
10982         if (!intel_fb)
10983                 return ERR_PTR(-ENOMEM);
10984
10985         ret = intel_framebuffer_init(dev, intel_fb, mode_cmd, obj);
10986         if (ret)
10987                 goto err;
10988
10989         return &intel_fb->base;
10990
10991 err:
10992         kfree(intel_fb);
10993         return ERR_PTR(ret);
10994 }
10995
10996 static struct drm_framebuffer *
10997 intel_framebuffer_create(struct drm_device *dev,
10998                          struct drm_mode_fb_cmd2 *mode_cmd,
10999                          struct drm_i915_gem_object *obj)
11000 {
11001         struct drm_framebuffer *fb;
11002         int ret;
11003
11004         ret = i915_mutex_lock_interruptible(dev);
11005         if (ret)
11006                 return ERR_PTR(ret);
11007         fb = __intel_framebuffer_create(dev, mode_cmd, obj);
11008         mutex_unlock(&dev->struct_mutex);
11009
11010         return fb;
11011 }
11012
11013 static u32
11014 intel_framebuffer_pitch_for_width(int width, int bpp)
11015 {
11016         u32 pitch = DIV_ROUND_UP(width * bpp, 8);
11017         return ALIGN(pitch, 64);
11018 }
11019
11020 static u32
11021 intel_framebuffer_size_for_mode(struct drm_display_mode *mode, int bpp)
11022 {
11023         u32 pitch = intel_framebuffer_pitch_for_width(mode->hdisplay, bpp);
11024         return PAGE_ALIGN(pitch * mode->vdisplay);
11025 }
11026
11027 static struct drm_framebuffer *
11028 intel_framebuffer_create_for_mode(struct drm_device *dev,
11029                                   struct drm_display_mode *mode,
11030                                   int depth, int bpp)
11031 {
11032         struct drm_framebuffer *fb;
11033         struct drm_i915_gem_object *obj;
11034         struct drm_mode_fb_cmd2 mode_cmd = { 0 };
11035
11036         obj = i915_gem_object_create(dev,
11037                                     intel_framebuffer_size_for_mode(mode, bpp));
11038         if (IS_ERR(obj))
11039                 return ERR_CAST(obj);
11040
11041         mode_cmd.width = mode->hdisplay;
11042         mode_cmd.height = mode->vdisplay;
11043         mode_cmd.pitches[0] = intel_framebuffer_pitch_for_width(mode_cmd.width,
11044                                                                 bpp);
11045         mode_cmd.pixel_format = drm_mode_legacy_fb_format(bpp, depth);
11046
11047         fb = intel_framebuffer_create(dev, &mode_cmd, obj);
11048         if (IS_ERR(fb))
11049                 i915_gem_object_put_unlocked(obj);
11050
11051         return fb;
11052 }
11053
11054 static struct drm_framebuffer *
11055 mode_fits_in_fbdev(struct drm_device *dev,
11056                    struct drm_display_mode *mode)
11057 {
11058 #ifdef CONFIG_DRM_FBDEV_EMULATION
11059         struct drm_i915_private *dev_priv = to_i915(dev);
11060         struct drm_i915_gem_object *obj;
11061         struct drm_framebuffer *fb;
11062
11063         if (!dev_priv->fbdev)
11064                 return NULL;
11065
11066         if (!dev_priv->fbdev->fb)
11067                 return NULL;
11068
11069         obj = dev_priv->fbdev->fb->obj;
11070         BUG_ON(!obj);
11071
11072         fb = &dev_priv->fbdev->fb->base;
11073         if (fb->pitches[0] < intel_framebuffer_pitch_for_width(mode->hdisplay,
11074                                                                fb->bits_per_pixel))
11075                 return NULL;
11076
11077         if (obj->base.size < mode->vdisplay * fb->pitches[0])
11078                 return NULL;
11079
11080         drm_framebuffer_reference(fb);
11081         return fb;
11082 #else
11083         return NULL;
11084 #endif
11085 }
11086
11087 static int intel_modeset_setup_plane_state(struct drm_atomic_state *state,
11088                                            struct drm_crtc *crtc,
11089                                            struct drm_display_mode *mode,
11090                                            struct drm_framebuffer *fb,
11091                                            int x, int y)
11092 {
11093         struct drm_plane_state *plane_state;
11094         int hdisplay, vdisplay;
11095         int ret;
11096
11097         plane_state = drm_atomic_get_plane_state(state, crtc->primary);
11098         if (IS_ERR(plane_state))
11099                 return PTR_ERR(plane_state);
11100
11101         if (mode)
11102                 drm_crtc_get_hv_timing(mode, &hdisplay, &vdisplay);
11103         else
11104                 hdisplay = vdisplay = 0;
11105
11106         ret = drm_atomic_set_crtc_for_plane(plane_state, fb ? crtc : NULL);
11107         if (ret)
11108                 return ret;
11109         drm_atomic_set_fb_for_plane(plane_state, fb);
11110         plane_state->crtc_x = 0;
11111         plane_state->crtc_y = 0;
11112         plane_state->crtc_w = hdisplay;
11113         plane_state->crtc_h = vdisplay;
11114         plane_state->src_x = x << 16;
11115         plane_state->src_y = y << 16;
11116         plane_state->src_w = hdisplay << 16;
11117         plane_state->src_h = vdisplay << 16;
11118
11119         return 0;
11120 }
11121
11122 bool intel_get_load_detect_pipe(struct drm_connector *connector,
11123                                 struct drm_display_mode *mode,
11124                                 struct intel_load_detect_pipe *old,
11125                                 struct drm_modeset_acquire_ctx *ctx)
11126 {
11127         struct intel_crtc *intel_crtc;
11128         struct intel_encoder *intel_encoder =
11129                 intel_attached_encoder(connector);
11130         struct drm_crtc *possible_crtc;
11131         struct drm_encoder *encoder = &intel_encoder->base;
11132         struct drm_crtc *crtc = NULL;
11133         struct drm_device *dev = encoder->dev;
11134         struct drm_framebuffer *fb;
11135         struct drm_mode_config *config = &dev->mode_config;
11136         struct drm_atomic_state *state = NULL, *restore_state = NULL;
11137         struct drm_connector_state *connector_state;
11138         struct intel_crtc_state *crtc_state;
11139         int ret, i = -1;
11140
11141         DRM_DEBUG_KMS("[CONNECTOR:%d:%s], [ENCODER:%d:%s]\n",
11142                       connector->base.id, connector->name,
11143                       encoder->base.id, encoder->name);
11144
11145         old->restore_state = NULL;
11146
11147 retry:
11148         ret = drm_modeset_lock(&config->connection_mutex, ctx);
11149         if (ret)
11150                 goto fail;
11151
11152         /*
11153          * Algorithm gets a little messy:
11154          *
11155          *   - if the connector already has an assigned crtc, use it (but make
11156          *     sure it's on first)
11157          *
11158          *   - try to find the first unused crtc that can drive this connector,
11159          *     and use that if we find one
11160          */
11161
11162         /* See if we already have a CRTC for this connector */
11163         if (connector->state->crtc) {
11164                 crtc = connector->state->crtc;
11165
11166                 ret = drm_modeset_lock(&crtc->mutex, ctx);
11167                 if (ret)
11168                         goto fail;
11169
11170                 /* Make sure the crtc and connector are running */
11171                 goto found;
11172         }
11173
11174         /* Find an unused one (if possible) */
11175         for_each_crtc(dev, possible_crtc) {
11176                 i++;
11177                 if (!(encoder->possible_crtcs & (1 << i)))
11178                         continue;
11179
11180                 ret = drm_modeset_lock(&possible_crtc->mutex, ctx);
11181                 if (ret)
11182                         goto fail;
11183
11184                 if (possible_crtc->state->enable) {
11185                         drm_modeset_unlock(&possible_crtc->mutex);
11186                         continue;
11187                 }
11188
11189                 crtc = possible_crtc;
11190                 break;
11191         }
11192
11193         /*
11194          * If we didn't find an unused CRTC, don't use any.
11195          */
11196         if (!crtc) {
11197                 DRM_DEBUG_KMS("no pipe available for load-detect\n");
11198                 goto fail;
11199         }
11200
11201 found:
11202         intel_crtc = to_intel_crtc(crtc);
11203
11204         ret = drm_modeset_lock(&crtc->primary->mutex, ctx);
11205         if (ret)
11206                 goto fail;
11207
11208         state = drm_atomic_state_alloc(dev);
11209         restore_state = drm_atomic_state_alloc(dev);
11210         if (!state || !restore_state) {
11211                 ret = -ENOMEM;
11212                 goto fail;
11213         }
11214
11215         state->acquire_ctx = ctx;
11216         restore_state->acquire_ctx = ctx;
11217
11218         connector_state = drm_atomic_get_connector_state(state, connector);
11219         if (IS_ERR(connector_state)) {
11220                 ret = PTR_ERR(connector_state);
11221                 goto fail;
11222         }
11223
11224         ret = drm_atomic_set_crtc_for_connector(connector_state, crtc);
11225         if (ret)
11226                 goto fail;
11227
11228         crtc_state = intel_atomic_get_crtc_state(state, intel_crtc);
11229         if (IS_ERR(crtc_state)) {
11230                 ret = PTR_ERR(crtc_state);
11231                 goto fail;
11232         }
11233
11234         crtc_state->base.active = crtc_state->base.enable = true;
11235
11236         if (!mode)
11237                 mode = &load_detect_mode;
11238
11239         /* We need a framebuffer large enough to accommodate all accesses
11240          * that the plane may generate whilst we perform load detection.
11241          * We can not rely on the fbcon either being present (we get called
11242          * during its initialisation to detect all boot displays, or it may
11243          * not even exist) or that it is large enough to satisfy the
11244          * requested mode.
11245          */
11246         fb = mode_fits_in_fbdev(dev, mode);
11247         if (fb == NULL) {
11248                 DRM_DEBUG_KMS("creating tmp fb for load-detection\n");
11249                 fb = intel_framebuffer_create_for_mode(dev, mode, 24, 32);
11250         } else
11251                 DRM_DEBUG_KMS("reusing fbdev for load-detection framebuffer\n");
11252         if (IS_ERR(fb)) {
11253                 DRM_DEBUG_KMS("failed to allocate framebuffer for load-detection\n");
11254                 goto fail;
11255         }
11256
11257         ret = intel_modeset_setup_plane_state(state, crtc, mode, fb, 0, 0);
11258         if (ret)
11259                 goto fail;
11260
11261         drm_framebuffer_unreference(fb);
11262
11263         ret = drm_atomic_set_mode_for_crtc(&crtc_state->base, mode);
11264         if (ret)
11265                 goto fail;
11266
11267         ret = PTR_ERR_OR_ZERO(drm_atomic_get_connector_state(restore_state, connector));
11268         if (!ret)
11269                 ret = PTR_ERR_OR_ZERO(drm_atomic_get_crtc_state(restore_state, crtc));
11270         if (!ret)
11271                 ret = PTR_ERR_OR_ZERO(drm_atomic_get_plane_state(restore_state, crtc->primary));
11272         if (ret) {
11273                 DRM_DEBUG_KMS("Failed to create a copy of old state to restore: %i\n", ret);
11274                 goto fail;
11275         }
11276
11277         ret = drm_atomic_commit(state);
11278         if (ret) {
11279                 DRM_DEBUG_KMS("failed to set mode on load-detect pipe\n");
11280                 goto fail;
11281         }
11282
11283         old->restore_state = restore_state;
11284
11285         /* let the connector get through one full cycle before testing */
11286         intel_wait_for_vblank(dev, intel_crtc->pipe);
11287         return true;
11288
11289 fail:
11290         drm_atomic_state_free(state);
11291         drm_atomic_state_free(restore_state);
11292         restore_state = state = NULL;
11293
11294         if (ret == -EDEADLK) {
11295                 drm_modeset_backoff(ctx);
11296                 goto retry;
11297         }
11298
11299         return false;
11300 }
11301
11302 void intel_release_load_detect_pipe(struct drm_connector *connector,
11303                                     struct intel_load_detect_pipe *old,
11304                                     struct drm_modeset_acquire_ctx *ctx)
11305 {
11306         struct intel_encoder *intel_encoder =
11307                 intel_attached_encoder(connector);
11308         struct drm_encoder *encoder = &intel_encoder->base;
11309         struct drm_atomic_state *state = old->restore_state;
11310         int ret;
11311
11312         DRM_DEBUG_KMS("[CONNECTOR:%d:%s], [ENCODER:%d:%s]\n",
11313                       connector->base.id, connector->name,
11314                       encoder->base.id, encoder->name);
11315
11316         if (!state)
11317                 return;
11318
11319         ret = drm_atomic_commit(state);
11320         if (ret) {
11321                 DRM_DEBUG_KMS("Couldn't release load detect pipe: %i\n", ret);
11322                 drm_atomic_state_free(state);
11323         }
11324 }
11325
11326 static int i9xx_pll_refclk(struct drm_device *dev,
11327                            const struct intel_crtc_state *pipe_config)
11328 {
11329         struct drm_i915_private *dev_priv = to_i915(dev);
11330         u32 dpll = pipe_config->dpll_hw_state.dpll;
11331
11332         if ((dpll & PLL_REF_INPUT_MASK) == PLLB_REF_INPUT_SPREADSPECTRUMIN)
11333                 return dev_priv->vbt.lvds_ssc_freq;
11334         else if (HAS_PCH_SPLIT(dev))
11335                 return 120000;
11336         else if (!IS_GEN2(dev))
11337                 return 96000;
11338         else
11339                 return 48000;
11340 }
11341
11342 /* Returns the clock of the currently programmed mode of the given pipe. */
11343 static void i9xx_crtc_clock_get(struct intel_crtc *crtc,
11344                                 struct intel_crtc_state *pipe_config)
11345 {
11346         struct drm_device *dev = crtc->base.dev;
11347         struct drm_i915_private *dev_priv = to_i915(dev);
11348         int pipe = pipe_config->cpu_transcoder;
11349         u32 dpll = pipe_config->dpll_hw_state.dpll;
11350         u32 fp;
11351         struct dpll clock;
11352         int port_clock;
11353         int refclk = i9xx_pll_refclk(dev, pipe_config);
11354
11355         if ((dpll & DISPLAY_RATE_SELECT_FPA1) == 0)
11356                 fp = pipe_config->dpll_hw_state.fp0;
11357         else
11358                 fp = pipe_config->dpll_hw_state.fp1;
11359
11360         clock.m1 = (fp & FP_M1_DIV_MASK) >> FP_M1_DIV_SHIFT;
11361         if (IS_PINEVIEW(dev)) {
11362                 clock.n = ffs((fp & FP_N_PINEVIEW_DIV_MASK) >> FP_N_DIV_SHIFT) - 1;
11363                 clock.m2 = (fp & FP_M2_PINEVIEW_DIV_MASK) >> FP_M2_DIV_SHIFT;
11364         } else {
11365                 clock.n = (fp & FP_N_DIV_MASK) >> FP_N_DIV_SHIFT;
11366                 clock.m2 = (fp & FP_M2_DIV_MASK) >> FP_M2_DIV_SHIFT;
11367         }
11368
11369         if (!IS_GEN2(dev)) {
11370                 if (IS_PINEVIEW(dev))
11371                         clock.p1 = ffs((dpll & DPLL_FPA01_P1_POST_DIV_MASK_PINEVIEW) >>
11372                                 DPLL_FPA01_P1_POST_DIV_SHIFT_PINEVIEW);
11373                 else
11374                         clock.p1 = ffs((dpll & DPLL_FPA01_P1_POST_DIV_MASK) >>
11375                                DPLL_FPA01_P1_POST_DIV_SHIFT);
11376
11377                 switch (dpll & DPLL_MODE_MASK) {
11378                 case DPLLB_MODE_DAC_SERIAL:
11379                         clock.p2 = dpll & DPLL_DAC_SERIAL_P2_CLOCK_DIV_5 ?
11380                                 5 : 10;
11381                         break;
11382                 case DPLLB_MODE_LVDS:
11383                         clock.p2 = dpll & DPLLB_LVDS_P2_CLOCK_DIV_7 ?
11384                                 7 : 14;
11385                         break;
11386                 default:
11387                         DRM_DEBUG_KMS("Unknown DPLL mode %08x in programmed "
11388                                   "mode\n", (int)(dpll & DPLL_MODE_MASK));
11389                         return;
11390                 }
11391
11392                 if (IS_PINEVIEW(dev))
11393                         port_clock = pnv_calc_dpll_params(refclk, &clock);
11394                 else
11395                         port_clock = i9xx_calc_dpll_params(refclk, &clock);
11396         } else {
11397                 u32 lvds = IS_I830(dev) ? 0 : I915_READ(LVDS);
11398                 bool is_lvds = (pipe == 1) && (lvds & LVDS_PORT_EN);
11399
11400                 if (is_lvds) {
11401                         clock.p1 = ffs((dpll & DPLL_FPA01_P1_POST_DIV_MASK_I830_LVDS) >>
11402                                        DPLL_FPA01_P1_POST_DIV_SHIFT);
11403
11404                         if (lvds & LVDS_CLKB_POWER_UP)
11405                                 clock.p2 = 7;
11406                         else
11407                                 clock.p2 = 14;
11408                 } else {
11409                         if (dpll & PLL_P1_DIVIDE_BY_TWO)
11410                                 clock.p1 = 2;
11411                         else {
11412                                 clock.p1 = ((dpll & DPLL_FPA01_P1_POST_DIV_MASK_I830) >>
11413                                             DPLL_FPA01_P1_POST_DIV_SHIFT) + 2;
11414                         }
11415                         if (dpll & PLL_P2_DIVIDE_BY_4)
11416                                 clock.p2 = 4;
11417                         else
11418                                 clock.p2 = 2;
11419                 }
11420
11421                 port_clock = i9xx_calc_dpll_params(refclk, &clock);
11422         }
11423
11424         /*
11425          * This value includes pixel_multiplier. We will use
11426          * port_clock to compute adjusted_mode.crtc_clock in the
11427          * encoder's get_config() function.
11428          */
11429         pipe_config->port_clock = port_clock;
11430 }
11431
11432 int intel_dotclock_calculate(int link_freq,
11433                              const struct intel_link_m_n *m_n)
11434 {
11435         /*
11436          * The calculation for the data clock is:
11437          * pixel_clock = ((m/n)*(link_clock * nr_lanes))/bpp
11438          * But we want to avoid losing precison if possible, so:
11439          * pixel_clock = ((m * link_clock * nr_lanes)/(n*bpp))
11440          *
11441          * and the link clock is simpler:
11442          * link_clock = (m * link_clock) / n
11443          */
11444
11445         if (!m_n->link_n)
11446                 return 0;
11447
11448         return div_u64((u64)m_n->link_m * link_freq, m_n->link_n);
11449 }
11450
11451 static void ironlake_pch_clock_get(struct intel_crtc *crtc,
11452                                    struct intel_crtc_state *pipe_config)
11453 {
11454         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
11455
11456         /* read out port_clock from the DPLL */
11457         i9xx_crtc_clock_get(crtc, pipe_config);
11458
11459         /*
11460          * In case there is an active pipe without active ports,
11461          * we may need some idea for the dotclock anyway.
11462          * Calculate one based on the FDI configuration.
11463          */
11464         pipe_config->base.adjusted_mode.crtc_clock =
11465                 intel_dotclock_calculate(intel_fdi_link_freq(dev_priv, pipe_config),
11466                                          &pipe_config->fdi_m_n);
11467 }
11468
11469 /** Returns the currently programmed mode of the given pipe. */
11470 struct drm_display_mode *intel_crtc_mode_get(struct drm_device *dev,
11471                                              struct drm_crtc *crtc)
11472 {
11473         struct drm_i915_private *dev_priv = to_i915(dev);
11474         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11475         enum transcoder cpu_transcoder;
11476         struct drm_display_mode *mode;
11477         struct intel_crtc_state *pipe_config;
11478         u32 htot, hsync, vtot, vsync;
11479         enum pipe pipe = intel_crtc->pipe;
11480
11481         mode = kzalloc(sizeof(*mode), GFP_KERNEL);
11482         if (!mode)
11483                 return NULL;
11484
11485         pipe_config = kzalloc(sizeof(*pipe_config), GFP_KERNEL);
11486         if (!pipe_config) {
11487                 kfree(mode);
11488                 return NULL;
11489         }
11490
11491         /*
11492          * Construct a pipe_config sufficient for getting the clock info
11493          * back out of crtc_clock_get.
11494          *
11495          * Note, if LVDS ever uses a non-1 pixel multiplier, we'll need
11496          * to use a real value here instead.
11497          */
11498         pipe_config->cpu_transcoder = (enum transcoder) pipe;
11499         pipe_config->pixel_multiplier = 1;
11500         pipe_config->dpll_hw_state.dpll = I915_READ(DPLL(pipe));
11501         pipe_config->dpll_hw_state.fp0 = I915_READ(FP0(pipe));
11502         pipe_config->dpll_hw_state.fp1 = I915_READ(FP1(pipe));
11503         i9xx_crtc_clock_get(intel_crtc, pipe_config);
11504
11505         mode->clock = pipe_config->port_clock / pipe_config->pixel_multiplier;
11506
11507         cpu_transcoder = pipe_config->cpu_transcoder;
11508         htot = I915_READ(HTOTAL(cpu_transcoder));
11509         hsync = I915_READ(HSYNC(cpu_transcoder));
11510         vtot = I915_READ(VTOTAL(cpu_transcoder));
11511         vsync = I915_READ(VSYNC(cpu_transcoder));
11512
11513         mode->hdisplay = (htot & 0xffff) + 1;
11514         mode->htotal = ((htot & 0xffff0000) >> 16) + 1;
11515         mode->hsync_start = (hsync & 0xffff) + 1;
11516         mode->hsync_end = ((hsync & 0xffff0000) >> 16) + 1;
11517         mode->vdisplay = (vtot & 0xffff) + 1;
11518         mode->vtotal = ((vtot & 0xffff0000) >> 16) + 1;
11519         mode->vsync_start = (vsync & 0xffff) + 1;
11520         mode->vsync_end = ((vsync & 0xffff0000) >> 16) + 1;
11521
11522         drm_mode_set_name(mode);
11523
11524         kfree(pipe_config);
11525
11526         return mode;
11527 }
11528
11529 static void intel_crtc_destroy(struct drm_crtc *crtc)
11530 {
11531         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11532         struct drm_device *dev = crtc->dev;
11533         struct intel_flip_work *work;
11534
11535         spin_lock_irq(&dev->event_lock);
11536         work = intel_crtc->flip_work;
11537         intel_crtc->flip_work = NULL;
11538         spin_unlock_irq(&dev->event_lock);
11539
11540         if (work) {
11541                 cancel_work_sync(&work->mmio_work);
11542                 cancel_work_sync(&work->unpin_work);
11543                 kfree(work);
11544         }
11545
11546         drm_crtc_cleanup(crtc);
11547
11548         kfree(intel_crtc);
11549 }
11550
11551 static void intel_unpin_work_fn(struct work_struct *__work)
11552 {
11553         struct intel_flip_work *work =
11554                 container_of(__work, struct intel_flip_work, unpin_work);
11555         struct intel_crtc *crtc = to_intel_crtc(work->crtc);
11556         struct drm_device *dev = crtc->base.dev;
11557         struct drm_plane *primary = crtc->base.primary;
11558
11559         if (is_mmio_work(work))
11560                 flush_work(&work->mmio_work);
11561
11562         mutex_lock(&dev->struct_mutex);
11563         intel_unpin_fb_obj(work->old_fb, primary->state->rotation);
11564         i915_gem_object_put(work->pending_flip_obj);
11565         mutex_unlock(&dev->struct_mutex);
11566
11567         i915_gem_request_put(work->flip_queued_req);
11568
11569         intel_frontbuffer_flip_complete(to_i915(dev),
11570                                         to_intel_plane(primary)->frontbuffer_bit);
11571         intel_fbc_post_update(crtc);
11572         drm_framebuffer_unreference(work->old_fb);
11573
11574         BUG_ON(atomic_read(&crtc->unpin_work_count) == 0);
11575         atomic_dec(&crtc->unpin_work_count);
11576
11577         kfree(work);
11578 }
11579
11580 /* Is 'a' after or equal to 'b'? */
11581 static bool g4x_flip_count_after_eq(u32 a, u32 b)
11582 {
11583         return !((a - b) & 0x80000000);
11584 }
11585
11586 static bool __pageflip_finished_cs(struct intel_crtc *crtc,
11587                                    struct intel_flip_work *work)
11588 {
11589         struct drm_device *dev = crtc->base.dev;
11590         struct drm_i915_private *dev_priv = to_i915(dev);
11591
11592         if (abort_flip_on_reset(crtc))
11593                 return true;
11594
11595         /*
11596          * The relevant registers doen't exist on pre-ctg.
11597          * As the flip done interrupt doesn't trigger for mmio
11598          * flips on gmch platforms, a flip count check isn't
11599          * really needed there. But since ctg has the registers,
11600          * include it in the check anyway.
11601          */
11602         if (INTEL_INFO(dev)->gen < 5 && !IS_G4X(dev))
11603                 return true;
11604
11605         /*
11606          * BDW signals flip done immediately if the plane
11607          * is disabled, even if the plane enable is already
11608          * armed to occur at the next vblank :(
11609          */
11610
11611         /*
11612          * A DSPSURFLIVE check isn't enough in case the mmio and CS flips
11613          * used the same base address. In that case the mmio flip might
11614          * have completed, but the CS hasn't even executed the flip yet.
11615          *
11616          * A flip count check isn't enough as the CS might have updated
11617          * the base address just after start of vblank, but before we
11618          * managed to process the interrupt. This means we'd complete the
11619          * CS flip too soon.
11620          *
11621          * Combining both checks should get us a good enough result. It may
11622          * still happen that the CS flip has been executed, but has not
11623          * yet actually completed. But in case the base address is the same
11624          * anyway, we don't really care.
11625          */
11626         return (I915_READ(DSPSURFLIVE(crtc->plane)) & ~0xfff) ==
11627                 crtc->flip_work->gtt_offset &&
11628                 g4x_flip_count_after_eq(I915_READ(PIPE_FLIPCOUNT_G4X(crtc->pipe)),
11629                                     crtc->flip_work->flip_count);
11630 }
11631
11632 static bool
11633 __pageflip_finished_mmio(struct intel_crtc *crtc,
11634                                struct intel_flip_work *work)
11635 {
11636         /*
11637          * MMIO work completes when vblank is different from
11638          * flip_queued_vblank.
11639          *
11640          * Reset counter value doesn't matter, this is handled by
11641          * i915_wait_request finishing early, so no need to handle
11642          * reset here.
11643          */
11644         return intel_crtc_get_vblank_counter(crtc) != work->flip_queued_vblank;
11645 }
11646
11647
11648 static bool pageflip_finished(struct intel_crtc *crtc,
11649                               struct intel_flip_work *work)
11650 {
11651         if (!atomic_read(&work->pending))
11652                 return false;
11653
11654         smp_rmb();
11655
11656         if (is_mmio_work(work))
11657                 return __pageflip_finished_mmio(crtc, work);
11658         else
11659                 return __pageflip_finished_cs(crtc, work);
11660 }
11661
11662 void intel_finish_page_flip_cs(struct drm_i915_private *dev_priv, int pipe)
11663 {
11664         struct drm_device *dev = &dev_priv->drm;
11665         struct drm_crtc *crtc = dev_priv->pipe_to_crtc_mapping[pipe];
11666         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11667         struct intel_flip_work *work;
11668         unsigned long flags;
11669
11670         /* Ignore early vblank irqs */
11671         if (!crtc)
11672                 return;
11673
11674         /*
11675          * This is called both by irq handlers and the reset code (to complete
11676          * lost pageflips) so needs the full irqsave spinlocks.
11677          */
11678         spin_lock_irqsave(&dev->event_lock, flags);
11679         work = intel_crtc->flip_work;
11680
11681         if (work != NULL &&
11682             !is_mmio_work(work) &&
11683             pageflip_finished(intel_crtc, work))
11684                 page_flip_completed(intel_crtc);
11685
11686         spin_unlock_irqrestore(&dev->event_lock, flags);
11687 }
11688
11689 void intel_finish_page_flip_mmio(struct drm_i915_private *dev_priv, int pipe)
11690 {
11691         struct drm_device *dev = &dev_priv->drm;
11692         struct drm_crtc *crtc = dev_priv->pipe_to_crtc_mapping[pipe];
11693         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11694         struct intel_flip_work *work;
11695         unsigned long flags;
11696
11697         /* Ignore early vblank irqs */
11698         if (!crtc)
11699                 return;
11700
11701         /*
11702          * This is called both by irq handlers and the reset code (to complete
11703          * lost pageflips) so needs the full irqsave spinlocks.
11704          */
11705         spin_lock_irqsave(&dev->event_lock, flags);
11706         work = intel_crtc->flip_work;
11707
11708         if (work != NULL &&
11709             is_mmio_work(work) &&
11710             pageflip_finished(intel_crtc, work))
11711                 page_flip_completed(intel_crtc);
11712
11713         spin_unlock_irqrestore(&dev->event_lock, flags);
11714 }
11715
11716 static inline void intel_mark_page_flip_active(struct intel_crtc *crtc,
11717                                                struct intel_flip_work *work)
11718 {
11719         work->flip_queued_vblank = intel_crtc_get_vblank_counter(crtc);
11720
11721         /* Ensure that the work item is consistent when activating it ... */
11722         smp_mb__before_atomic();
11723         atomic_set(&work->pending, 1);
11724 }
11725
11726 static int intel_gen2_queue_flip(struct drm_device *dev,
11727                                  struct drm_crtc *crtc,
11728                                  struct drm_framebuffer *fb,
11729                                  struct drm_i915_gem_object *obj,
11730                                  struct drm_i915_gem_request *req,
11731                                  uint32_t flags)
11732 {
11733         struct intel_ring *ring = req->ring;
11734         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11735         u32 flip_mask;
11736         int ret;
11737
11738         ret = intel_ring_begin(req, 6);
11739         if (ret)
11740                 return ret;
11741
11742         /* Can't queue multiple flips, so wait for the previous
11743          * one to finish before executing the next.
11744          */
11745         if (intel_crtc->plane)
11746                 flip_mask = MI_WAIT_FOR_PLANE_B_FLIP;
11747         else
11748                 flip_mask = MI_WAIT_FOR_PLANE_A_FLIP;
11749         intel_ring_emit(ring, MI_WAIT_FOR_EVENT | flip_mask);
11750         intel_ring_emit(ring, MI_NOOP);
11751         intel_ring_emit(ring, MI_DISPLAY_FLIP |
11752                         MI_DISPLAY_FLIP_PLANE(intel_crtc->plane));
11753         intel_ring_emit(ring, fb->pitches[0]);
11754         intel_ring_emit(ring, intel_crtc->flip_work->gtt_offset);
11755         intel_ring_emit(ring, 0); /* aux display base address, unused */
11756
11757         return 0;
11758 }
11759
11760 static int intel_gen3_queue_flip(struct drm_device *dev,
11761                                  struct drm_crtc *crtc,
11762                                  struct drm_framebuffer *fb,
11763                                  struct drm_i915_gem_object *obj,
11764                                  struct drm_i915_gem_request *req,
11765                                  uint32_t flags)
11766 {
11767         struct intel_ring *ring = req->ring;
11768         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11769         u32 flip_mask;
11770         int ret;
11771
11772         ret = intel_ring_begin(req, 6);
11773         if (ret)
11774                 return ret;
11775
11776         if (intel_crtc->plane)
11777                 flip_mask = MI_WAIT_FOR_PLANE_B_FLIP;
11778         else
11779                 flip_mask = MI_WAIT_FOR_PLANE_A_FLIP;
11780         intel_ring_emit(ring, MI_WAIT_FOR_EVENT | flip_mask);
11781         intel_ring_emit(ring, MI_NOOP);
11782         intel_ring_emit(ring, MI_DISPLAY_FLIP_I915 |
11783                         MI_DISPLAY_FLIP_PLANE(intel_crtc->plane));
11784         intel_ring_emit(ring, fb->pitches[0]);
11785         intel_ring_emit(ring, intel_crtc->flip_work->gtt_offset);
11786         intel_ring_emit(ring, MI_NOOP);
11787
11788         return 0;
11789 }
11790
11791 static int intel_gen4_queue_flip(struct drm_device *dev,
11792                                  struct drm_crtc *crtc,
11793                                  struct drm_framebuffer *fb,
11794                                  struct drm_i915_gem_object *obj,
11795                                  struct drm_i915_gem_request *req,
11796                                  uint32_t flags)
11797 {
11798         struct intel_ring *ring = req->ring;
11799         struct drm_i915_private *dev_priv = to_i915(dev);
11800         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11801         uint32_t pf, pipesrc;
11802         int ret;
11803
11804         ret = intel_ring_begin(req, 4);
11805         if (ret)
11806                 return ret;
11807
11808         /* i965+ uses the linear or tiled offsets from the
11809          * Display Registers (which do not change across a page-flip)
11810          * so we need only reprogram the base address.
11811          */
11812         intel_ring_emit(ring, MI_DISPLAY_FLIP |
11813                         MI_DISPLAY_FLIP_PLANE(intel_crtc->plane));
11814         intel_ring_emit(ring, fb->pitches[0]);
11815         intel_ring_emit(ring, intel_crtc->flip_work->gtt_offset |
11816                         intel_fb_modifier_to_tiling(fb->modifier[0]));
11817
11818         /* XXX Enabling the panel-fitter across page-flip is so far
11819          * untested on non-native modes, so ignore it for now.
11820          * pf = I915_READ(pipe == 0 ? PFA_CTL_1 : PFB_CTL_1) & PF_ENABLE;
11821          */
11822         pf = 0;
11823         pipesrc = I915_READ(PIPESRC(intel_crtc->pipe)) & 0x0fff0fff;
11824         intel_ring_emit(ring, pf | pipesrc);
11825
11826         return 0;
11827 }
11828
11829 static int intel_gen6_queue_flip(struct drm_device *dev,
11830                                  struct drm_crtc *crtc,
11831                                  struct drm_framebuffer *fb,
11832                                  struct drm_i915_gem_object *obj,
11833                                  struct drm_i915_gem_request *req,
11834                                  uint32_t flags)
11835 {
11836         struct intel_ring *ring = req->ring;
11837         struct drm_i915_private *dev_priv = to_i915(dev);
11838         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11839         uint32_t pf, pipesrc;
11840         int ret;
11841
11842         ret = intel_ring_begin(req, 4);
11843         if (ret)
11844                 return ret;
11845
11846         intel_ring_emit(ring, MI_DISPLAY_FLIP |
11847                         MI_DISPLAY_FLIP_PLANE(intel_crtc->plane));
11848         intel_ring_emit(ring, fb->pitches[0] |
11849                         intel_fb_modifier_to_tiling(fb->modifier[0]));
11850         intel_ring_emit(ring, intel_crtc->flip_work->gtt_offset);
11851
11852         /* Contrary to the suggestions in the documentation,
11853          * "Enable Panel Fitter" does not seem to be required when page
11854          * flipping with a non-native mode, and worse causes a normal
11855          * modeset to fail.
11856          * pf = I915_READ(PF_CTL(intel_crtc->pipe)) & PF_ENABLE;
11857          */
11858         pf = 0;
11859         pipesrc = I915_READ(PIPESRC(intel_crtc->pipe)) & 0x0fff0fff;
11860         intel_ring_emit(ring, pf | pipesrc);
11861
11862         return 0;
11863 }
11864
11865 static int intel_gen7_queue_flip(struct drm_device *dev,
11866                                  struct drm_crtc *crtc,
11867                                  struct drm_framebuffer *fb,
11868                                  struct drm_i915_gem_object *obj,
11869                                  struct drm_i915_gem_request *req,
11870                                  uint32_t flags)
11871 {
11872         struct intel_ring *ring = req->ring;
11873         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11874         uint32_t plane_bit = 0;
11875         int len, ret;
11876
11877         switch (intel_crtc->plane) {
11878         case PLANE_A:
11879                 plane_bit = MI_DISPLAY_FLIP_IVB_PLANE_A;
11880                 break;
11881         case PLANE_B:
11882                 plane_bit = MI_DISPLAY_FLIP_IVB_PLANE_B;
11883                 break;
11884         case PLANE_C:
11885                 plane_bit = MI_DISPLAY_FLIP_IVB_PLANE_C;
11886                 break;
11887         default:
11888                 WARN_ONCE(1, "unknown plane in flip command\n");
11889                 return -ENODEV;
11890         }
11891
11892         len = 4;
11893         if (req->engine->id == RCS) {
11894                 len += 6;
11895                 /*
11896                  * On Gen 8, SRM is now taking an extra dword to accommodate
11897                  * 48bits addresses, and we need a NOOP for the batch size to
11898                  * stay even.
11899                  */
11900                 if (IS_GEN8(dev))
11901                         len += 2;
11902         }
11903
11904         /*
11905          * BSpec MI_DISPLAY_FLIP for IVB:
11906          * "The full packet must be contained within the same cache line."
11907          *
11908          * Currently the LRI+SRM+MI_DISPLAY_FLIP all fit within the same
11909          * cacheline, if we ever start emitting more commands before
11910          * the MI_DISPLAY_FLIP we may need to first emit everything else,
11911          * then do the cacheline alignment, and finally emit the
11912          * MI_DISPLAY_FLIP.
11913          */
11914         ret = intel_ring_cacheline_align(req);
11915         if (ret)
11916                 return ret;
11917
11918         ret = intel_ring_begin(req, len);
11919         if (ret)
11920                 return ret;
11921
11922         /* Unmask the flip-done completion message. Note that the bspec says that
11923          * we should do this for both the BCS and RCS, and that we must not unmask
11924          * more than one flip event at any time (or ensure that one flip message
11925          * can be sent by waiting for flip-done prior to queueing new flips).
11926          * Experimentation says that BCS works despite DERRMR masking all
11927          * flip-done completion events and that unmasking all planes at once
11928          * for the RCS also doesn't appear to drop events. Setting the DERRMR
11929          * to zero does lead to lockups within MI_DISPLAY_FLIP.
11930          */
11931         if (req->engine->id == RCS) {
11932                 intel_ring_emit(ring, MI_LOAD_REGISTER_IMM(1));
11933                 intel_ring_emit_reg(ring, DERRMR);
11934                 intel_ring_emit(ring, ~(DERRMR_PIPEA_PRI_FLIP_DONE |
11935                                           DERRMR_PIPEB_PRI_FLIP_DONE |
11936                                           DERRMR_PIPEC_PRI_FLIP_DONE));
11937                 if (IS_GEN8(dev))
11938                         intel_ring_emit(ring, MI_STORE_REGISTER_MEM_GEN8 |
11939                                               MI_SRM_LRM_GLOBAL_GTT);
11940                 else
11941                         intel_ring_emit(ring, MI_STORE_REGISTER_MEM |
11942                                               MI_SRM_LRM_GLOBAL_GTT);
11943                 intel_ring_emit_reg(ring, DERRMR);
11944                 intel_ring_emit(ring,
11945                                 i915_ggtt_offset(req->engine->scratch) + 256);
11946                 if (IS_GEN8(dev)) {
11947                         intel_ring_emit(ring, 0);
11948                         intel_ring_emit(ring, MI_NOOP);
11949                 }
11950         }
11951
11952         intel_ring_emit(ring, MI_DISPLAY_FLIP_I915 | plane_bit);
11953         intel_ring_emit(ring, fb->pitches[0] |
11954                         intel_fb_modifier_to_tiling(fb->modifier[0]));
11955         intel_ring_emit(ring, intel_crtc->flip_work->gtt_offset);
11956         intel_ring_emit(ring, (MI_NOOP));
11957
11958         return 0;
11959 }
11960
11961 static bool use_mmio_flip(struct intel_engine_cs *engine,
11962                           struct drm_i915_gem_object *obj)
11963 {
11964         struct reservation_object *resv;
11965
11966         /*
11967          * This is not being used for older platforms, because
11968          * non-availability of flip done interrupt forces us to use
11969          * CS flips. Older platforms derive flip done using some clever
11970          * tricks involving the flip_pending status bits and vblank irqs.
11971          * So using MMIO flips there would disrupt this mechanism.
11972          */
11973
11974         if (engine == NULL)
11975                 return true;
11976
11977         if (INTEL_GEN(engine->i915) < 5)
11978                 return false;
11979
11980         if (i915.use_mmio_flip < 0)
11981                 return false;
11982         else if (i915.use_mmio_flip > 0)
11983                 return true;
11984         else if (i915.enable_execlists)
11985                 return true;
11986
11987         resv = i915_gem_object_get_dmabuf_resv(obj);
11988         if (resv && !reservation_object_test_signaled_rcu(resv, false))
11989                 return true;
11990
11991         return engine != i915_gem_active_get_engine(&obj->last_write,
11992                                                     &obj->base.dev->struct_mutex);
11993 }
11994
11995 static void skl_do_mmio_flip(struct intel_crtc *intel_crtc,
11996                              unsigned int rotation,
11997                              struct intel_flip_work *work)
11998 {
11999         struct drm_device *dev = intel_crtc->base.dev;
12000         struct drm_i915_private *dev_priv = to_i915(dev);
12001         struct drm_framebuffer *fb = intel_crtc->base.primary->fb;
12002         const enum pipe pipe = intel_crtc->pipe;
12003         u32 ctl, stride = skl_plane_stride(fb, 0, rotation);
12004
12005         ctl = I915_READ(PLANE_CTL(pipe, 0));
12006         ctl &= ~PLANE_CTL_TILED_MASK;
12007         switch (fb->modifier[0]) {
12008         case DRM_FORMAT_MOD_NONE:
12009                 break;
12010         case I915_FORMAT_MOD_X_TILED:
12011                 ctl |= PLANE_CTL_TILED_X;
12012                 break;
12013         case I915_FORMAT_MOD_Y_TILED:
12014                 ctl |= PLANE_CTL_TILED_Y;
12015                 break;
12016         case I915_FORMAT_MOD_Yf_TILED:
12017                 ctl |= PLANE_CTL_TILED_YF;
12018                 break;
12019         default:
12020                 MISSING_CASE(fb->modifier[0]);
12021         }
12022
12023         /*
12024          * Both PLANE_CTL and PLANE_STRIDE are not updated on vblank but on
12025          * PLANE_SURF updates, the update is then guaranteed to be atomic.
12026          */
12027         I915_WRITE(PLANE_CTL(pipe, 0), ctl);
12028         I915_WRITE(PLANE_STRIDE(pipe, 0), stride);
12029
12030         I915_WRITE(PLANE_SURF(pipe, 0), work->gtt_offset);
12031         POSTING_READ(PLANE_SURF(pipe, 0));
12032 }
12033
12034 static void ilk_do_mmio_flip(struct intel_crtc *intel_crtc,
12035                              struct intel_flip_work *work)
12036 {
12037         struct drm_device *dev = intel_crtc->base.dev;
12038         struct drm_i915_private *dev_priv = to_i915(dev);
12039         struct drm_framebuffer *fb = intel_crtc->base.primary->fb;
12040         i915_reg_t reg = DSPCNTR(intel_crtc->plane);
12041         u32 dspcntr;
12042
12043         dspcntr = I915_READ(reg);
12044
12045         if (fb->modifier[0] == I915_FORMAT_MOD_X_TILED)
12046                 dspcntr |= DISPPLANE_TILED;
12047         else
12048                 dspcntr &= ~DISPPLANE_TILED;
12049
12050         I915_WRITE(reg, dspcntr);
12051
12052         I915_WRITE(DSPSURF(intel_crtc->plane), work->gtt_offset);
12053         POSTING_READ(DSPSURF(intel_crtc->plane));
12054 }
12055
12056 static void intel_mmio_flip_work_func(struct work_struct *w)
12057 {
12058         struct intel_flip_work *work =
12059                 container_of(w, struct intel_flip_work, mmio_work);
12060         struct intel_crtc *crtc = to_intel_crtc(work->crtc);
12061         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
12062         struct intel_framebuffer *intel_fb =
12063                 to_intel_framebuffer(crtc->base.primary->fb);
12064         struct drm_i915_gem_object *obj = intel_fb->obj;
12065         struct reservation_object *resv;
12066
12067         if (work->flip_queued_req)
12068                 WARN_ON(i915_wait_request(work->flip_queued_req,
12069                                           0, NULL, NO_WAITBOOST));
12070
12071         /* For framebuffer backed by dmabuf, wait for fence */
12072         resv = i915_gem_object_get_dmabuf_resv(obj);
12073         if (resv)
12074                 WARN_ON(reservation_object_wait_timeout_rcu(resv, false, false,
12075                                                             MAX_SCHEDULE_TIMEOUT) < 0);
12076
12077         intel_pipe_update_start(crtc);
12078
12079         if (INTEL_GEN(dev_priv) >= 9)
12080                 skl_do_mmio_flip(crtc, work->rotation, work);
12081         else
12082                 /* use_mmio_flip() retricts MMIO flips to ilk+ */
12083                 ilk_do_mmio_flip(crtc, work);
12084
12085         intel_pipe_update_end(crtc, work);
12086 }
12087
12088 static int intel_default_queue_flip(struct drm_device *dev,
12089                                     struct drm_crtc *crtc,
12090                                     struct drm_framebuffer *fb,
12091                                     struct drm_i915_gem_object *obj,
12092                                     struct drm_i915_gem_request *req,
12093                                     uint32_t flags)
12094 {
12095         return -ENODEV;
12096 }
12097
12098 static bool __pageflip_stall_check_cs(struct drm_i915_private *dev_priv,
12099                                       struct intel_crtc *intel_crtc,
12100                                       struct intel_flip_work *work)
12101 {
12102         u32 addr, vblank;
12103
12104         if (!atomic_read(&work->pending))
12105                 return false;
12106
12107         smp_rmb();
12108
12109         vblank = intel_crtc_get_vblank_counter(intel_crtc);
12110         if (work->flip_ready_vblank == 0) {
12111                 if (work->flip_queued_req &&
12112                     !i915_gem_request_completed(work->flip_queued_req))
12113                         return false;
12114
12115                 work->flip_ready_vblank = vblank;
12116         }
12117
12118         if (vblank - work->flip_ready_vblank < 3)
12119                 return false;
12120
12121         /* Potential stall - if we see that the flip has happened,
12122          * assume a missed interrupt. */
12123         if (INTEL_GEN(dev_priv) >= 4)
12124                 addr = I915_HI_DISPBASE(I915_READ(DSPSURF(intel_crtc->plane)));
12125         else
12126                 addr = I915_READ(DSPADDR(intel_crtc->plane));
12127
12128         /* There is a potential issue here with a false positive after a flip
12129          * to the same address. We could address this by checking for a
12130          * non-incrementing frame counter.
12131          */
12132         return addr == work->gtt_offset;
12133 }
12134
12135 void intel_check_page_flip(struct drm_i915_private *dev_priv, int pipe)
12136 {
12137         struct drm_device *dev = &dev_priv->drm;
12138         struct drm_crtc *crtc = dev_priv->pipe_to_crtc_mapping[pipe];
12139         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
12140         struct intel_flip_work *work;
12141
12142         WARN_ON(!in_interrupt());
12143
12144         if (crtc == NULL)
12145                 return;
12146
12147         spin_lock(&dev->event_lock);
12148         work = intel_crtc->flip_work;
12149
12150         if (work != NULL && !is_mmio_work(work) &&
12151             __pageflip_stall_check_cs(dev_priv, intel_crtc, work)) {
12152                 WARN_ONCE(1,
12153                           "Kicking stuck page flip: queued at %d, now %d\n",
12154                         work->flip_queued_vblank, intel_crtc_get_vblank_counter(intel_crtc));
12155                 page_flip_completed(intel_crtc);
12156                 work = NULL;
12157         }
12158
12159         if (work != NULL && !is_mmio_work(work) &&
12160             intel_crtc_get_vblank_counter(intel_crtc) - work->flip_queued_vblank > 1)
12161                 intel_queue_rps_boost_for_request(work->flip_queued_req);
12162         spin_unlock(&dev->event_lock);
12163 }
12164
12165 static int intel_crtc_page_flip(struct drm_crtc *crtc,
12166                                 struct drm_framebuffer *fb,
12167                                 struct drm_pending_vblank_event *event,
12168                                 uint32_t page_flip_flags)
12169 {
12170         struct drm_device *dev = crtc->dev;
12171         struct drm_i915_private *dev_priv = to_i915(dev);
12172         struct drm_framebuffer *old_fb = crtc->primary->fb;
12173         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
12174         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
12175         struct drm_plane *primary = crtc->primary;
12176         enum pipe pipe = intel_crtc->pipe;
12177         struct intel_flip_work *work;
12178         struct intel_engine_cs *engine;
12179         bool mmio_flip;
12180         struct drm_i915_gem_request *request;
12181         struct i915_vma *vma;
12182         int ret;
12183
12184         /*
12185          * drm_mode_page_flip_ioctl() should already catch this, but double
12186          * check to be safe.  In the future we may enable pageflipping from
12187          * a disabled primary plane.
12188          */
12189         if (WARN_ON(intel_fb_obj(old_fb) == NULL))
12190                 return -EBUSY;
12191
12192         /* Can't change pixel format via MI display flips. */
12193         if (fb->pixel_format != crtc->primary->fb->pixel_format)
12194                 return -EINVAL;
12195
12196         /*
12197          * TILEOFF/LINOFF registers can't be changed via MI display flips.
12198          * Note that pitch changes could also affect these register.
12199          */
12200         if (INTEL_INFO(dev)->gen > 3 &&
12201             (fb->offsets[0] != crtc->primary->fb->offsets[0] ||
12202              fb->pitches[0] != crtc->primary->fb->pitches[0]))
12203                 return -EINVAL;
12204
12205         if (i915_terminally_wedged(&dev_priv->gpu_error))
12206                 goto out_hang;
12207
12208         work = kzalloc(sizeof(*work), GFP_KERNEL);
12209         if (work == NULL)
12210                 return -ENOMEM;
12211
12212         work->event = event;
12213         work->crtc = crtc;
12214         work->old_fb = old_fb;
12215         INIT_WORK(&work->unpin_work, intel_unpin_work_fn);
12216
12217         ret = drm_crtc_vblank_get(crtc);
12218         if (ret)
12219                 goto free_work;
12220
12221         /* We borrow the event spin lock for protecting flip_work */
12222         spin_lock_irq(&dev->event_lock);
12223         if (intel_crtc->flip_work) {
12224                 /* Before declaring the flip queue wedged, check if
12225                  * the hardware completed the operation behind our backs.
12226                  */
12227                 if (pageflip_finished(intel_crtc, intel_crtc->flip_work)) {
12228                         DRM_DEBUG_DRIVER("flip queue: previous flip completed, continuing\n");
12229                         page_flip_completed(intel_crtc);
12230                 } else {
12231                         DRM_DEBUG_DRIVER("flip queue: crtc already busy\n");
12232                         spin_unlock_irq(&dev->event_lock);
12233
12234                         drm_crtc_vblank_put(crtc);
12235                         kfree(work);
12236                         return -EBUSY;
12237                 }
12238         }
12239         intel_crtc->flip_work = work;
12240         spin_unlock_irq(&dev->event_lock);
12241
12242         if (atomic_read(&intel_crtc->unpin_work_count) >= 2)
12243                 flush_workqueue(dev_priv->wq);
12244
12245         /* Reference the objects for the scheduled work. */
12246         drm_framebuffer_reference(work->old_fb);
12247
12248         crtc->primary->fb = fb;
12249         update_state_fb(crtc->primary);
12250
12251         work->pending_flip_obj = i915_gem_object_get(obj);
12252
12253         ret = i915_mutex_lock_interruptible(dev);
12254         if (ret)
12255                 goto cleanup;
12256
12257         intel_crtc->reset_count = i915_reset_count(&dev_priv->gpu_error);
12258         if (i915_reset_in_progress_or_wedged(&dev_priv->gpu_error)) {
12259                 ret = -EIO;
12260                 goto unlock;
12261         }
12262
12263         atomic_inc(&intel_crtc->unpin_work_count);
12264
12265         if (INTEL_INFO(dev)->gen >= 5 || IS_G4X(dev))
12266                 work->flip_count = I915_READ(PIPE_FLIPCOUNT_G4X(pipe)) + 1;
12267
12268         if (IS_VALLEYVIEW(dev) || IS_CHERRYVIEW(dev)) {
12269                 engine = &dev_priv->engine[BCS];
12270                 if (fb->modifier[0] != old_fb->modifier[0])
12271                         /* vlv: DISPLAY_FLIP fails to change tiling */
12272                         engine = NULL;
12273         } else if (IS_IVYBRIDGE(dev) || IS_HASWELL(dev)) {
12274                 engine = &dev_priv->engine[BCS];
12275         } else if (INTEL_INFO(dev)->gen >= 7) {
12276                 engine = i915_gem_active_get_engine(&obj->last_write,
12277                                                     &obj->base.dev->struct_mutex);
12278                 if (engine == NULL || engine->id != RCS)
12279                         engine = &dev_priv->engine[BCS];
12280         } else {
12281                 engine = &dev_priv->engine[RCS];
12282         }
12283
12284         mmio_flip = use_mmio_flip(engine, obj);
12285
12286         vma = intel_pin_and_fence_fb_obj(fb, primary->state->rotation);
12287         if (IS_ERR(vma)) {
12288                 ret = PTR_ERR(vma);
12289                 goto cleanup_pending;
12290         }
12291
12292         work->gtt_offset = intel_fb_gtt_offset(fb, primary->state->rotation);
12293         work->gtt_offset += intel_crtc->dspaddr_offset;
12294         work->rotation = crtc->primary->state->rotation;
12295
12296         /*
12297          * There's the potential that the next frame will not be compatible with
12298          * FBC, so we want to call pre_update() before the actual page flip.
12299          * The problem is that pre_update() caches some information about the fb
12300          * object, so we want to do this only after the object is pinned. Let's
12301          * be on the safe side and do this immediately before scheduling the
12302          * flip.
12303          */
12304         intel_fbc_pre_update(intel_crtc, intel_crtc->config,
12305                              to_intel_plane_state(primary->state));
12306
12307         if (mmio_flip) {
12308                 INIT_WORK(&work->mmio_work, intel_mmio_flip_work_func);
12309
12310                 work->flip_queued_req = i915_gem_active_get(&obj->last_write,
12311                                                             &obj->base.dev->struct_mutex);
12312                 schedule_work(&work->mmio_work);
12313         } else {
12314                 request = i915_gem_request_alloc(engine, engine->last_context);
12315                 if (IS_ERR(request)) {
12316                         ret = PTR_ERR(request);
12317                         goto cleanup_unpin;
12318                 }
12319
12320                 ret = i915_gem_request_await_object(request, obj, false);
12321                 if (ret)
12322                         goto cleanup_request;
12323
12324                 ret = dev_priv->display.queue_flip(dev, crtc, fb, obj, request,
12325                                                    page_flip_flags);
12326                 if (ret)
12327                         goto cleanup_request;
12328
12329                 intel_mark_page_flip_active(intel_crtc, work);
12330
12331                 work->flip_queued_req = i915_gem_request_get(request);
12332                 i915_add_request_no_flush(request);
12333         }
12334
12335         i915_gem_track_fb(intel_fb_obj(old_fb), obj,
12336                           to_intel_plane(primary)->frontbuffer_bit);
12337         mutex_unlock(&dev->struct_mutex);
12338
12339         intel_frontbuffer_flip_prepare(to_i915(dev),
12340                                        to_intel_plane(primary)->frontbuffer_bit);
12341
12342         trace_i915_flip_request(intel_crtc->plane, obj);
12343
12344         return 0;
12345
12346 cleanup_request:
12347         i915_add_request_no_flush(request);
12348 cleanup_unpin:
12349         intel_unpin_fb_obj(fb, crtc->primary->state->rotation);
12350 cleanup_pending:
12351         atomic_dec(&intel_crtc->unpin_work_count);
12352 unlock:
12353         mutex_unlock(&dev->struct_mutex);
12354 cleanup:
12355         crtc->primary->fb = old_fb;
12356         update_state_fb(crtc->primary);
12357
12358         i915_gem_object_put_unlocked(obj);
12359         drm_framebuffer_unreference(work->old_fb);
12360
12361         spin_lock_irq(&dev->event_lock);
12362         intel_crtc->flip_work = NULL;
12363         spin_unlock_irq(&dev->event_lock);
12364
12365         drm_crtc_vblank_put(crtc);
12366 free_work:
12367         kfree(work);
12368
12369         if (ret == -EIO) {
12370                 struct drm_atomic_state *state;
12371                 struct drm_plane_state *plane_state;
12372
12373 out_hang:
12374                 state = drm_atomic_state_alloc(dev);
12375                 if (!state)
12376                         return -ENOMEM;
12377                 state->acquire_ctx = drm_modeset_legacy_acquire_ctx(crtc);
12378
12379 retry:
12380                 plane_state = drm_atomic_get_plane_state(state, primary);
12381                 ret = PTR_ERR_OR_ZERO(plane_state);
12382                 if (!ret) {
12383                         drm_atomic_set_fb_for_plane(plane_state, fb);
12384
12385                         ret = drm_atomic_set_crtc_for_plane(plane_state, crtc);
12386                         if (!ret)
12387                                 ret = drm_atomic_commit(state);
12388                 }
12389
12390                 if (ret == -EDEADLK) {
12391                         drm_modeset_backoff(state->acquire_ctx);
12392                         drm_atomic_state_clear(state);
12393                         goto retry;
12394                 }
12395
12396                 if (ret)
12397                         drm_atomic_state_free(state);
12398
12399                 if (ret == 0 && event) {
12400                         spin_lock_irq(&dev->event_lock);
12401                         drm_crtc_send_vblank_event(crtc, event);
12402                         spin_unlock_irq(&dev->event_lock);
12403                 }
12404         }
12405         return ret;
12406 }
12407
12408
12409 /**
12410  * intel_wm_need_update - Check whether watermarks need updating
12411  * @plane: drm plane
12412  * @state: new plane state
12413  *
12414  * Check current plane state versus the new one to determine whether
12415  * watermarks need to be recalculated.
12416  *
12417  * Returns true or false.
12418  */
12419 static bool intel_wm_need_update(struct drm_plane *plane,
12420                                  struct drm_plane_state *state)
12421 {
12422         struct intel_plane_state *new = to_intel_plane_state(state);
12423         struct intel_plane_state *cur = to_intel_plane_state(plane->state);
12424
12425         /* Update watermarks on tiling or size changes. */
12426         if (new->base.visible != cur->base.visible)
12427                 return true;
12428
12429         if (!cur->base.fb || !new->base.fb)
12430                 return false;
12431
12432         if (cur->base.fb->modifier[0] != new->base.fb->modifier[0] ||
12433             cur->base.rotation != new->base.rotation ||
12434             drm_rect_width(&new->base.src) != drm_rect_width(&cur->base.src) ||
12435             drm_rect_height(&new->base.src) != drm_rect_height(&cur->base.src) ||
12436             drm_rect_width(&new->base.dst) != drm_rect_width(&cur->base.dst) ||
12437             drm_rect_height(&new->base.dst) != drm_rect_height(&cur->base.dst))
12438                 return true;
12439
12440         return false;
12441 }
12442
12443 static bool needs_scaling(struct intel_plane_state *state)
12444 {
12445         int src_w = drm_rect_width(&state->base.src) >> 16;
12446         int src_h = drm_rect_height(&state->base.src) >> 16;
12447         int dst_w = drm_rect_width(&state->base.dst);
12448         int dst_h = drm_rect_height(&state->base.dst);
12449
12450         return (src_w != dst_w || src_h != dst_h);
12451 }
12452
12453 int intel_plane_atomic_calc_changes(struct drm_crtc_state *crtc_state,
12454                                     struct drm_plane_state *plane_state)
12455 {
12456         struct intel_crtc_state *pipe_config = to_intel_crtc_state(crtc_state);
12457         struct drm_crtc *crtc = crtc_state->crtc;
12458         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
12459         struct drm_plane *plane = plane_state->plane;
12460         struct drm_device *dev = crtc->dev;
12461         struct drm_i915_private *dev_priv = to_i915(dev);
12462         struct intel_plane_state *old_plane_state =
12463                 to_intel_plane_state(plane->state);
12464         bool mode_changed = needs_modeset(crtc_state);
12465         bool was_crtc_enabled = crtc->state->active;
12466         bool is_crtc_enabled = crtc_state->active;
12467         bool turn_off, turn_on, visible, was_visible;
12468         struct drm_framebuffer *fb = plane_state->fb;
12469         int ret;
12470
12471         if (INTEL_GEN(dev) >= 9 && plane->type != DRM_PLANE_TYPE_CURSOR) {
12472                 ret = skl_update_scaler_plane(
12473                         to_intel_crtc_state(crtc_state),
12474                         to_intel_plane_state(plane_state));
12475                 if (ret)
12476                         return ret;
12477         }
12478
12479         was_visible = old_plane_state->base.visible;
12480         visible = to_intel_plane_state(plane_state)->base.visible;
12481
12482         if (!was_crtc_enabled && WARN_ON(was_visible))
12483                 was_visible = false;
12484
12485         /*
12486          * Visibility is calculated as if the crtc was on, but
12487          * after scaler setup everything depends on it being off
12488          * when the crtc isn't active.
12489          *
12490          * FIXME this is wrong for watermarks. Watermarks should also
12491          * be computed as if the pipe would be active. Perhaps move
12492          * per-plane wm computation to the .check_plane() hook, and
12493          * only combine the results from all planes in the current place?
12494          */
12495         if (!is_crtc_enabled)
12496                 to_intel_plane_state(plane_state)->base.visible = visible = false;
12497
12498         if (!was_visible && !visible)
12499                 return 0;
12500
12501         if (fb != old_plane_state->base.fb)
12502                 pipe_config->fb_changed = true;
12503
12504         turn_off = was_visible && (!visible || mode_changed);
12505         turn_on = visible && (!was_visible || mode_changed);
12506
12507         DRM_DEBUG_ATOMIC("[CRTC:%d:%s] has [PLANE:%d:%s] with fb %i\n",
12508                          intel_crtc->base.base.id,
12509                          intel_crtc->base.name,
12510                          plane->base.id, plane->name,
12511                          fb ? fb->base.id : -1);
12512
12513         DRM_DEBUG_ATOMIC("[PLANE:%d:%s] visible %i -> %i, off %i, on %i, ms %i\n",
12514                          plane->base.id, plane->name,
12515                          was_visible, visible,
12516                          turn_off, turn_on, mode_changed);
12517
12518         if (turn_on) {
12519                 pipe_config->update_wm_pre = true;
12520
12521                 /* must disable cxsr around plane enable/disable */
12522                 if (plane->type != DRM_PLANE_TYPE_CURSOR)
12523                         pipe_config->disable_cxsr = true;
12524         } else if (turn_off) {
12525                 pipe_config->update_wm_post = true;
12526
12527                 /* must disable cxsr around plane enable/disable */
12528                 if (plane->type != DRM_PLANE_TYPE_CURSOR)
12529                         pipe_config->disable_cxsr = true;
12530         } else if (intel_wm_need_update(plane, plane_state)) {
12531                 /* FIXME bollocks */
12532                 pipe_config->update_wm_pre = true;
12533                 pipe_config->update_wm_post = true;
12534         }
12535
12536         /* Pre-gen9 platforms need two-step watermark updates */
12537         if ((pipe_config->update_wm_pre || pipe_config->update_wm_post) &&
12538             INTEL_INFO(dev)->gen < 9 && dev_priv->display.optimize_watermarks)
12539                 to_intel_crtc_state(crtc_state)->wm.need_postvbl_update = true;
12540
12541         if (visible || was_visible)
12542                 pipe_config->fb_bits |= to_intel_plane(plane)->frontbuffer_bit;
12543
12544         /*
12545          * WaCxSRDisabledForSpriteScaling:ivb
12546          *
12547          * cstate->update_wm was already set above, so this flag will
12548          * take effect when we commit and program watermarks.
12549          */
12550         if (plane->type == DRM_PLANE_TYPE_OVERLAY && IS_IVYBRIDGE(dev) &&
12551             needs_scaling(to_intel_plane_state(plane_state)) &&
12552             !needs_scaling(old_plane_state))
12553                 pipe_config->disable_lp_wm = true;
12554
12555         return 0;
12556 }
12557
12558 static bool encoders_cloneable(const struct intel_encoder *a,
12559                                const struct intel_encoder *b)
12560 {
12561         /* masks could be asymmetric, so check both ways */
12562         return a == b || (a->cloneable & (1 << b->type) &&
12563                           b->cloneable & (1 << a->type));
12564 }
12565
12566 static bool check_single_encoder_cloning(struct drm_atomic_state *state,
12567                                          struct intel_crtc *crtc,
12568                                          struct intel_encoder *encoder)
12569 {
12570         struct intel_encoder *source_encoder;
12571         struct drm_connector *connector;
12572         struct drm_connector_state *connector_state;
12573         int i;
12574
12575         for_each_connector_in_state(state, connector, connector_state, i) {
12576                 if (connector_state->crtc != &crtc->base)
12577                         continue;
12578
12579                 source_encoder =
12580                         to_intel_encoder(connector_state->best_encoder);
12581                 if (!encoders_cloneable(encoder, source_encoder))
12582                         return false;
12583         }
12584
12585         return true;
12586 }
12587
12588 static int intel_crtc_atomic_check(struct drm_crtc *crtc,
12589                                    struct drm_crtc_state *crtc_state)
12590 {
12591         struct drm_device *dev = crtc->dev;
12592         struct drm_i915_private *dev_priv = to_i915(dev);
12593         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
12594         struct intel_crtc_state *pipe_config =
12595                 to_intel_crtc_state(crtc_state);
12596         struct drm_atomic_state *state = crtc_state->state;
12597         int ret;
12598         bool mode_changed = needs_modeset(crtc_state);
12599
12600         if (mode_changed && !crtc_state->active)
12601                 pipe_config->update_wm_post = true;
12602
12603         if (mode_changed && crtc_state->enable &&
12604             dev_priv->display.crtc_compute_clock &&
12605             !WARN_ON(pipe_config->shared_dpll)) {
12606                 ret = dev_priv->display.crtc_compute_clock(intel_crtc,
12607                                                            pipe_config);
12608                 if (ret)
12609                         return ret;
12610         }
12611
12612         if (crtc_state->color_mgmt_changed) {
12613                 ret = intel_color_check(crtc, crtc_state);
12614                 if (ret)
12615                         return ret;
12616
12617                 /*
12618                  * Changing color management on Intel hardware is
12619                  * handled as part of planes update.
12620                  */
12621                 crtc_state->planes_changed = true;
12622         }
12623
12624         ret = 0;
12625         if (dev_priv->display.compute_pipe_wm) {
12626                 ret = dev_priv->display.compute_pipe_wm(pipe_config);
12627                 if (ret) {
12628                         DRM_DEBUG_KMS("Target pipe watermarks are invalid\n");
12629                         return ret;
12630                 }
12631         }
12632
12633         if (dev_priv->display.compute_intermediate_wm &&
12634             !to_intel_atomic_state(state)->skip_intermediate_wm) {
12635                 if (WARN_ON(!dev_priv->display.compute_pipe_wm))
12636                         return 0;
12637
12638                 /*
12639                  * Calculate 'intermediate' watermarks that satisfy both the
12640                  * old state and the new state.  We can program these
12641                  * immediately.
12642                  */
12643                 ret = dev_priv->display.compute_intermediate_wm(crtc->dev,
12644                                                                 intel_crtc,
12645                                                                 pipe_config);
12646                 if (ret) {
12647                         DRM_DEBUG_KMS("No valid intermediate pipe watermarks are possible\n");
12648                         return ret;
12649                 }
12650         } else if (dev_priv->display.compute_intermediate_wm) {
12651                 if (HAS_PCH_SPLIT(dev_priv) && INTEL_GEN(dev_priv) < 9)
12652                         pipe_config->wm.ilk.intermediate = pipe_config->wm.ilk.optimal;
12653         }
12654
12655         if (INTEL_INFO(dev)->gen >= 9) {
12656                 if (mode_changed)
12657                         ret = skl_update_scaler_crtc(pipe_config);
12658
12659                 if (!ret)
12660                         ret = intel_atomic_setup_scalers(dev, intel_crtc,
12661                                                          pipe_config);
12662         }
12663
12664         return ret;
12665 }
12666
12667 static const struct drm_crtc_helper_funcs intel_helper_funcs = {
12668         .mode_set_base_atomic = intel_pipe_set_base_atomic,
12669         .atomic_begin = intel_begin_crtc_commit,
12670         .atomic_flush = intel_finish_crtc_commit,
12671         .atomic_check = intel_crtc_atomic_check,
12672 };
12673
12674 static void intel_modeset_update_connector_atomic_state(struct drm_device *dev)
12675 {
12676         struct intel_connector *connector;
12677
12678         for_each_intel_connector(dev, connector) {
12679                 if (connector->base.state->crtc)
12680                         drm_connector_unreference(&connector->base);
12681
12682                 if (connector->base.encoder) {
12683                         connector->base.state->best_encoder =
12684                                 connector->base.encoder;
12685                         connector->base.state->crtc =
12686                                 connector->base.encoder->crtc;
12687
12688                         drm_connector_reference(&connector->base);
12689                 } else {
12690                         connector->base.state->best_encoder = NULL;
12691                         connector->base.state->crtc = NULL;
12692                 }
12693         }
12694 }
12695
12696 static void
12697 connected_sink_compute_bpp(struct intel_connector *connector,
12698                            struct intel_crtc_state *pipe_config)
12699 {
12700         const struct drm_display_info *info = &connector->base.display_info;
12701         int bpp = pipe_config->pipe_bpp;
12702
12703         DRM_DEBUG_KMS("[CONNECTOR:%d:%s] checking for sink bpp constrains\n",
12704                       connector->base.base.id,
12705                       connector->base.name);
12706
12707         /* Don't use an invalid EDID bpc value */
12708         if (info->bpc != 0 && info->bpc * 3 < bpp) {
12709                 DRM_DEBUG_KMS("clamping display bpp (was %d) to EDID reported max of %d\n",
12710                               bpp, info->bpc * 3);
12711                 pipe_config->pipe_bpp = info->bpc * 3;
12712         }
12713
12714         /* Clamp bpp to 8 on screens without EDID 1.4 */
12715         if (info->bpc == 0 && bpp > 24) {
12716                 DRM_DEBUG_KMS("clamping display bpp (was %d) to default limit of 24\n",
12717                               bpp);
12718                 pipe_config->pipe_bpp = 24;
12719         }
12720 }
12721
12722 static int
12723 compute_baseline_pipe_bpp(struct intel_crtc *crtc,
12724                           struct intel_crtc_state *pipe_config)
12725 {
12726         struct drm_device *dev = crtc->base.dev;
12727         struct drm_atomic_state *state;
12728         struct drm_connector *connector;
12729         struct drm_connector_state *connector_state;
12730         int bpp, i;
12731
12732         if ((IS_G4X(dev) || IS_VALLEYVIEW(dev) || IS_CHERRYVIEW(dev)))
12733                 bpp = 10*3;
12734         else if (INTEL_INFO(dev)->gen >= 5)
12735                 bpp = 12*3;
12736         else
12737                 bpp = 8*3;
12738
12739
12740         pipe_config->pipe_bpp = bpp;
12741
12742         state = pipe_config->base.state;
12743
12744         /* Clamp display bpp to EDID value */
12745         for_each_connector_in_state(state, connector, connector_state, i) {
12746                 if (connector_state->crtc != &crtc->base)
12747                         continue;
12748
12749                 connected_sink_compute_bpp(to_intel_connector(connector),
12750                                            pipe_config);
12751         }
12752
12753         return bpp;
12754 }
12755
12756 static void intel_dump_crtc_timings(const struct drm_display_mode *mode)
12757 {
12758         DRM_DEBUG_KMS("crtc timings: %d %d %d %d %d %d %d %d %d, "
12759                         "type: 0x%x flags: 0x%x\n",
12760                 mode->crtc_clock,
12761                 mode->crtc_hdisplay, mode->crtc_hsync_start,
12762                 mode->crtc_hsync_end, mode->crtc_htotal,
12763                 mode->crtc_vdisplay, mode->crtc_vsync_start,
12764                 mode->crtc_vsync_end, mode->crtc_vtotal, mode->type, mode->flags);
12765 }
12766
12767 static void intel_dump_pipe_config(struct intel_crtc *crtc,
12768                                    struct intel_crtc_state *pipe_config,
12769                                    const char *context)
12770 {
12771         struct drm_device *dev = crtc->base.dev;
12772         struct drm_plane *plane;
12773         struct intel_plane *intel_plane;
12774         struct intel_plane_state *state;
12775         struct drm_framebuffer *fb;
12776
12777         DRM_DEBUG_KMS("[CRTC:%d:%s]%s config %p for pipe %c\n",
12778                       crtc->base.base.id, crtc->base.name,
12779                       context, pipe_config, pipe_name(crtc->pipe));
12780
12781         DRM_DEBUG_KMS("cpu_transcoder: %s\n", transcoder_name(pipe_config->cpu_transcoder));
12782         DRM_DEBUG_KMS("pipe bpp: %i, dithering: %i\n",
12783                       pipe_config->pipe_bpp, pipe_config->dither);
12784         DRM_DEBUG_KMS("fdi/pch: %i, lanes: %i, gmch_m: %u, gmch_n: %u, link_m: %u, link_n: %u, tu: %u\n",
12785                       pipe_config->has_pch_encoder,
12786                       pipe_config->fdi_lanes,
12787                       pipe_config->fdi_m_n.gmch_m, pipe_config->fdi_m_n.gmch_n,
12788                       pipe_config->fdi_m_n.link_m, pipe_config->fdi_m_n.link_n,
12789                       pipe_config->fdi_m_n.tu);
12790         DRM_DEBUG_KMS("dp: %i, lanes: %i, gmch_m: %u, gmch_n: %u, link_m: %u, link_n: %u, tu: %u\n",
12791                       intel_crtc_has_dp_encoder(pipe_config),
12792                       pipe_config->lane_count,
12793                       pipe_config->dp_m_n.gmch_m, pipe_config->dp_m_n.gmch_n,
12794                       pipe_config->dp_m_n.link_m, pipe_config->dp_m_n.link_n,
12795                       pipe_config->dp_m_n.tu);
12796
12797         DRM_DEBUG_KMS("dp: %i, lanes: %i, gmch_m2: %u, gmch_n2: %u, link_m2: %u, link_n2: %u, tu2: %u\n",
12798                       intel_crtc_has_dp_encoder(pipe_config),
12799                       pipe_config->lane_count,
12800                       pipe_config->dp_m2_n2.gmch_m,
12801                       pipe_config->dp_m2_n2.gmch_n,
12802                       pipe_config->dp_m2_n2.link_m,
12803                       pipe_config->dp_m2_n2.link_n,
12804                       pipe_config->dp_m2_n2.tu);
12805
12806         DRM_DEBUG_KMS("audio: %i, infoframes: %i\n",
12807                       pipe_config->has_audio,
12808                       pipe_config->has_infoframe);
12809
12810         DRM_DEBUG_KMS("requested mode:\n");
12811         drm_mode_debug_printmodeline(&pipe_config->base.mode);
12812         DRM_DEBUG_KMS("adjusted mode:\n");
12813         drm_mode_debug_printmodeline(&pipe_config->base.adjusted_mode);
12814         intel_dump_crtc_timings(&pipe_config->base.adjusted_mode);
12815         DRM_DEBUG_KMS("port clock: %d\n", pipe_config->port_clock);
12816         DRM_DEBUG_KMS("pipe src size: %dx%d\n",
12817                       pipe_config->pipe_src_w, pipe_config->pipe_src_h);
12818         DRM_DEBUG_KMS("num_scalers: %d, scaler_users: 0x%x, scaler_id: %d\n",
12819                       crtc->num_scalers,
12820                       pipe_config->scaler_state.scaler_users,
12821                       pipe_config->scaler_state.scaler_id);
12822         DRM_DEBUG_KMS("gmch pfit: control: 0x%08x, ratios: 0x%08x, lvds border: 0x%08x\n",
12823                       pipe_config->gmch_pfit.control,
12824                       pipe_config->gmch_pfit.pgm_ratios,
12825                       pipe_config->gmch_pfit.lvds_border_bits);
12826         DRM_DEBUG_KMS("pch pfit: pos: 0x%08x, size: 0x%08x, %s\n",
12827                       pipe_config->pch_pfit.pos,
12828                       pipe_config->pch_pfit.size,
12829                       pipe_config->pch_pfit.enabled ? "enabled" : "disabled");
12830         DRM_DEBUG_KMS("ips: %i\n", pipe_config->ips_enabled);
12831         DRM_DEBUG_KMS("double wide: %i\n", pipe_config->double_wide);
12832
12833         if (IS_BROXTON(dev)) {
12834                 DRM_DEBUG_KMS("dpll_hw_state: ebb0: 0x%x, ebb4: 0x%x,"
12835                               "pll0: 0x%x, pll1: 0x%x, pll2: 0x%x, pll3: 0x%x, "
12836                               "pll6: 0x%x, pll8: 0x%x, pll9: 0x%x, pll10: 0x%x, pcsdw12: 0x%x\n",
12837                               pipe_config->dpll_hw_state.ebb0,
12838                               pipe_config->dpll_hw_state.ebb4,
12839                               pipe_config->dpll_hw_state.pll0,
12840                               pipe_config->dpll_hw_state.pll1,
12841                               pipe_config->dpll_hw_state.pll2,
12842                               pipe_config->dpll_hw_state.pll3,
12843                               pipe_config->dpll_hw_state.pll6,
12844                               pipe_config->dpll_hw_state.pll8,
12845                               pipe_config->dpll_hw_state.pll9,
12846                               pipe_config->dpll_hw_state.pll10,
12847                               pipe_config->dpll_hw_state.pcsdw12);
12848         } else if (IS_SKYLAKE(dev) || IS_KABYLAKE(dev)) {
12849                 DRM_DEBUG_KMS("dpll_hw_state: "
12850                               "ctrl1: 0x%x, cfgcr1: 0x%x, cfgcr2: 0x%x\n",
12851                               pipe_config->dpll_hw_state.ctrl1,
12852                               pipe_config->dpll_hw_state.cfgcr1,
12853                               pipe_config->dpll_hw_state.cfgcr2);
12854         } else if (HAS_DDI(dev)) {
12855                 DRM_DEBUG_KMS("dpll_hw_state: wrpll: 0x%x spll: 0x%x\n",
12856                               pipe_config->dpll_hw_state.wrpll,
12857                               pipe_config->dpll_hw_state.spll);
12858         } else {
12859                 DRM_DEBUG_KMS("dpll_hw_state: dpll: 0x%x, dpll_md: 0x%x, "
12860                               "fp0: 0x%x, fp1: 0x%x\n",
12861                               pipe_config->dpll_hw_state.dpll,
12862                               pipe_config->dpll_hw_state.dpll_md,
12863                               pipe_config->dpll_hw_state.fp0,
12864                               pipe_config->dpll_hw_state.fp1);
12865         }
12866
12867         DRM_DEBUG_KMS("planes on this crtc\n");
12868         list_for_each_entry(plane, &dev->mode_config.plane_list, head) {
12869                 char *format_name;
12870                 intel_plane = to_intel_plane(plane);
12871                 if (intel_plane->pipe != crtc->pipe)
12872                         continue;
12873
12874                 state = to_intel_plane_state(plane->state);
12875                 fb = state->base.fb;
12876                 if (!fb) {
12877                         DRM_DEBUG_KMS("[PLANE:%d:%s] disabled, scaler_id = %d\n",
12878                                       plane->base.id, plane->name, state->scaler_id);
12879                         continue;
12880                 }
12881
12882                 format_name = drm_get_format_name(fb->pixel_format);
12883
12884                 DRM_DEBUG_KMS("[PLANE:%d:%s] enabled",
12885                               plane->base.id, plane->name);
12886                 DRM_DEBUG_KMS("\tFB:%d, fb = %ux%u format = %s",
12887                               fb->base.id, fb->width, fb->height, format_name);
12888                 DRM_DEBUG_KMS("\tscaler:%d src %dx%d+%d+%d dst %dx%d+%d+%d\n",
12889                               state->scaler_id,
12890                               state->base.src.x1 >> 16,
12891                               state->base.src.y1 >> 16,
12892                               drm_rect_width(&state->base.src) >> 16,
12893                               drm_rect_height(&state->base.src) >> 16,
12894                               state->base.dst.x1, state->base.dst.y1,
12895                               drm_rect_width(&state->base.dst),
12896                               drm_rect_height(&state->base.dst));
12897
12898                 kfree(format_name);
12899         }
12900 }
12901
12902 static bool check_digital_port_conflicts(struct drm_atomic_state *state)
12903 {
12904         struct drm_device *dev = state->dev;
12905         struct drm_connector *connector;
12906         unsigned int used_ports = 0;
12907         unsigned int used_mst_ports = 0;
12908
12909         /*
12910          * Walk the connector list instead of the encoder
12911          * list to detect the problem on ddi platforms
12912          * where there's just one encoder per digital port.
12913          */
12914         drm_for_each_connector(connector, dev) {
12915                 struct drm_connector_state *connector_state;
12916                 struct intel_encoder *encoder;
12917
12918                 connector_state = drm_atomic_get_existing_connector_state(state, connector);
12919                 if (!connector_state)
12920                         connector_state = connector->state;
12921
12922                 if (!connector_state->best_encoder)
12923                         continue;
12924
12925                 encoder = to_intel_encoder(connector_state->best_encoder);
12926
12927                 WARN_ON(!connector_state->crtc);
12928
12929                 switch (encoder->type) {
12930                         unsigned int port_mask;
12931                 case INTEL_OUTPUT_UNKNOWN:
12932                         if (WARN_ON(!HAS_DDI(dev)))
12933                                 break;
12934                 case INTEL_OUTPUT_DP:
12935                 case INTEL_OUTPUT_HDMI:
12936                 case INTEL_OUTPUT_EDP:
12937                         port_mask = 1 << enc_to_dig_port(&encoder->base)->port;
12938
12939                         /* the same port mustn't appear more than once */
12940                         if (used_ports & port_mask)
12941                                 return false;
12942
12943                         used_ports |= port_mask;
12944                         break;
12945                 case INTEL_OUTPUT_DP_MST:
12946                         used_mst_ports |=
12947                                 1 << enc_to_mst(&encoder->base)->primary->port;
12948                         break;
12949                 default:
12950                         break;
12951                 }
12952         }
12953
12954         /* can't mix MST and SST/HDMI on the same port */
12955         if (used_ports & used_mst_ports)
12956                 return false;
12957
12958         return true;
12959 }
12960
12961 static void
12962 clear_intel_crtc_state(struct intel_crtc_state *crtc_state)
12963 {
12964         struct drm_crtc_state tmp_state;
12965         struct intel_crtc_scaler_state scaler_state;
12966         struct intel_dpll_hw_state dpll_hw_state;
12967         struct intel_shared_dpll *shared_dpll;
12968         bool force_thru;
12969
12970         /* FIXME: before the switch to atomic started, a new pipe_config was
12971          * kzalloc'd. Code that depends on any field being zero should be
12972          * fixed, so that the crtc_state can be safely duplicated. For now,
12973          * only fields that are know to not cause problems are preserved. */
12974
12975         tmp_state = crtc_state->base;
12976         scaler_state = crtc_state->scaler_state;
12977         shared_dpll = crtc_state->shared_dpll;
12978         dpll_hw_state = crtc_state->dpll_hw_state;
12979         force_thru = crtc_state->pch_pfit.force_thru;
12980
12981         memset(crtc_state, 0, sizeof *crtc_state);
12982
12983         crtc_state->base = tmp_state;
12984         crtc_state->scaler_state = scaler_state;
12985         crtc_state->shared_dpll = shared_dpll;
12986         crtc_state->dpll_hw_state = dpll_hw_state;
12987         crtc_state->pch_pfit.force_thru = force_thru;
12988 }
12989
12990 static int
12991 intel_modeset_pipe_config(struct drm_crtc *crtc,
12992                           struct intel_crtc_state *pipe_config)
12993 {
12994         struct drm_atomic_state *state = pipe_config->base.state;
12995         struct intel_encoder *encoder;
12996         struct drm_connector *connector;
12997         struct drm_connector_state *connector_state;
12998         int base_bpp, ret = -EINVAL;
12999         int i;
13000         bool retry = true;
13001
13002         clear_intel_crtc_state(pipe_config);
13003
13004         pipe_config->cpu_transcoder =
13005                 (enum transcoder) to_intel_crtc(crtc)->pipe;
13006
13007         /*
13008          * Sanitize sync polarity flags based on requested ones. If neither
13009          * positive or negative polarity is requested, treat this as meaning
13010          * negative polarity.
13011          */
13012         if (!(pipe_config->base.adjusted_mode.flags &
13013               (DRM_MODE_FLAG_PHSYNC | DRM_MODE_FLAG_NHSYNC)))
13014                 pipe_config->base.adjusted_mode.flags |= DRM_MODE_FLAG_NHSYNC;
13015
13016         if (!(pipe_config->base.adjusted_mode.flags &
13017               (DRM_MODE_FLAG_PVSYNC | DRM_MODE_FLAG_NVSYNC)))
13018                 pipe_config->base.adjusted_mode.flags |= DRM_MODE_FLAG_NVSYNC;
13019
13020         base_bpp = compute_baseline_pipe_bpp(to_intel_crtc(crtc),
13021                                              pipe_config);
13022         if (base_bpp < 0)
13023                 goto fail;
13024
13025         /*
13026          * Determine the real pipe dimensions. Note that stereo modes can
13027          * increase the actual pipe size due to the frame doubling and
13028          * insertion of additional space for blanks between the frame. This
13029          * is stored in the crtc timings. We use the requested mode to do this
13030          * computation to clearly distinguish it from the adjusted mode, which
13031          * can be changed by the connectors in the below retry loop.
13032          */
13033         drm_crtc_get_hv_timing(&pipe_config->base.mode,
13034                                &pipe_config->pipe_src_w,
13035                                &pipe_config->pipe_src_h);
13036
13037         for_each_connector_in_state(state, connector, connector_state, i) {
13038                 if (connector_state->crtc != crtc)
13039                         continue;
13040
13041                 encoder = to_intel_encoder(connector_state->best_encoder);
13042
13043                 if (!check_single_encoder_cloning(state, to_intel_crtc(crtc), encoder)) {
13044                         DRM_DEBUG_KMS("rejecting invalid cloning configuration\n");
13045                         goto fail;
13046                 }
13047
13048                 /*
13049                  * Determine output_types before calling the .compute_config()
13050                  * hooks so that the hooks can use this information safely.
13051                  */
13052                 pipe_config->output_types |= 1 << encoder->type;
13053         }
13054
13055 encoder_retry:
13056         /* Ensure the port clock defaults are reset when retrying. */
13057         pipe_config->port_clock = 0;
13058         pipe_config->pixel_multiplier = 1;
13059
13060         /* Fill in default crtc timings, allow encoders to overwrite them. */
13061         drm_mode_set_crtcinfo(&pipe_config->base.adjusted_mode,
13062                               CRTC_STEREO_DOUBLE);
13063
13064         /* Pass our mode to the connectors and the CRTC to give them a chance to
13065          * adjust it according to limitations or connector properties, and also
13066          * a chance to reject the mode entirely.
13067          */
13068         for_each_connector_in_state(state, connector, connector_state, i) {
13069                 if (connector_state->crtc != crtc)
13070                         continue;
13071
13072                 encoder = to_intel_encoder(connector_state->best_encoder);
13073
13074                 if (!(encoder->compute_config(encoder, pipe_config, connector_state))) {
13075                         DRM_DEBUG_KMS("Encoder config failure\n");
13076                         goto fail;
13077                 }
13078         }
13079
13080         /* Set default port clock if not overwritten by the encoder. Needs to be
13081          * done afterwards in case the encoder adjusts the mode. */
13082         if (!pipe_config->port_clock)
13083                 pipe_config->port_clock = pipe_config->base.adjusted_mode.crtc_clock
13084                         * pipe_config->pixel_multiplier;
13085
13086         ret = intel_crtc_compute_config(to_intel_crtc(crtc), pipe_config);
13087         if (ret < 0) {
13088                 DRM_DEBUG_KMS("CRTC fixup failed\n");
13089                 goto fail;
13090         }
13091
13092         if (ret == RETRY) {
13093                 if (WARN(!retry, "loop in pipe configuration computation\n")) {
13094                         ret = -EINVAL;
13095                         goto fail;
13096                 }
13097
13098                 DRM_DEBUG_KMS("CRTC bw constrained, retrying\n");
13099                 retry = false;
13100                 goto encoder_retry;
13101         }
13102
13103         /* Dithering seems to not pass-through bits correctly when it should, so
13104          * only enable it on 6bpc panels. */
13105         pipe_config->dither = pipe_config->pipe_bpp == 6*3;
13106         DRM_DEBUG_KMS("hw max bpp: %i, pipe bpp: %i, dithering: %i\n",
13107                       base_bpp, pipe_config->pipe_bpp, pipe_config->dither);
13108
13109 fail:
13110         return ret;
13111 }
13112
13113 static void
13114 intel_modeset_update_crtc_state(struct drm_atomic_state *state)
13115 {
13116         struct drm_crtc *crtc;
13117         struct drm_crtc_state *crtc_state;
13118         int i;
13119
13120         /* Double check state. */
13121         for_each_crtc_in_state(state, crtc, crtc_state, i) {
13122                 to_intel_crtc(crtc)->config = to_intel_crtc_state(crtc->state);
13123
13124                 /* Update hwmode for vblank functions */
13125                 if (crtc->state->active)
13126                         crtc->hwmode = crtc->state->adjusted_mode;
13127                 else
13128                         crtc->hwmode.crtc_clock = 0;
13129
13130                 /*
13131                  * Update legacy state to satisfy fbc code. This can
13132                  * be removed when fbc uses the atomic state.
13133                  */
13134                 if (drm_atomic_get_existing_plane_state(state, crtc->primary)) {
13135                         struct drm_plane_state *plane_state = crtc->primary->state;
13136
13137                         crtc->primary->fb = plane_state->fb;
13138                         crtc->x = plane_state->src_x >> 16;
13139                         crtc->y = plane_state->src_y >> 16;
13140                 }
13141         }
13142 }
13143
13144 static bool intel_fuzzy_clock_check(int clock1, int clock2)
13145 {
13146         int diff;
13147
13148         if (clock1 == clock2)
13149                 return true;
13150
13151         if (!clock1 || !clock2)
13152                 return false;
13153
13154         diff = abs(clock1 - clock2);
13155
13156         if (((((diff + clock1 + clock2) * 100)) / (clock1 + clock2)) < 105)
13157                 return true;
13158
13159         return false;
13160 }
13161
13162 static bool
13163 intel_compare_m_n(unsigned int m, unsigned int n,
13164                   unsigned int m2, unsigned int n2,
13165                   bool exact)
13166 {
13167         if (m == m2 && n == n2)
13168                 return true;
13169
13170         if (exact || !m || !n || !m2 || !n2)
13171                 return false;
13172
13173         BUILD_BUG_ON(DATA_LINK_M_N_MASK > INT_MAX);
13174
13175         if (n > n2) {
13176                 while (n > n2) {
13177                         m2 <<= 1;
13178                         n2 <<= 1;
13179                 }
13180         } else if (n < n2) {
13181                 while (n < n2) {
13182                         m <<= 1;
13183                         n <<= 1;
13184                 }
13185         }
13186
13187         if (n != n2)
13188                 return false;
13189
13190         return intel_fuzzy_clock_check(m, m2);
13191 }
13192
13193 static bool
13194 intel_compare_link_m_n(const struct intel_link_m_n *m_n,
13195                        struct intel_link_m_n *m2_n2,
13196                        bool adjust)
13197 {
13198         if (m_n->tu == m2_n2->tu &&
13199             intel_compare_m_n(m_n->gmch_m, m_n->gmch_n,
13200                               m2_n2->gmch_m, m2_n2->gmch_n, !adjust) &&
13201             intel_compare_m_n(m_n->link_m, m_n->link_n,
13202                               m2_n2->link_m, m2_n2->link_n, !adjust)) {
13203                 if (adjust)
13204                         *m2_n2 = *m_n;
13205
13206                 return true;
13207         }
13208
13209         return false;
13210 }
13211
13212 static bool
13213 intel_pipe_config_compare(struct drm_device *dev,
13214                           struct intel_crtc_state *current_config,
13215                           struct intel_crtc_state *pipe_config,
13216                           bool adjust)
13217 {
13218         bool ret = true;
13219
13220 #define INTEL_ERR_OR_DBG_KMS(fmt, ...) \
13221         do { \
13222                 if (!adjust) \
13223                         DRM_ERROR(fmt, ##__VA_ARGS__); \
13224                 else \
13225                         DRM_DEBUG_KMS(fmt, ##__VA_ARGS__); \
13226         } while (0)
13227
13228 #define PIPE_CONF_CHECK_X(name) \
13229         if (current_config->name != pipe_config->name) { \
13230                 INTEL_ERR_OR_DBG_KMS("mismatch in " #name " " \
13231                           "(expected 0x%08x, found 0x%08x)\n", \
13232                           current_config->name, \
13233                           pipe_config->name); \
13234                 ret = false; \
13235         }
13236
13237 #define PIPE_CONF_CHECK_I(name) \
13238         if (current_config->name != pipe_config->name) { \
13239                 INTEL_ERR_OR_DBG_KMS("mismatch in " #name " " \
13240                           "(expected %i, found %i)\n", \
13241                           current_config->name, \
13242                           pipe_config->name); \
13243                 ret = false; \
13244         }
13245
13246 #define PIPE_CONF_CHECK_P(name) \
13247         if (current_config->name != pipe_config->name) { \
13248                 INTEL_ERR_OR_DBG_KMS("mismatch in " #name " " \
13249                           "(expected %p, found %p)\n", \
13250                           current_config->name, \
13251                           pipe_config->name); \
13252                 ret = false; \
13253         }
13254
13255 #define PIPE_CONF_CHECK_M_N(name) \
13256         if (!intel_compare_link_m_n(&current_config->name, \
13257                                     &pipe_config->name,\
13258                                     adjust)) { \
13259                 INTEL_ERR_OR_DBG_KMS("mismatch in " #name " " \
13260                           "(expected tu %i gmch %i/%i link %i/%i, " \
13261                           "found tu %i, gmch %i/%i link %i/%i)\n", \
13262                           current_config->name.tu, \
13263                           current_config->name.gmch_m, \
13264                           current_config->name.gmch_n, \
13265                           current_config->name.link_m, \
13266                           current_config->name.link_n, \
13267                           pipe_config->name.tu, \
13268                           pipe_config->name.gmch_m, \
13269                           pipe_config->name.gmch_n, \
13270                           pipe_config->name.link_m, \
13271                           pipe_config->name.link_n); \
13272                 ret = false; \
13273         }
13274
13275 /* This is required for BDW+ where there is only one set of registers for
13276  * switching between high and low RR.
13277  * This macro can be used whenever a comparison has to be made between one
13278  * hw state and multiple sw state variables.
13279  */
13280 #define PIPE_CONF_CHECK_M_N_ALT(name, alt_name) \
13281         if (!intel_compare_link_m_n(&current_config->name, \
13282                                     &pipe_config->name, adjust) && \
13283             !intel_compare_link_m_n(&current_config->alt_name, \
13284                                     &pipe_config->name, adjust)) { \
13285                 INTEL_ERR_OR_DBG_KMS("mismatch in " #name " " \
13286                           "(expected tu %i gmch %i/%i link %i/%i, " \
13287                           "or tu %i gmch %i/%i link %i/%i, " \
13288                           "found tu %i, gmch %i/%i link %i/%i)\n", \
13289                           current_config->name.tu, \
13290                           current_config->name.gmch_m, \
13291                           current_config->name.gmch_n, \
13292                           current_config->name.link_m, \
13293                           current_config->name.link_n, \
13294                           current_config->alt_name.tu, \
13295                           current_config->alt_name.gmch_m, \
13296                           current_config->alt_name.gmch_n, \
13297                           current_config->alt_name.link_m, \
13298                           current_config->alt_name.link_n, \
13299                           pipe_config->name.tu, \
13300                           pipe_config->name.gmch_m, \
13301                           pipe_config->name.gmch_n, \
13302                           pipe_config->name.link_m, \
13303                           pipe_config->name.link_n); \
13304                 ret = false; \
13305         }
13306
13307 #define PIPE_CONF_CHECK_FLAGS(name, mask)       \
13308         if ((current_config->name ^ pipe_config->name) & (mask)) { \
13309                 INTEL_ERR_OR_DBG_KMS("mismatch in " #name "(" #mask ") " \
13310                           "(expected %i, found %i)\n", \
13311                           current_config->name & (mask), \
13312                           pipe_config->name & (mask)); \
13313                 ret = false; \
13314         }
13315
13316 #define PIPE_CONF_CHECK_CLOCK_FUZZY(name) \
13317         if (!intel_fuzzy_clock_check(current_config->name, pipe_config->name)) { \
13318                 INTEL_ERR_OR_DBG_KMS("mismatch in " #name " " \
13319                           "(expected %i, found %i)\n", \
13320                           current_config->name, \
13321                           pipe_config->name); \
13322                 ret = false; \
13323         }
13324
13325 #define PIPE_CONF_QUIRK(quirk)  \
13326         ((current_config->quirks | pipe_config->quirks) & (quirk))
13327
13328         PIPE_CONF_CHECK_I(cpu_transcoder);
13329
13330         PIPE_CONF_CHECK_I(has_pch_encoder);
13331         PIPE_CONF_CHECK_I(fdi_lanes);
13332         PIPE_CONF_CHECK_M_N(fdi_m_n);
13333
13334         PIPE_CONF_CHECK_I(lane_count);
13335         PIPE_CONF_CHECK_X(lane_lat_optim_mask);
13336
13337         if (INTEL_INFO(dev)->gen < 8) {
13338                 PIPE_CONF_CHECK_M_N(dp_m_n);
13339
13340                 if (current_config->has_drrs)
13341                         PIPE_CONF_CHECK_M_N(dp_m2_n2);
13342         } else
13343                 PIPE_CONF_CHECK_M_N_ALT(dp_m_n, dp_m2_n2);
13344
13345         PIPE_CONF_CHECK_X(output_types);
13346
13347         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hdisplay);
13348         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_htotal);
13349         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hblank_start);
13350         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hblank_end);
13351         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hsync_start);
13352         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hsync_end);
13353
13354         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vdisplay);
13355         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vtotal);
13356         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vblank_start);
13357         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vblank_end);
13358         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vsync_start);
13359         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vsync_end);
13360
13361         PIPE_CONF_CHECK_I(pixel_multiplier);
13362         PIPE_CONF_CHECK_I(has_hdmi_sink);
13363         if ((INTEL_INFO(dev)->gen < 8 && !IS_HASWELL(dev)) ||
13364             IS_VALLEYVIEW(dev) || IS_CHERRYVIEW(dev))
13365                 PIPE_CONF_CHECK_I(limited_color_range);
13366         PIPE_CONF_CHECK_I(has_infoframe);
13367
13368         PIPE_CONF_CHECK_I(has_audio);
13369
13370         PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
13371                               DRM_MODE_FLAG_INTERLACE);
13372
13373         if (!PIPE_CONF_QUIRK(PIPE_CONFIG_QUIRK_MODE_SYNC_FLAGS)) {
13374                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
13375                                       DRM_MODE_FLAG_PHSYNC);
13376                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
13377                                       DRM_MODE_FLAG_NHSYNC);
13378                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
13379                                       DRM_MODE_FLAG_PVSYNC);
13380                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
13381                                       DRM_MODE_FLAG_NVSYNC);
13382         }
13383
13384         PIPE_CONF_CHECK_X(gmch_pfit.control);
13385         /* pfit ratios are autocomputed by the hw on gen4+ */
13386         if (INTEL_INFO(dev)->gen < 4)
13387                 PIPE_CONF_CHECK_X(gmch_pfit.pgm_ratios);
13388         PIPE_CONF_CHECK_X(gmch_pfit.lvds_border_bits);
13389
13390         if (!adjust) {
13391                 PIPE_CONF_CHECK_I(pipe_src_w);
13392                 PIPE_CONF_CHECK_I(pipe_src_h);
13393
13394                 PIPE_CONF_CHECK_I(pch_pfit.enabled);
13395                 if (current_config->pch_pfit.enabled) {
13396                         PIPE_CONF_CHECK_X(pch_pfit.pos);
13397                         PIPE_CONF_CHECK_X(pch_pfit.size);
13398                 }
13399
13400                 PIPE_CONF_CHECK_I(scaler_state.scaler_id);
13401         }
13402
13403         /* BDW+ don't expose a synchronous way to read the state */
13404         if (IS_HASWELL(dev))
13405                 PIPE_CONF_CHECK_I(ips_enabled);
13406
13407         PIPE_CONF_CHECK_I(double_wide);
13408
13409         PIPE_CONF_CHECK_P(shared_dpll);
13410         PIPE_CONF_CHECK_X(dpll_hw_state.dpll);
13411         PIPE_CONF_CHECK_X(dpll_hw_state.dpll_md);
13412         PIPE_CONF_CHECK_X(dpll_hw_state.fp0);
13413         PIPE_CONF_CHECK_X(dpll_hw_state.fp1);
13414         PIPE_CONF_CHECK_X(dpll_hw_state.wrpll);
13415         PIPE_CONF_CHECK_X(dpll_hw_state.spll);
13416         PIPE_CONF_CHECK_X(dpll_hw_state.ctrl1);
13417         PIPE_CONF_CHECK_X(dpll_hw_state.cfgcr1);
13418         PIPE_CONF_CHECK_X(dpll_hw_state.cfgcr2);
13419
13420         PIPE_CONF_CHECK_X(dsi_pll.ctrl);
13421         PIPE_CONF_CHECK_X(dsi_pll.div);
13422
13423         if (IS_G4X(dev) || INTEL_INFO(dev)->gen >= 5)
13424                 PIPE_CONF_CHECK_I(pipe_bpp);
13425
13426         PIPE_CONF_CHECK_CLOCK_FUZZY(base.adjusted_mode.crtc_clock);
13427         PIPE_CONF_CHECK_CLOCK_FUZZY(port_clock);
13428
13429 #undef PIPE_CONF_CHECK_X
13430 #undef PIPE_CONF_CHECK_I
13431 #undef PIPE_CONF_CHECK_P
13432 #undef PIPE_CONF_CHECK_FLAGS
13433 #undef PIPE_CONF_CHECK_CLOCK_FUZZY
13434 #undef PIPE_CONF_QUIRK
13435 #undef INTEL_ERR_OR_DBG_KMS
13436
13437         return ret;
13438 }
13439
13440 static void intel_pipe_config_sanity_check(struct drm_i915_private *dev_priv,
13441                                            const struct intel_crtc_state *pipe_config)
13442 {
13443         if (pipe_config->has_pch_encoder) {
13444                 int fdi_dotclock = intel_dotclock_calculate(intel_fdi_link_freq(dev_priv, pipe_config),
13445                                                             &pipe_config->fdi_m_n);
13446                 int dotclock = pipe_config->base.adjusted_mode.crtc_clock;
13447
13448                 /*
13449                  * FDI already provided one idea for the dotclock.
13450                  * Yell if the encoder disagrees.
13451                  */
13452                 WARN(!intel_fuzzy_clock_check(fdi_dotclock, dotclock),
13453                      "FDI dotclock and encoder dotclock mismatch, fdi: %i, encoder: %i\n",
13454                      fdi_dotclock, dotclock);
13455         }
13456 }
13457
13458 static void verify_wm_state(struct drm_crtc *crtc,
13459                             struct drm_crtc_state *new_state)
13460 {
13461         struct drm_device *dev = crtc->dev;
13462         struct drm_i915_private *dev_priv = to_i915(dev);
13463         struct skl_ddb_allocation hw_ddb, *sw_ddb;
13464         struct skl_ddb_entry *hw_entry, *sw_entry;
13465         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
13466         const enum pipe pipe = intel_crtc->pipe;
13467         int plane;
13468
13469         if (INTEL_INFO(dev)->gen < 9 || !new_state->active)
13470                 return;
13471
13472         skl_ddb_get_hw_state(dev_priv, &hw_ddb);
13473         sw_ddb = &dev_priv->wm.skl_hw.ddb;
13474
13475         /* planes */
13476         for_each_plane(dev_priv, pipe, plane) {
13477                 hw_entry = &hw_ddb.plane[pipe][plane];
13478                 sw_entry = &sw_ddb->plane[pipe][plane];
13479
13480                 if (skl_ddb_entry_equal(hw_entry, sw_entry))
13481                         continue;
13482
13483                 DRM_ERROR("mismatch in DDB state pipe %c plane %d "
13484                           "(expected (%u,%u), found (%u,%u))\n",
13485                           pipe_name(pipe), plane + 1,
13486                           sw_entry->start, sw_entry->end,
13487                           hw_entry->start, hw_entry->end);
13488         }
13489
13490         /*
13491          * cursor
13492          * If the cursor plane isn't active, we may not have updated it's ddb
13493          * allocation. In that case since the ddb allocation will be updated
13494          * once the plane becomes visible, we can skip this check
13495          */
13496         if (intel_crtc->cursor_addr) {
13497                 hw_entry = &hw_ddb.plane[pipe][PLANE_CURSOR];
13498                 sw_entry = &sw_ddb->plane[pipe][PLANE_CURSOR];
13499
13500                 if (!skl_ddb_entry_equal(hw_entry, sw_entry)) {
13501                         DRM_ERROR("mismatch in DDB state pipe %c cursor "
13502                                   "(expected (%u,%u), found (%u,%u))\n",
13503                                   pipe_name(pipe),
13504                                   sw_entry->start, sw_entry->end,
13505                                   hw_entry->start, hw_entry->end);
13506                 }
13507         }
13508 }
13509
13510 static void
13511 verify_connector_state(struct drm_device *dev, struct drm_crtc *crtc)
13512 {
13513         struct drm_connector *connector;
13514
13515         drm_for_each_connector(connector, dev) {
13516                 struct drm_encoder *encoder = connector->encoder;
13517                 struct drm_connector_state *state = connector->state;
13518
13519                 if (state->crtc != crtc)
13520                         continue;
13521
13522                 intel_connector_verify_state(to_intel_connector(connector));
13523
13524                 I915_STATE_WARN(state->best_encoder != encoder,
13525                      "connector's atomic encoder doesn't match legacy encoder\n");
13526         }
13527 }
13528
13529 static void
13530 verify_encoder_state(struct drm_device *dev)
13531 {
13532         struct intel_encoder *encoder;
13533         struct intel_connector *connector;
13534
13535         for_each_intel_encoder(dev, encoder) {
13536                 bool enabled = false;
13537                 enum pipe pipe;
13538
13539                 DRM_DEBUG_KMS("[ENCODER:%d:%s]\n",
13540                               encoder->base.base.id,
13541                               encoder->base.name);
13542
13543                 for_each_intel_connector(dev, connector) {
13544                         if (connector->base.state->best_encoder != &encoder->base)
13545                                 continue;
13546                         enabled = true;
13547
13548                         I915_STATE_WARN(connector->base.state->crtc !=
13549                                         encoder->base.crtc,
13550                              "connector's crtc doesn't match encoder crtc\n");
13551                 }
13552
13553                 I915_STATE_WARN(!!encoder->base.crtc != enabled,
13554                      "encoder's enabled state mismatch "
13555                      "(expected %i, found %i)\n",
13556                      !!encoder->base.crtc, enabled);
13557
13558                 if (!encoder->base.crtc) {
13559                         bool active;
13560
13561                         active = encoder->get_hw_state(encoder, &pipe);
13562                         I915_STATE_WARN(active,
13563                              "encoder detached but still enabled on pipe %c.\n",
13564                              pipe_name(pipe));
13565                 }
13566         }
13567 }
13568
13569 static void
13570 verify_crtc_state(struct drm_crtc *crtc,
13571                   struct drm_crtc_state *old_crtc_state,
13572                   struct drm_crtc_state *new_crtc_state)
13573 {
13574         struct drm_device *dev = crtc->dev;
13575         struct drm_i915_private *dev_priv = to_i915(dev);
13576         struct intel_encoder *encoder;
13577         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
13578         struct intel_crtc_state *pipe_config, *sw_config;
13579         struct drm_atomic_state *old_state;
13580         bool active;
13581
13582         old_state = old_crtc_state->state;
13583         __drm_atomic_helper_crtc_destroy_state(old_crtc_state);
13584         pipe_config = to_intel_crtc_state(old_crtc_state);
13585         memset(pipe_config, 0, sizeof(*pipe_config));
13586         pipe_config->base.crtc = crtc;
13587         pipe_config->base.state = old_state;
13588
13589         DRM_DEBUG_KMS("[CRTC:%d:%s]\n", crtc->base.id, crtc->name);
13590
13591         active = dev_priv->display.get_pipe_config(intel_crtc, pipe_config);
13592
13593         /* hw state is inconsistent with the pipe quirk */
13594         if ((intel_crtc->pipe == PIPE_A && dev_priv->quirks & QUIRK_PIPEA_FORCE) ||
13595             (intel_crtc->pipe == PIPE_B && dev_priv->quirks & QUIRK_PIPEB_FORCE))
13596                 active = new_crtc_state->active;
13597
13598         I915_STATE_WARN(new_crtc_state->active != active,
13599              "crtc active state doesn't match with hw state "
13600              "(expected %i, found %i)\n", new_crtc_state->active, active);
13601
13602         I915_STATE_WARN(intel_crtc->active != new_crtc_state->active,
13603              "transitional active state does not match atomic hw state "
13604              "(expected %i, found %i)\n", new_crtc_state->active, intel_crtc->active);
13605
13606         for_each_encoder_on_crtc(dev, crtc, encoder) {
13607                 enum pipe pipe;
13608
13609                 active = encoder->get_hw_state(encoder, &pipe);
13610                 I915_STATE_WARN(active != new_crtc_state->active,
13611                         "[ENCODER:%i] active %i with crtc active %i\n",
13612                         encoder->base.base.id, active, new_crtc_state->active);
13613
13614                 I915_STATE_WARN(active && intel_crtc->pipe != pipe,
13615                                 "Encoder connected to wrong pipe %c\n",
13616                                 pipe_name(pipe));
13617
13618                 if (active) {
13619                         pipe_config->output_types |= 1 << encoder->type;
13620                         encoder->get_config(encoder, pipe_config);
13621                 }
13622         }
13623
13624         if (!new_crtc_state->active)
13625                 return;
13626
13627         intel_pipe_config_sanity_check(dev_priv, pipe_config);
13628
13629         sw_config = to_intel_crtc_state(crtc->state);
13630         if (!intel_pipe_config_compare(dev, sw_config,
13631                                        pipe_config, false)) {
13632                 I915_STATE_WARN(1, "pipe state doesn't match!\n");
13633                 intel_dump_pipe_config(intel_crtc, pipe_config,
13634                                        "[hw state]");
13635                 intel_dump_pipe_config(intel_crtc, sw_config,
13636                                        "[sw state]");
13637         }
13638 }
13639
13640 static void
13641 verify_single_dpll_state(struct drm_i915_private *dev_priv,
13642                          struct intel_shared_dpll *pll,
13643                          struct drm_crtc *crtc,
13644                          struct drm_crtc_state *new_state)
13645 {
13646         struct intel_dpll_hw_state dpll_hw_state;
13647         unsigned crtc_mask;
13648         bool active;
13649
13650         memset(&dpll_hw_state, 0, sizeof(dpll_hw_state));
13651
13652         DRM_DEBUG_KMS("%s\n", pll->name);
13653
13654         active = pll->funcs.get_hw_state(dev_priv, pll, &dpll_hw_state);
13655
13656         if (!(pll->flags & INTEL_DPLL_ALWAYS_ON)) {
13657                 I915_STATE_WARN(!pll->on && pll->active_mask,
13658                      "pll in active use but not on in sw tracking\n");
13659                 I915_STATE_WARN(pll->on && !pll->active_mask,
13660                      "pll is on but not used by any active crtc\n");
13661                 I915_STATE_WARN(pll->on != active,
13662                      "pll on state mismatch (expected %i, found %i)\n",
13663                      pll->on, active);
13664         }
13665
13666         if (!crtc) {
13667                 I915_STATE_WARN(pll->active_mask & ~pll->config.crtc_mask,
13668                                 "more active pll users than references: %x vs %x\n",
13669                                 pll->active_mask, pll->config.crtc_mask);
13670
13671                 return;
13672         }
13673
13674         crtc_mask = 1 << drm_crtc_index(crtc);
13675
13676         if (new_state->active)
13677                 I915_STATE_WARN(!(pll->active_mask & crtc_mask),
13678                                 "pll active mismatch (expected pipe %c in active mask 0x%02x)\n",
13679                                 pipe_name(drm_crtc_index(crtc)), pll->active_mask);
13680         else
13681                 I915_STATE_WARN(pll->active_mask & crtc_mask,
13682                                 "pll active mismatch (didn't expect pipe %c in active mask 0x%02x)\n",
13683                                 pipe_name(drm_crtc_index(crtc)), pll->active_mask);
13684
13685         I915_STATE_WARN(!(pll->config.crtc_mask & crtc_mask),
13686                         "pll enabled crtcs mismatch (expected 0x%x in 0x%02x)\n",
13687                         crtc_mask, pll->config.crtc_mask);
13688
13689         I915_STATE_WARN(pll->on && memcmp(&pll->config.hw_state,
13690                                           &dpll_hw_state,
13691                                           sizeof(dpll_hw_state)),
13692                         "pll hw state mismatch\n");
13693 }
13694
13695 static void
13696 verify_shared_dpll_state(struct drm_device *dev, struct drm_crtc *crtc,
13697                          struct drm_crtc_state *old_crtc_state,
13698                          struct drm_crtc_state *new_crtc_state)
13699 {
13700         struct drm_i915_private *dev_priv = to_i915(dev);
13701         struct intel_crtc_state *old_state = to_intel_crtc_state(old_crtc_state);
13702         struct intel_crtc_state *new_state = to_intel_crtc_state(new_crtc_state);
13703
13704         if (new_state->shared_dpll)
13705                 verify_single_dpll_state(dev_priv, new_state->shared_dpll, crtc, new_crtc_state);
13706
13707         if (old_state->shared_dpll &&
13708             old_state->shared_dpll != new_state->shared_dpll) {
13709                 unsigned crtc_mask = 1 << drm_crtc_index(crtc);
13710                 struct intel_shared_dpll *pll = old_state->shared_dpll;
13711
13712                 I915_STATE_WARN(pll->active_mask & crtc_mask,
13713                                 "pll active mismatch (didn't expect pipe %c in active mask)\n",
13714                                 pipe_name(drm_crtc_index(crtc)));
13715                 I915_STATE_WARN(pll->config.crtc_mask & crtc_mask,
13716                                 "pll enabled crtcs mismatch (found %x in enabled mask)\n",
13717                                 pipe_name(drm_crtc_index(crtc)));
13718         }
13719 }
13720
13721 static void
13722 intel_modeset_verify_crtc(struct drm_crtc *crtc,
13723                          struct drm_crtc_state *old_state,
13724                          struct drm_crtc_state *new_state)
13725 {
13726         if (!needs_modeset(new_state) &&
13727             !to_intel_crtc_state(new_state)->update_pipe)
13728                 return;
13729
13730         verify_wm_state(crtc, new_state);
13731         verify_connector_state(crtc->dev, crtc);
13732         verify_crtc_state(crtc, old_state, new_state);
13733         verify_shared_dpll_state(crtc->dev, crtc, old_state, new_state);
13734 }
13735
13736 static void
13737 verify_disabled_dpll_state(struct drm_device *dev)
13738 {
13739         struct drm_i915_private *dev_priv = to_i915(dev);
13740         int i;
13741
13742         for (i = 0; i < dev_priv->num_shared_dpll; i++)
13743                 verify_single_dpll_state(dev_priv, &dev_priv->shared_dplls[i], NULL, NULL);
13744 }
13745
13746 static void
13747 intel_modeset_verify_disabled(struct drm_device *dev)
13748 {
13749         verify_encoder_state(dev);
13750         verify_connector_state(dev, NULL);
13751         verify_disabled_dpll_state(dev);
13752 }
13753
13754 static void update_scanline_offset(struct intel_crtc *crtc)
13755 {
13756         struct drm_device *dev = crtc->base.dev;
13757
13758         /*
13759          * The scanline counter increments at the leading edge of hsync.
13760          *
13761          * On most platforms it starts counting from vtotal-1 on the
13762          * first active line. That means the scanline counter value is
13763          * always one less than what we would expect. Ie. just after
13764          * start of vblank, which also occurs at start of hsync (on the
13765          * last active line), the scanline counter will read vblank_start-1.
13766          *
13767          * On gen2 the scanline counter starts counting from 1 instead
13768          * of vtotal-1, so we have to subtract one (or rather add vtotal-1
13769          * to keep the value positive), instead of adding one.
13770          *
13771          * On HSW+ the behaviour of the scanline counter depends on the output
13772          * type. For DP ports it behaves like most other platforms, but on HDMI
13773          * there's an extra 1 line difference. So we need to add two instead of
13774          * one to the value.
13775          *
13776          * On VLV/CHV DSI the scanline counter would appear to increment
13777          * approx. 1/3 of a scanline before start of vblank. Unfortunately
13778          * that means we can't tell whether we're in vblank or not while
13779          * we're on that particular line. We must still set scanline_offset
13780          * to 1 so that the vblank timestamps come out correct when we query
13781          * the scanline counter from within the vblank interrupt handler.
13782          * However if queried just before the start of vblank we'll get an
13783          * answer that's slightly in the future.
13784          */
13785         if (IS_GEN2(dev)) {
13786                 const struct drm_display_mode *adjusted_mode = &crtc->config->base.adjusted_mode;
13787                 int vtotal;
13788
13789                 vtotal = adjusted_mode->crtc_vtotal;
13790                 if (adjusted_mode->flags & DRM_MODE_FLAG_INTERLACE)
13791                         vtotal /= 2;
13792
13793                 crtc->scanline_offset = vtotal - 1;
13794         } else if (HAS_DDI(dev) &&
13795                    intel_crtc_has_type(crtc->config, INTEL_OUTPUT_HDMI)) {
13796                 crtc->scanline_offset = 2;
13797         } else
13798                 crtc->scanline_offset = 1;
13799 }
13800
13801 static void intel_modeset_clear_plls(struct drm_atomic_state *state)
13802 {
13803         struct drm_device *dev = state->dev;
13804         struct drm_i915_private *dev_priv = to_i915(dev);
13805         struct intel_shared_dpll_config *shared_dpll = NULL;
13806         struct drm_crtc *crtc;
13807         struct drm_crtc_state *crtc_state;
13808         int i;
13809
13810         if (!dev_priv->display.crtc_compute_clock)
13811                 return;
13812
13813         for_each_crtc_in_state(state, crtc, crtc_state, i) {
13814                 struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
13815                 struct intel_shared_dpll *old_dpll =
13816                         to_intel_crtc_state(crtc->state)->shared_dpll;
13817
13818                 if (!needs_modeset(crtc_state))
13819                         continue;
13820
13821                 to_intel_crtc_state(crtc_state)->shared_dpll = NULL;
13822
13823                 if (!old_dpll)
13824                         continue;
13825
13826                 if (!shared_dpll)
13827                         shared_dpll = intel_atomic_get_shared_dpll_state(state);
13828
13829                 intel_shared_dpll_config_put(shared_dpll, old_dpll, intel_crtc);
13830         }
13831 }
13832
13833 /*
13834  * This implements the workaround described in the "notes" section of the mode
13835  * set sequence documentation. When going from no pipes or single pipe to
13836  * multiple pipes, and planes are enabled after the pipe, we need to wait at
13837  * least 2 vblanks on the first pipe before enabling planes on the second pipe.
13838  */
13839 static int haswell_mode_set_planes_workaround(struct drm_atomic_state *state)
13840 {
13841         struct drm_crtc_state *crtc_state;
13842         struct intel_crtc *intel_crtc;
13843         struct drm_crtc *crtc;
13844         struct intel_crtc_state *first_crtc_state = NULL;
13845         struct intel_crtc_state *other_crtc_state = NULL;
13846         enum pipe first_pipe = INVALID_PIPE, enabled_pipe = INVALID_PIPE;
13847         int i;
13848
13849         /* look at all crtc's that are going to be enabled in during modeset */
13850         for_each_crtc_in_state(state, crtc, crtc_state, i) {
13851                 intel_crtc = to_intel_crtc(crtc);
13852
13853                 if (!crtc_state->active || !needs_modeset(crtc_state))
13854                         continue;
13855
13856                 if (first_crtc_state) {
13857                         other_crtc_state = to_intel_crtc_state(crtc_state);
13858                         break;
13859                 } else {
13860                         first_crtc_state = to_intel_crtc_state(crtc_state);
13861                         first_pipe = intel_crtc->pipe;
13862                 }
13863         }
13864
13865         /* No workaround needed? */
13866         if (!first_crtc_state)
13867                 return 0;
13868
13869         /* w/a possibly needed, check how many crtc's are already enabled. */
13870         for_each_intel_crtc(state->dev, intel_crtc) {
13871                 struct intel_crtc_state *pipe_config;
13872
13873                 pipe_config = intel_atomic_get_crtc_state(state, intel_crtc);
13874                 if (IS_ERR(pipe_config))
13875                         return PTR_ERR(pipe_config);
13876
13877                 pipe_config->hsw_workaround_pipe = INVALID_PIPE;
13878
13879                 if (!pipe_config->base.active ||
13880                     needs_modeset(&pipe_config->base))
13881                         continue;
13882
13883                 /* 2 or more enabled crtcs means no need for w/a */
13884                 if (enabled_pipe != INVALID_PIPE)
13885                         return 0;
13886
13887                 enabled_pipe = intel_crtc->pipe;
13888         }
13889
13890         if (enabled_pipe != INVALID_PIPE)
13891                 first_crtc_state->hsw_workaround_pipe = enabled_pipe;
13892         else if (other_crtc_state)
13893                 other_crtc_state->hsw_workaround_pipe = first_pipe;
13894
13895         return 0;
13896 }
13897
13898 static int intel_modeset_all_pipes(struct drm_atomic_state *state)
13899 {
13900         struct drm_crtc *crtc;
13901         struct drm_crtc_state *crtc_state;
13902         int ret = 0;
13903
13904         /* add all active pipes to the state */
13905         for_each_crtc(state->dev, crtc) {
13906                 crtc_state = drm_atomic_get_crtc_state(state, crtc);
13907                 if (IS_ERR(crtc_state))
13908                         return PTR_ERR(crtc_state);
13909
13910                 if (!crtc_state->active || needs_modeset(crtc_state))
13911                         continue;
13912
13913                 crtc_state->mode_changed = true;
13914
13915                 ret = drm_atomic_add_affected_connectors(state, crtc);
13916                 if (ret)
13917                         break;
13918
13919                 ret = drm_atomic_add_affected_planes(state, crtc);
13920                 if (ret)
13921                         break;
13922         }
13923
13924         return ret;
13925 }
13926
13927 static int intel_modeset_checks(struct drm_atomic_state *state)
13928 {
13929         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
13930         struct drm_i915_private *dev_priv = to_i915(state->dev);
13931         struct drm_crtc *crtc;
13932         struct drm_crtc_state *crtc_state;
13933         int ret = 0, i;
13934
13935         if (!check_digital_port_conflicts(state)) {
13936                 DRM_DEBUG_KMS("rejecting conflicting digital port configuration\n");
13937                 return -EINVAL;
13938         }
13939
13940         intel_state->modeset = true;
13941         intel_state->active_crtcs = dev_priv->active_crtcs;
13942
13943         for_each_crtc_in_state(state, crtc, crtc_state, i) {
13944                 if (crtc_state->active)
13945                         intel_state->active_crtcs |= 1 << i;
13946                 else
13947                         intel_state->active_crtcs &= ~(1 << i);
13948
13949                 if (crtc_state->active != crtc->state->active)
13950                         intel_state->active_pipe_changes |= drm_crtc_mask(crtc);
13951         }
13952
13953         /*
13954          * See if the config requires any additional preparation, e.g.
13955          * to adjust global state with pipes off.  We need to do this
13956          * here so we can get the modeset_pipe updated config for the new
13957          * mode set on this crtc.  For other crtcs we need to use the
13958          * adjusted_mode bits in the crtc directly.
13959          */
13960         if (dev_priv->display.modeset_calc_cdclk) {
13961                 if (!intel_state->cdclk_pll_vco)
13962                         intel_state->cdclk_pll_vco = dev_priv->cdclk_pll.vco;
13963                 if (!intel_state->cdclk_pll_vco)
13964                         intel_state->cdclk_pll_vco = dev_priv->skl_preferred_vco_freq;
13965
13966                 ret = dev_priv->display.modeset_calc_cdclk(state);
13967                 if (ret < 0)
13968                         return ret;
13969
13970                 if (intel_state->dev_cdclk != dev_priv->cdclk_freq ||
13971                     intel_state->cdclk_pll_vco != dev_priv->cdclk_pll.vco)
13972                         ret = intel_modeset_all_pipes(state);
13973
13974                 if (ret < 0)
13975                         return ret;
13976
13977                 DRM_DEBUG_KMS("New cdclk calculated to be atomic %u, actual %u\n",
13978                               intel_state->cdclk, intel_state->dev_cdclk);
13979         } else {
13980                 to_intel_atomic_state(state)->cdclk = dev_priv->atomic_cdclk_freq;
13981         }
13982
13983         intel_modeset_clear_plls(state);
13984
13985         if (IS_HASWELL(dev_priv))
13986                 return haswell_mode_set_planes_workaround(state);
13987
13988         return 0;
13989 }
13990
13991 /*
13992  * Handle calculation of various watermark data at the end of the atomic check
13993  * phase.  The code here should be run after the per-crtc and per-plane 'check'
13994  * handlers to ensure that all derived state has been updated.
13995  */
13996 static int calc_watermark_data(struct drm_atomic_state *state)
13997 {
13998         struct drm_device *dev = state->dev;
13999         struct drm_i915_private *dev_priv = to_i915(dev);
14000
14001         /* Is there platform-specific watermark information to calculate? */
14002         if (dev_priv->display.compute_global_watermarks)
14003                 return dev_priv->display.compute_global_watermarks(state);
14004
14005         return 0;
14006 }
14007
14008 /**
14009  * intel_atomic_check - validate state object
14010  * @dev: drm device
14011  * @state: state to validate
14012  */
14013 static int intel_atomic_check(struct drm_device *dev,
14014                               struct drm_atomic_state *state)
14015 {
14016         struct drm_i915_private *dev_priv = to_i915(dev);
14017         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
14018         struct drm_crtc *crtc;
14019         struct drm_crtc_state *crtc_state;
14020         int ret, i;
14021         bool any_ms = false;
14022
14023         ret = drm_atomic_helper_check_modeset(dev, state);
14024         if (ret)
14025                 return ret;
14026
14027         for_each_crtc_in_state(state, crtc, crtc_state, i) {
14028                 struct intel_crtc_state *pipe_config =
14029                         to_intel_crtc_state(crtc_state);
14030
14031                 /* Catch I915_MODE_FLAG_INHERITED */
14032                 if (crtc_state->mode.private_flags != crtc->state->mode.private_flags)
14033                         crtc_state->mode_changed = true;
14034
14035                 if (!needs_modeset(crtc_state))
14036                         continue;
14037
14038                 if (!crtc_state->enable) {
14039                         any_ms = true;
14040                         continue;
14041                 }
14042
14043                 /* FIXME: For only active_changed we shouldn't need to do any
14044                  * state recomputation at all. */
14045
14046                 ret = drm_atomic_add_affected_connectors(state, crtc);
14047                 if (ret)
14048                         return ret;
14049
14050                 ret = intel_modeset_pipe_config(crtc, pipe_config);
14051                 if (ret) {
14052                         intel_dump_pipe_config(to_intel_crtc(crtc),
14053                                                pipe_config, "[failed]");
14054                         return ret;
14055                 }
14056
14057                 if (i915.fastboot &&
14058                     intel_pipe_config_compare(dev,
14059                                         to_intel_crtc_state(crtc->state),
14060                                         pipe_config, true)) {
14061                         crtc_state->mode_changed = false;
14062                         to_intel_crtc_state(crtc_state)->update_pipe = true;
14063                 }
14064
14065                 if (needs_modeset(crtc_state))
14066                         any_ms = true;
14067
14068                 ret = drm_atomic_add_affected_planes(state, crtc);
14069                 if (ret)
14070                         return ret;
14071
14072                 intel_dump_pipe_config(to_intel_crtc(crtc), pipe_config,
14073                                        needs_modeset(crtc_state) ?
14074                                        "[modeset]" : "[fastset]");
14075         }
14076
14077         if (any_ms) {
14078                 ret = intel_modeset_checks(state);
14079
14080                 if (ret)
14081                         return ret;
14082         } else {
14083                 intel_state->cdclk = dev_priv->atomic_cdclk_freq;
14084         }
14085
14086         ret = drm_atomic_helper_check_planes(dev, state);
14087         if (ret)
14088                 return ret;
14089
14090         intel_fbc_choose_crtc(dev_priv, state);
14091         return calc_watermark_data(state);
14092 }
14093
14094 static int intel_atomic_prepare_commit(struct drm_device *dev,
14095                                        struct drm_atomic_state *state,
14096                                        bool nonblock)
14097 {
14098         struct drm_i915_private *dev_priv = to_i915(dev);
14099         struct drm_plane_state *plane_state;
14100         struct drm_crtc_state *crtc_state;
14101         struct drm_plane *plane;
14102         struct drm_crtc *crtc;
14103         int i, ret;
14104
14105         for_each_crtc_in_state(state, crtc, crtc_state, i) {
14106                 if (state->legacy_cursor_update)
14107                         continue;
14108
14109                 ret = intel_crtc_wait_for_pending_flips(crtc);
14110                 if (ret)
14111                         return ret;
14112
14113                 if (atomic_read(&to_intel_crtc(crtc)->unpin_work_count) >= 2)
14114                         flush_workqueue(dev_priv->wq);
14115         }
14116
14117         ret = mutex_lock_interruptible(&dev->struct_mutex);
14118         if (ret)
14119                 return ret;
14120
14121         ret = drm_atomic_helper_prepare_planes(dev, state);
14122         mutex_unlock(&dev->struct_mutex);
14123
14124         if (!ret && !nonblock) {
14125                 for_each_plane_in_state(state, plane, plane_state, i) {
14126                         struct intel_plane_state *intel_plane_state =
14127                                 to_intel_plane_state(plane_state);
14128
14129                         if (!intel_plane_state->wait_req)
14130                                 continue;
14131
14132                         ret = i915_wait_request(intel_plane_state->wait_req,
14133                                                 I915_WAIT_INTERRUPTIBLE,
14134                                                 NULL, NULL);
14135                         if (ret) {
14136                                 /* Any hang should be swallowed by the wait */
14137                                 WARN_ON(ret == -EIO);
14138                                 mutex_lock(&dev->struct_mutex);
14139                                 drm_atomic_helper_cleanup_planes(dev, state);
14140                                 mutex_unlock(&dev->struct_mutex);
14141                                 break;
14142                         }
14143                 }
14144         }
14145
14146         return ret;
14147 }
14148
14149 u32 intel_crtc_get_vblank_counter(struct intel_crtc *crtc)
14150 {
14151         struct drm_device *dev = crtc->base.dev;
14152
14153         if (!dev->max_vblank_count)
14154                 return drm_accurate_vblank_count(&crtc->base);
14155
14156         return dev->driver->get_vblank_counter(dev, crtc->pipe);
14157 }
14158
14159 static void intel_atomic_wait_for_vblanks(struct drm_device *dev,
14160                                           struct drm_i915_private *dev_priv,
14161                                           unsigned crtc_mask)
14162 {
14163         unsigned last_vblank_count[I915_MAX_PIPES];
14164         enum pipe pipe;
14165         int ret;
14166
14167         if (!crtc_mask)
14168                 return;
14169
14170         for_each_pipe(dev_priv, pipe) {
14171                 struct drm_crtc *crtc = dev_priv->pipe_to_crtc_mapping[pipe];
14172
14173                 if (!((1 << pipe) & crtc_mask))
14174                         continue;
14175
14176                 ret = drm_crtc_vblank_get(crtc);
14177                 if (WARN_ON(ret != 0)) {
14178                         crtc_mask &= ~(1 << pipe);
14179                         continue;
14180                 }
14181
14182                 last_vblank_count[pipe] = drm_crtc_vblank_count(crtc);
14183         }
14184
14185         for_each_pipe(dev_priv, pipe) {
14186                 struct drm_crtc *crtc = dev_priv->pipe_to_crtc_mapping[pipe];
14187                 long lret;
14188
14189                 if (!((1 << pipe) & crtc_mask))
14190                         continue;
14191
14192                 lret = wait_event_timeout(dev->vblank[pipe].queue,
14193                                 last_vblank_count[pipe] !=
14194                                         drm_crtc_vblank_count(crtc),
14195                                 msecs_to_jiffies(50));
14196
14197                 WARN(!lret, "pipe %c vblank wait timed out\n", pipe_name(pipe));
14198
14199                 drm_crtc_vblank_put(crtc);
14200         }
14201 }
14202
14203 static bool needs_vblank_wait(struct intel_crtc_state *crtc_state)
14204 {
14205         /* fb updated, need to unpin old fb */
14206         if (crtc_state->fb_changed)
14207                 return true;
14208
14209         /* wm changes, need vblank before final wm's */
14210         if (crtc_state->update_wm_post)
14211                 return true;
14212
14213         /*
14214          * cxsr is re-enabled after vblank.
14215          * This is already handled by crtc_state->update_wm_post,
14216          * but added for clarity.
14217          */
14218         if (crtc_state->disable_cxsr)
14219                 return true;
14220
14221         return false;
14222 }
14223
14224 static void intel_update_crtc(struct drm_crtc *crtc,
14225                               struct drm_atomic_state *state,
14226                               struct drm_crtc_state *old_crtc_state,
14227                               unsigned int *crtc_vblank_mask)
14228 {
14229         struct drm_device *dev = crtc->dev;
14230         struct drm_i915_private *dev_priv = to_i915(dev);
14231         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
14232         struct intel_crtc_state *pipe_config = to_intel_crtc_state(crtc->state);
14233         bool modeset = needs_modeset(crtc->state);
14234
14235         if (modeset) {
14236                 update_scanline_offset(intel_crtc);
14237                 dev_priv->display.crtc_enable(pipe_config, state);
14238         } else {
14239                 intel_pre_plane_update(to_intel_crtc_state(old_crtc_state));
14240         }
14241
14242         if (drm_atomic_get_existing_plane_state(state, crtc->primary)) {
14243                 intel_fbc_enable(
14244                     intel_crtc, pipe_config,
14245                     to_intel_plane_state(crtc->primary->state));
14246         }
14247
14248         drm_atomic_helper_commit_planes_on_crtc(old_crtc_state);
14249
14250         if (needs_vblank_wait(pipe_config))
14251                 *crtc_vblank_mask |= drm_crtc_mask(crtc);
14252 }
14253
14254 static void intel_update_crtcs(struct drm_atomic_state *state,
14255                                unsigned int *crtc_vblank_mask)
14256 {
14257         struct drm_crtc *crtc;
14258         struct drm_crtc_state *old_crtc_state;
14259         int i;
14260
14261         for_each_crtc_in_state(state, crtc, old_crtc_state, i) {
14262                 if (!crtc->state->active)
14263                         continue;
14264
14265                 intel_update_crtc(crtc, state, old_crtc_state,
14266                                   crtc_vblank_mask);
14267         }
14268 }
14269
14270 static void skl_update_crtcs(struct drm_atomic_state *state,
14271                              unsigned int *crtc_vblank_mask)
14272 {
14273         struct drm_device *dev = state->dev;
14274         struct drm_i915_private *dev_priv = to_i915(dev);
14275         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
14276         struct drm_crtc *crtc;
14277         struct drm_crtc_state *old_crtc_state;
14278         struct skl_ddb_allocation *new_ddb = &intel_state->wm_results.ddb;
14279         struct skl_ddb_allocation *cur_ddb = &dev_priv->wm.skl_hw.ddb;
14280         unsigned int updated = 0;
14281         bool progress;
14282         enum pipe pipe;
14283
14284         /*
14285          * Whenever the number of active pipes changes, we need to make sure we
14286          * update the pipes in the right order so that their ddb allocations
14287          * never overlap with eachother inbetween CRTC updates. Otherwise we'll
14288          * cause pipe underruns and other bad stuff.
14289          */
14290         do {
14291                 int i;
14292                 progress = false;
14293
14294                 for_each_crtc_in_state(state, crtc, old_crtc_state, i) {
14295                         bool vbl_wait = false;
14296                         unsigned int cmask = drm_crtc_mask(crtc);
14297                         pipe = to_intel_crtc(crtc)->pipe;
14298
14299                         if (updated & cmask || !crtc->state->active)
14300                                 continue;
14301                         if (skl_ddb_allocation_overlaps(state, cur_ddb, new_ddb,
14302                                                         pipe))
14303                                 continue;
14304
14305                         updated |= cmask;
14306
14307                         /*
14308                          * If this is an already active pipe, it's DDB changed,
14309                          * and this isn't the last pipe that needs updating
14310                          * then we need to wait for a vblank to pass for the
14311                          * new ddb allocation to take effect.
14312                          */
14313                         if (!skl_ddb_allocation_equals(cur_ddb, new_ddb, pipe) &&
14314                             !crtc->state->active_changed &&
14315                             intel_state->wm_results.dirty_pipes != updated)
14316                                 vbl_wait = true;
14317
14318                         intel_update_crtc(crtc, state, old_crtc_state,
14319                                           crtc_vblank_mask);
14320
14321                         if (vbl_wait)
14322                                 intel_wait_for_vblank(dev, pipe);
14323
14324                         progress = true;
14325                 }
14326         } while (progress);
14327 }
14328
14329 static void intel_atomic_commit_tail(struct drm_atomic_state *state)
14330 {
14331         struct drm_device *dev = state->dev;
14332         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
14333         struct drm_i915_private *dev_priv = to_i915(dev);
14334         struct drm_crtc_state *old_crtc_state;
14335         struct drm_crtc *crtc;
14336         struct intel_crtc_state *intel_cstate;
14337         struct drm_plane *plane;
14338         struct drm_plane_state *plane_state;
14339         bool hw_check = intel_state->modeset;
14340         unsigned long put_domains[I915_MAX_PIPES] = {};
14341         unsigned crtc_vblank_mask = 0;
14342         int i, ret;
14343
14344         for_each_plane_in_state(state, plane, plane_state, i) {
14345                 struct intel_plane_state *intel_plane_state =
14346                         to_intel_plane_state(plane->state);
14347
14348                 if (!intel_plane_state->wait_req)
14349                         continue;
14350
14351                 ret = i915_wait_request(intel_plane_state->wait_req,
14352                                         0, NULL, NULL);
14353                 /* EIO should be eaten, and we can't get interrupted in the
14354                  * worker, and blocking commits have waited already. */
14355                 WARN_ON(ret);
14356         }
14357
14358         drm_atomic_helper_wait_for_dependencies(state);
14359
14360         if (intel_state->modeset) {
14361                 memcpy(dev_priv->min_pixclk, intel_state->min_pixclk,
14362                        sizeof(intel_state->min_pixclk));
14363                 dev_priv->active_crtcs = intel_state->active_crtcs;
14364                 dev_priv->atomic_cdclk_freq = intel_state->cdclk;
14365
14366                 intel_display_power_get(dev_priv, POWER_DOMAIN_MODESET);
14367         }
14368
14369         for_each_crtc_in_state(state, crtc, old_crtc_state, i) {
14370                 struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
14371
14372                 if (needs_modeset(crtc->state) ||
14373                     to_intel_crtc_state(crtc->state)->update_pipe) {
14374                         hw_check = true;
14375
14376                         put_domains[to_intel_crtc(crtc)->pipe] =
14377                                 modeset_get_crtc_power_domains(crtc,
14378                                         to_intel_crtc_state(crtc->state));
14379                 }
14380
14381                 if (!needs_modeset(crtc->state))
14382                         continue;
14383
14384                 intel_pre_plane_update(to_intel_crtc_state(old_crtc_state));
14385
14386                 if (old_crtc_state->active) {
14387                         intel_crtc_disable_planes(crtc, old_crtc_state->plane_mask);
14388                         dev_priv->display.crtc_disable(to_intel_crtc_state(old_crtc_state), state);
14389                         intel_crtc->active = false;
14390                         intel_fbc_disable(intel_crtc);
14391                         intel_disable_shared_dpll(intel_crtc);
14392
14393                         /*
14394                          * Underruns don't always raise
14395                          * interrupts, so check manually.
14396                          */
14397                         intel_check_cpu_fifo_underruns(dev_priv);
14398                         intel_check_pch_fifo_underruns(dev_priv);
14399
14400                         if (!crtc->state->active)
14401                                 intel_update_watermarks(crtc);
14402                 }
14403         }
14404
14405         /* Only after disabling all output pipelines that will be changed can we
14406          * update the the output configuration. */
14407         intel_modeset_update_crtc_state(state);
14408
14409         if (intel_state->modeset) {
14410                 drm_atomic_helper_update_legacy_modeset_state(state->dev, state);
14411
14412                 if (dev_priv->display.modeset_commit_cdclk &&
14413                     (intel_state->dev_cdclk != dev_priv->cdclk_freq ||
14414                      intel_state->cdclk_pll_vco != dev_priv->cdclk_pll.vco))
14415                         dev_priv->display.modeset_commit_cdclk(state);
14416
14417                 /*
14418                  * SKL workaround: bspec recommends we disable the SAGV when we
14419                  * have more then one pipe enabled
14420                  */
14421                 if (!intel_can_enable_sagv(state))
14422                         intel_disable_sagv(dev_priv);
14423
14424                 intel_modeset_verify_disabled(dev);
14425         }
14426
14427         /* Complete the events for pipes that have now been disabled */
14428         for_each_crtc_in_state(state, crtc, old_crtc_state, i) {
14429                 bool modeset = needs_modeset(crtc->state);
14430
14431                 /* Complete events for now disable pipes here. */
14432                 if (modeset && !crtc->state->active && crtc->state->event) {
14433                         spin_lock_irq(&dev->event_lock);
14434                         drm_crtc_send_vblank_event(crtc, crtc->state->event);
14435                         spin_unlock_irq(&dev->event_lock);
14436
14437                         crtc->state->event = NULL;
14438                 }
14439         }
14440
14441         /* Now enable the clocks, plane, pipe, and connectors that we set up. */
14442         dev_priv->display.update_crtcs(state, &crtc_vblank_mask);
14443
14444         /* FIXME: We should call drm_atomic_helper_commit_hw_done() here
14445          * already, but still need the state for the delayed optimization. To
14446          * fix this:
14447          * - wrap the optimization/post_plane_update stuff into a per-crtc work.
14448          * - schedule that vblank worker _before_ calling hw_done
14449          * - at the start of commit_tail, cancel it _synchrously
14450          * - switch over to the vblank wait helper in the core after that since
14451          *   we don't need out special handling any more.
14452          */
14453         if (!state->legacy_cursor_update)
14454                 intel_atomic_wait_for_vblanks(dev, dev_priv, crtc_vblank_mask);
14455
14456         /*
14457          * Now that the vblank has passed, we can go ahead and program the
14458          * optimal watermarks on platforms that need two-step watermark
14459          * programming.
14460          *
14461          * TODO: Move this (and other cleanup) to an async worker eventually.
14462          */
14463         for_each_crtc_in_state(state, crtc, old_crtc_state, i) {
14464                 intel_cstate = to_intel_crtc_state(crtc->state);
14465
14466                 if (dev_priv->display.optimize_watermarks)
14467                         dev_priv->display.optimize_watermarks(intel_cstate);
14468         }
14469
14470         for_each_crtc_in_state(state, crtc, old_crtc_state, i) {
14471                 intel_post_plane_update(to_intel_crtc_state(old_crtc_state));
14472
14473                 if (put_domains[i])
14474                         modeset_put_power_domains(dev_priv, put_domains[i]);
14475
14476                 intel_modeset_verify_crtc(crtc, old_crtc_state, crtc->state);
14477         }
14478
14479         if (intel_state->modeset && intel_can_enable_sagv(state))
14480                 intel_enable_sagv(dev_priv);
14481
14482         drm_atomic_helper_commit_hw_done(state);
14483
14484         if (intel_state->modeset)
14485                 intel_display_power_put(dev_priv, POWER_DOMAIN_MODESET);
14486
14487         mutex_lock(&dev->struct_mutex);
14488         drm_atomic_helper_cleanup_planes(dev, state);
14489         mutex_unlock(&dev->struct_mutex);
14490
14491         drm_atomic_helper_commit_cleanup_done(state);
14492
14493         drm_atomic_state_free(state);
14494
14495         /* As one of the primary mmio accessors, KMS has a high likelihood
14496          * of triggering bugs in unclaimed access. After we finish
14497          * modesetting, see if an error has been flagged, and if so
14498          * enable debugging for the next modeset - and hope we catch
14499          * the culprit.
14500          *
14501          * XXX note that we assume display power is on at this point.
14502          * This might hold true now but we need to add pm helper to check
14503          * unclaimed only when the hardware is on, as atomic commits
14504          * can happen also when the device is completely off.
14505          */
14506         intel_uncore_arm_unclaimed_mmio_detection(dev_priv);
14507 }
14508
14509 static void intel_atomic_commit_work(struct work_struct *work)
14510 {
14511         struct drm_atomic_state *state = container_of(work,
14512                                                       struct drm_atomic_state,
14513                                                       commit_work);
14514         intel_atomic_commit_tail(state);
14515 }
14516
14517 static void intel_atomic_track_fbs(struct drm_atomic_state *state)
14518 {
14519         struct drm_plane_state *old_plane_state;
14520         struct drm_plane *plane;
14521         int i;
14522
14523         for_each_plane_in_state(state, plane, old_plane_state, i)
14524                 i915_gem_track_fb(intel_fb_obj(old_plane_state->fb),
14525                                   intel_fb_obj(plane->state->fb),
14526                                   to_intel_plane(plane)->frontbuffer_bit);
14527 }
14528
14529 /**
14530  * intel_atomic_commit - commit validated state object
14531  * @dev: DRM device
14532  * @state: the top-level driver state object
14533  * @nonblock: nonblocking commit
14534  *
14535  * This function commits a top-level state object that has been validated
14536  * with drm_atomic_helper_check().
14537  *
14538  * FIXME:  Atomic modeset support for i915 is not yet complete.  At the moment
14539  * nonblocking commits are only safe for pure plane updates. Everything else
14540  * should work though.
14541  *
14542  * RETURNS
14543  * Zero for success or -errno.
14544  */
14545 static int intel_atomic_commit(struct drm_device *dev,
14546                                struct drm_atomic_state *state,
14547                                bool nonblock)
14548 {
14549         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
14550         struct drm_i915_private *dev_priv = to_i915(dev);
14551         int ret = 0;
14552
14553         if (intel_state->modeset && nonblock) {
14554                 DRM_DEBUG_KMS("nonblocking commit for modeset not yet implemented.\n");
14555                 return -EINVAL;
14556         }
14557
14558         ret = drm_atomic_helper_setup_commit(state, nonblock);
14559         if (ret)
14560                 return ret;
14561
14562         INIT_WORK(&state->commit_work, intel_atomic_commit_work);
14563
14564         ret = intel_atomic_prepare_commit(dev, state, nonblock);
14565         if (ret) {
14566                 DRM_DEBUG_ATOMIC("Preparing state failed with %i\n", ret);
14567                 return ret;
14568         }
14569
14570         drm_atomic_helper_swap_state(state, true);
14571         dev_priv->wm.distrust_bios_wm = false;
14572         dev_priv->wm.skl_results = intel_state->wm_results;
14573         intel_shared_dpll_commit(state);
14574         intel_atomic_track_fbs(state);
14575
14576         if (nonblock)
14577                 queue_work(system_unbound_wq, &state->commit_work);
14578         else
14579                 intel_atomic_commit_tail(state);
14580
14581         return 0;
14582 }
14583
14584 void intel_crtc_restore_mode(struct drm_crtc *crtc)
14585 {
14586         struct drm_device *dev = crtc->dev;
14587         struct drm_atomic_state *state;
14588         struct drm_crtc_state *crtc_state;
14589         int ret;
14590
14591         state = drm_atomic_state_alloc(dev);
14592         if (!state) {
14593                 DRM_DEBUG_KMS("[CRTC:%d:%s] crtc restore failed, out of memory",
14594                               crtc->base.id, crtc->name);
14595                 return;
14596         }
14597
14598         state->acquire_ctx = drm_modeset_legacy_acquire_ctx(crtc);
14599
14600 retry:
14601         crtc_state = drm_atomic_get_crtc_state(state, crtc);
14602         ret = PTR_ERR_OR_ZERO(crtc_state);
14603         if (!ret) {
14604                 if (!crtc_state->active)
14605                         goto out;
14606
14607                 crtc_state->mode_changed = true;
14608                 ret = drm_atomic_commit(state);
14609         }
14610
14611         if (ret == -EDEADLK) {
14612                 drm_atomic_state_clear(state);
14613                 drm_modeset_backoff(state->acquire_ctx);
14614                 goto retry;
14615         }
14616
14617         if (ret)
14618 out:
14619                 drm_atomic_state_free(state);
14620 }
14621
14622 /*
14623  * FIXME: Remove this once i915 is fully DRIVER_ATOMIC by calling
14624  *        drm_atomic_helper_legacy_gamma_set() directly.
14625  */
14626 static int intel_atomic_legacy_gamma_set(struct drm_crtc *crtc,
14627                                          u16 *red, u16 *green, u16 *blue,
14628                                          uint32_t size)
14629 {
14630         struct drm_device *dev = crtc->dev;
14631         struct drm_mode_config *config = &dev->mode_config;
14632         struct drm_crtc_state *state;
14633         int ret;
14634
14635         ret = drm_atomic_helper_legacy_gamma_set(crtc, red, green, blue, size);
14636         if (ret)
14637                 return ret;
14638
14639         /*
14640          * Make sure we update the legacy properties so this works when
14641          * atomic is not enabled.
14642          */
14643
14644         state = crtc->state;
14645
14646         drm_object_property_set_value(&crtc->base,
14647                                       config->degamma_lut_property,
14648                                       (state->degamma_lut) ?
14649                                       state->degamma_lut->base.id : 0);
14650
14651         drm_object_property_set_value(&crtc->base,
14652                                       config->ctm_property,
14653                                       (state->ctm) ?
14654                                       state->ctm->base.id : 0);
14655
14656         drm_object_property_set_value(&crtc->base,
14657                                       config->gamma_lut_property,
14658                                       (state->gamma_lut) ?
14659                                       state->gamma_lut->base.id : 0);
14660
14661         return 0;
14662 }
14663
14664 static const struct drm_crtc_funcs intel_crtc_funcs = {
14665         .gamma_set = intel_atomic_legacy_gamma_set,
14666         .set_config = drm_atomic_helper_set_config,
14667         .set_property = drm_atomic_helper_crtc_set_property,
14668         .destroy = intel_crtc_destroy,
14669         .page_flip = intel_crtc_page_flip,
14670         .atomic_duplicate_state = intel_crtc_duplicate_state,
14671         .atomic_destroy_state = intel_crtc_destroy_state,
14672 };
14673
14674 /**
14675  * intel_prepare_plane_fb - Prepare fb for usage on plane
14676  * @plane: drm plane to prepare for
14677  * @fb: framebuffer to prepare for presentation
14678  *
14679  * Prepares a framebuffer for usage on a display plane.  Generally this
14680  * involves pinning the underlying object and updating the frontbuffer tracking
14681  * bits.  Some older platforms need special physical address handling for
14682  * cursor planes.
14683  *
14684  * Must be called with struct_mutex held.
14685  *
14686  * Returns 0 on success, negative error code on failure.
14687  */
14688 int
14689 intel_prepare_plane_fb(struct drm_plane *plane,
14690                        struct drm_plane_state *new_state)
14691 {
14692         struct drm_device *dev = plane->dev;
14693         struct drm_framebuffer *fb = new_state->fb;
14694         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
14695         struct drm_i915_gem_object *old_obj = intel_fb_obj(plane->state->fb);
14696         struct reservation_object *resv;
14697         int ret = 0;
14698
14699         if (!obj && !old_obj)
14700                 return 0;
14701
14702         if (old_obj) {
14703                 struct drm_crtc_state *crtc_state =
14704                         drm_atomic_get_existing_crtc_state(new_state->state, plane->state->crtc);
14705
14706                 /* Big Hammer, we also need to ensure that any pending
14707                  * MI_WAIT_FOR_EVENT inside a user batch buffer on the
14708                  * current scanout is retired before unpinning the old
14709                  * framebuffer. Note that we rely on userspace rendering
14710                  * into the buffer attached to the pipe they are waiting
14711                  * on. If not, userspace generates a GPU hang with IPEHR
14712                  * point to the MI_WAIT_FOR_EVENT.
14713                  *
14714                  * This should only fail upon a hung GPU, in which case we
14715                  * can safely continue.
14716                  */
14717                 if (needs_modeset(crtc_state))
14718                         ret = i915_gem_object_wait_rendering(old_obj, true);
14719                 if (ret) {
14720                         /* GPU hangs should have been swallowed by the wait */
14721                         WARN_ON(ret == -EIO);
14722                         return ret;
14723                 }
14724         }
14725
14726         if (!obj)
14727                 return 0;
14728
14729         /* For framebuffer backed by dmabuf, wait for fence */
14730         resv = i915_gem_object_get_dmabuf_resv(obj);
14731         if (resv) {
14732                 long lret;
14733
14734                 lret = reservation_object_wait_timeout_rcu(resv, false, true,
14735                                                            MAX_SCHEDULE_TIMEOUT);
14736                 if (lret == -ERESTARTSYS)
14737                         return lret;
14738
14739                 WARN(lret < 0, "waiting returns %li\n", lret);
14740         }
14741
14742         if (plane->type == DRM_PLANE_TYPE_CURSOR &&
14743             INTEL_INFO(dev)->cursor_needs_physical) {
14744                 int align = IS_I830(dev) ? 16 * 1024 : 256;
14745                 ret = i915_gem_object_attach_phys(obj, align);
14746                 if (ret)
14747                         DRM_DEBUG_KMS("failed to attach phys object\n");
14748         } else {
14749                 struct i915_vma *vma;
14750
14751                 vma = intel_pin_and_fence_fb_obj(fb, new_state->rotation);
14752                 if (IS_ERR(vma))
14753                         ret = PTR_ERR(vma);
14754         }
14755
14756         if (ret == 0) {
14757                 to_intel_plane_state(new_state)->wait_req =
14758                         i915_gem_active_get(&obj->last_write,
14759                                             &obj->base.dev->struct_mutex);
14760         }
14761
14762         return ret;
14763 }
14764
14765 /**
14766  * intel_cleanup_plane_fb - Cleans up an fb after plane use
14767  * @plane: drm plane to clean up for
14768  * @fb: old framebuffer that was on plane
14769  *
14770  * Cleans up a framebuffer that has just been removed from a plane.
14771  *
14772  * Must be called with struct_mutex held.
14773  */
14774 void
14775 intel_cleanup_plane_fb(struct drm_plane *plane,
14776                        struct drm_plane_state *old_state)
14777 {
14778         struct drm_device *dev = plane->dev;
14779         struct intel_plane_state *old_intel_state;
14780         struct intel_plane_state *intel_state = to_intel_plane_state(plane->state);
14781         struct drm_i915_gem_object *old_obj = intel_fb_obj(old_state->fb);
14782         struct drm_i915_gem_object *obj = intel_fb_obj(plane->state->fb);
14783
14784         old_intel_state = to_intel_plane_state(old_state);
14785
14786         if (!obj && !old_obj)
14787                 return;
14788
14789         if (old_obj && (plane->type != DRM_PLANE_TYPE_CURSOR ||
14790             !INTEL_INFO(dev)->cursor_needs_physical))
14791                 intel_unpin_fb_obj(old_state->fb, old_state->rotation);
14792
14793         i915_gem_request_assign(&intel_state->wait_req, NULL);
14794         i915_gem_request_assign(&old_intel_state->wait_req, NULL);
14795 }
14796
14797 int
14798 skl_max_scale(struct intel_crtc *intel_crtc, struct intel_crtc_state *crtc_state)
14799 {
14800         int max_scale;
14801         int crtc_clock, cdclk;
14802
14803         if (!intel_crtc || !crtc_state->base.enable)
14804                 return DRM_PLANE_HELPER_NO_SCALING;
14805
14806         crtc_clock = crtc_state->base.adjusted_mode.crtc_clock;
14807         cdclk = to_intel_atomic_state(crtc_state->base.state)->cdclk;
14808
14809         if (WARN_ON_ONCE(!crtc_clock || cdclk < crtc_clock))
14810                 return DRM_PLANE_HELPER_NO_SCALING;
14811
14812         /*
14813          * skl max scale is lower of:
14814          *    close to 3 but not 3, -1 is for that purpose
14815          *            or
14816          *    cdclk/crtc_clock
14817          */
14818         max_scale = min((1 << 16) * 3 - 1, (1 << 8) * ((cdclk << 8) / crtc_clock));
14819
14820         return max_scale;
14821 }
14822
14823 static int
14824 intel_check_primary_plane(struct drm_plane *plane,
14825                           struct intel_crtc_state *crtc_state,
14826                           struct intel_plane_state *state)
14827 {
14828         struct drm_i915_private *dev_priv = to_i915(plane->dev);
14829         struct drm_crtc *crtc = state->base.crtc;
14830         int min_scale = DRM_PLANE_HELPER_NO_SCALING;
14831         int max_scale = DRM_PLANE_HELPER_NO_SCALING;
14832         bool can_position = false;
14833         int ret;
14834
14835         if (INTEL_GEN(dev_priv) >= 9) {
14836                 /* use scaler when colorkey is not required */
14837                 if (state->ckey.flags == I915_SET_COLORKEY_NONE) {
14838                         min_scale = 1;
14839                         max_scale = skl_max_scale(to_intel_crtc(crtc), crtc_state);
14840                 }
14841                 can_position = true;
14842         }
14843
14844         ret = drm_plane_helper_check_state(&state->base,
14845                                            &state->clip,
14846                                            min_scale, max_scale,
14847                                            can_position, true);
14848         if (ret)
14849                 return ret;
14850
14851         if (!state->base.fb)
14852                 return 0;
14853
14854         if (INTEL_GEN(dev_priv) >= 9) {
14855                 ret = skl_check_plane_surface(state);
14856                 if (ret)
14857                         return ret;
14858         }
14859
14860         return 0;
14861 }
14862
14863 static void intel_begin_crtc_commit(struct drm_crtc *crtc,
14864                                     struct drm_crtc_state *old_crtc_state)
14865 {
14866         struct drm_device *dev = crtc->dev;
14867         struct drm_i915_private *dev_priv = to_i915(dev);
14868         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
14869         struct intel_crtc_state *old_intel_state =
14870                 to_intel_crtc_state(old_crtc_state);
14871         bool modeset = needs_modeset(crtc->state);
14872         enum pipe pipe = intel_crtc->pipe;
14873
14874         /* Perform vblank evasion around commit operation */
14875         intel_pipe_update_start(intel_crtc);
14876
14877         if (modeset)
14878                 return;
14879
14880         if (crtc->state->color_mgmt_changed || to_intel_crtc_state(crtc->state)->update_pipe) {
14881                 intel_color_set_csc(crtc->state);
14882                 intel_color_load_luts(crtc->state);
14883         }
14884
14885         if (to_intel_crtc_state(crtc->state)->update_pipe)
14886                 intel_update_pipe_config(intel_crtc, old_intel_state);
14887         else if (INTEL_GEN(dev_priv) >= 9) {
14888                 skl_detach_scalers(intel_crtc);
14889
14890                 I915_WRITE(PIPE_WM_LINETIME(pipe),
14891                            dev_priv->wm.skl_hw.wm_linetime[pipe]);
14892         }
14893 }
14894
14895 static void intel_finish_crtc_commit(struct drm_crtc *crtc,
14896                                      struct drm_crtc_state *old_crtc_state)
14897 {
14898         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
14899
14900         intel_pipe_update_end(intel_crtc, NULL);
14901 }
14902
14903 /**
14904  * intel_plane_destroy - destroy a plane
14905  * @plane: plane to destroy
14906  *
14907  * Common destruction function for all types of planes (primary, cursor,
14908  * sprite).
14909  */
14910 void intel_plane_destroy(struct drm_plane *plane)
14911 {
14912         if (!plane)
14913                 return;
14914
14915         drm_plane_cleanup(plane);
14916         kfree(to_intel_plane(plane));
14917 }
14918
14919 const struct drm_plane_funcs intel_plane_funcs = {
14920         .update_plane = drm_atomic_helper_update_plane,
14921         .disable_plane = drm_atomic_helper_disable_plane,
14922         .destroy = intel_plane_destroy,
14923         .set_property = drm_atomic_helper_plane_set_property,
14924         .atomic_get_property = intel_plane_atomic_get_property,
14925         .atomic_set_property = intel_plane_atomic_set_property,
14926         .atomic_duplicate_state = intel_plane_duplicate_state,
14927         .atomic_destroy_state = intel_plane_destroy_state,
14928
14929 };
14930
14931 static struct drm_plane *intel_primary_plane_create(struct drm_device *dev,
14932                                                     int pipe)
14933 {
14934         struct intel_plane *primary = NULL;
14935         struct intel_plane_state *state = NULL;
14936         const uint32_t *intel_primary_formats;
14937         unsigned int num_formats;
14938         int ret;
14939
14940         primary = kzalloc(sizeof(*primary), GFP_KERNEL);
14941         if (!primary)
14942                 goto fail;
14943
14944         state = intel_create_plane_state(&primary->base);
14945         if (!state)
14946                 goto fail;
14947         primary->base.state = &state->base;
14948
14949         primary->can_scale = false;
14950         primary->max_downscale = 1;
14951         if (INTEL_INFO(dev)->gen >= 9) {
14952                 primary->can_scale = true;
14953                 state->scaler_id = -1;
14954         }
14955         primary->pipe = pipe;
14956         primary->plane = pipe;
14957         primary->frontbuffer_bit = INTEL_FRONTBUFFER_PRIMARY(pipe);
14958         primary->check_plane = intel_check_primary_plane;
14959         if (HAS_FBC(dev) && INTEL_INFO(dev)->gen < 4)
14960                 primary->plane = !pipe;
14961
14962         if (INTEL_INFO(dev)->gen >= 9) {
14963                 intel_primary_formats = skl_primary_formats;
14964                 num_formats = ARRAY_SIZE(skl_primary_formats);
14965
14966                 primary->update_plane = skylake_update_primary_plane;
14967                 primary->disable_plane = skylake_disable_primary_plane;
14968         } else if (HAS_PCH_SPLIT(dev)) {
14969                 intel_primary_formats = i965_primary_formats;
14970                 num_formats = ARRAY_SIZE(i965_primary_formats);
14971
14972                 primary->update_plane = ironlake_update_primary_plane;
14973                 primary->disable_plane = i9xx_disable_primary_plane;
14974         } else if (INTEL_INFO(dev)->gen >= 4) {
14975                 intel_primary_formats = i965_primary_formats;
14976                 num_formats = ARRAY_SIZE(i965_primary_formats);
14977
14978                 primary->update_plane = i9xx_update_primary_plane;
14979                 primary->disable_plane = i9xx_disable_primary_plane;
14980         } else {
14981                 intel_primary_formats = i8xx_primary_formats;
14982                 num_formats = ARRAY_SIZE(i8xx_primary_formats);
14983
14984                 primary->update_plane = i9xx_update_primary_plane;
14985                 primary->disable_plane = i9xx_disable_primary_plane;
14986         }
14987
14988         if (INTEL_INFO(dev)->gen >= 9)
14989                 ret = drm_universal_plane_init(dev, &primary->base, 0,
14990                                                &intel_plane_funcs,
14991                                                intel_primary_formats, num_formats,
14992                                                DRM_PLANE_TYPE_PRIMARY,
14993                                                "plane 1%c", pipe_name(pipe));
14994         else if (INTEL_INFO(dev)->gen >= 5 || IS_G4X(dev))
14995                 ret = drm_universal_plane_init(dev, &primary->base, 0,
14996                                                &intel_plane_funcs,
14997                                                intel_primary_formats, num_formats,
14998                                                DRM_PLANE_TYPE_PRIMARY,
14999                                                "primary %c", pipe_name(pipe));
15000         else
15001                 ret = drm_universal_plane_init(dev, &primary->base, 0,
15002                                                &intel_plane_funcs,
15003                                                intel_primary_formats, num_formats,
15004                                                DRM_PLANE_TYPE_PRIMARY,
15005                                                "plane %c", plane_name(primary->plane));
15006         if (ret)
15007                 goto fail;
15008
15009         if (INTEL_INFO(dev)->gen >= 4)
15010                 intel_create_rotation_property(dev, primary);
15011
15012         drm_plane_helper_add(&primary->base, &intel_plane_helper_funcs);
15013
15014         return &primary->base;
15015
15016 fail:
15017         kfree(state);
15018         kfree(primary);
15019
15020         return NULL;
15021 }
15022
15023 void intel_create_rotation_property(struct drm_device *dev, struct intel_plane *plane)
15024 {
15025         if (!dev->mode_config.rotation_property) {
15026                 unsigned long flags = DRM_ROTATE_0 |
15027                         DRM_ROTATE_180;
15028
15029                 if (INTEL_INFO(dev)->gen >= 9)
15030                         flags |= DRM_ROTATE_90 | DRM_ROTATE_270;
15031
15032                 dev->mode_config.rotation_property =
15033                         drm_mode_create_rotation_property(dev, flags);
15034         }
15035         if (dev->mode_config.rotation_property)
15036                 drm_object_attach_property(&plane->base.base,
15037                                 dev->mode_config.rotation_property,
15038                                 plane->base.state->rotation);
15039 }
15040
15041 static int
15042 intel_check_cursor_plane(struct drm_plane *plane,
15043                          struct intel_crtc_state *crtc_state,
15044                          struct intel_plane_state *state)
15045 {
15046         struct drm_framebuffer *fb = state->base.fb;
15047         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
15048         enum pipe pipe = to_intel_plane(plane)->pipe;
15049         unsigned stride;
15050         int ret;
15051
15052         ret = drm_plane_helper_check_state(&state->base,
15053                                            &state->clip,
15054                                            DRM_PLANE_HELPER_NO_SCALING,
15055                                            DRM_PLANE_HELPER_NO_SCALING,
15056                                            true, true);
15057         if (ret)
15058                 return ret;
15059
15060         /* if we want to turn off the cursor ignore width and height */
15061         if (!obj)
15062                 return 0;
15063
15064         /* Check for which cursor types we support */
15065         if (!cursor_size_ok(plane->dev, state->base.crtc_w, state->base.crtc_h)) {
15066                 DRM_DEBUG("Cursor dimension %dx%d not supported\n",
15067                           state->base.crtc_w, state->base.crtc_h);
15068                 return -EINVAL;
15069         }
15070
15071         stride = roundup_pow_of_two(state->base.crtc_w) * 4;
15072         if (obj->base.size < stride * state->base.crtc_h) {
15073                 DRM_DEBUG_KMS("buffer is too small\n");
15074                 return -ENOMEM;
15075         }
15076
15077         if (fb->modifier[0] != DRM_FORMAT_MOD_NONE) {
15078                 DRM_DEBUG_KMS("cursor cannot be tiled\n");
15079                 return -EINVAL;
15080         }
15081
15082         /*
15083          * There's something wrong with the cursor on CHV pipe C.
15084          * If it straddles the left edge of the screen then
15085          * moving it away from the edge or disabling it often
15086          * results in a pipe underrun, and often that can lead to
15087          * dead pipe (constant underrun reported, and it scans
15088          * out just a solid color). To recover from that, the
15089          * display power well must be turned off and on again.
15090          * Refuse the put the cursor into that compromised position.
15091          */
15092         if (IS_CHERRYVIEW(plane->dev) && pipe == PIPE_C &&
15093             state->base.visible && state->base.crtc_x < 0) {
15094                 DRM_DEBUG_KMS("CHV cursor C not allowed to straddle the left screen edge\n");
15095                 return -EINVAL;
15096         }
15097
15098         return 0;
15099 }
15100
15101 static void
15102 intel_disable_cursor_plane(struct drm_plane *plane,
15103                            struct drm_crtc *crtc)
15104 {
15105         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
15106
15107         intel_crtc->cursor_addr = 0;
15108         intel_crtc_update_cursor(crtc, NULL);
15109 }
15110
15111 static void
15112 intel_update_cursor_plane(struct drm_plane *plane,
15113                           const struct intel_crtc_state *crtc_state,
15114                           const struct intel_plane_state *state)
15115 {
15116         struct drm_crtc *crtc = crtc_state->base.crtc;
15117         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
15118         struct drm_device *dev = plane->dev;
15119         struct drm_i915_gem_object *obj = intel_fb_obj(state->base.fb);
15120         uint32_t addr;
15121
15122         if (!obj)
15123                 addr = 0;
15124         else if (!INTEL_INFO(dev)->cursor_needs_physical)
15125                 addr = i915_gem_object_ggtt_offset(obj, NULL);
15126         else
15127                 addr = obj->phys_handle->busaddr;
15128
15129         intel_crtc->cursor_addr = addr;
15130         intel_crtc_update_cursor(crtc, state);
15131 }
15132
15133 static struct drm_plane *intel_cursor_plane_create(struct drm_device *dev,
15134                                                    int pipe)
15135 {
15136         struct intel_plane *cursor = NULL;
15137         struct intel_plane_state *state = NULL;
15138         int ret;
15139
15140         cursor = kzalloc(sizeof(*cursor), GFP_KERNEL);
15141         if (!cursor)
15142                 goto fail;
15143
15144         state = intel_create_plane_state(&cursor->base);
15145         if (!state)
15146                 goto fail;
15147         cursor->base.state = &state->base;
15148
15149         cursor->can_scale = false;
15150         cursor->max_downscale = 1;
15151         cursor->pipe = pipe;
15152         cursor->plane = pipe;
15153         cursor->frontbuffer_bit = INTEL_FRONTBUFFER_CURSOR(pipe);
15154         cursor->check_plane = intel_check_cursor_plane;
15155         cursor->update_plane = intel_update_cursor_plane;
15156         cursor->disable_plane = intel_disable_cursor_plane;
15157
15158         ret = drm_universal_plane_init(dev, &cursor->base, 0,
15159                                        &intel_plane_funcs,
15160                                        intel_cursor_formats,
15161                                        ARRAY_SIZE(intel_cursor_formats),
15162                                        DRM_PLANE_TYPE_CURSOR,
15163                                        "cursor %c", pipe_name(pipe));
15164         if (ret)
15165                 goto fail;
15166
15167         if (INTEL_INFO(dev)->gen >= 4) {
15168                 if (!dev->mode_config.rotation_property)
15169                         dev->mode_config.rotation_property =
15170                                 drm_mode_create_rotation_property(dev,
15171                                                         DRM_ROTATE_0 |
15172                                                         DRM_ROTATE_180);
15173                 if (dev->mode_config.rotation_property)
15174                         drm_object_attach_property(&cursor->base.base,
15175                                 dev->mode_config.rotation_property,
15176                                 state->base.rotation);
15177         }
15178
15179         if (INTEL_INFO(dev)->gen >=9)
15180                 state->scaler_id = -1;
15181
15182         drm_plane_helper_add(&cursor->base, &intel_plane_helper_funcs);
15183
15184         return &cursor->base;
15185
15186 fail:
15187         kfree(state);
15188         kfree(cursor);
15189
15190         return NULL;
15191 }
15192
15193 static void skl_init_scalers(struct drm_device *dev, struct intel_crtc *intel_crtc,
15194         struct intel_crtc_state *crtc_state)
15195 {
15196         int i;
15197         struct intel_scaler *intel_scaler;
15198         struct intel_crtc_scaler_state *scaler_state = &crtc_state->scaler_state;
15199
15200         for (i = 0; i < intel_crtc->num_scalers; i++) {
15201                 intel_scaler = &scaler_state->scalers[i];
15202                 intel_scaler->in_use = 0;
15203                 intel_scaler->mode = PS_SCALER_MODE_DYN;
15204         }
15205
15206         scaler_state->scaler_id = -1;
15207 }
15208
15209 static void intel_crtc_init(struct drm_device *dev, int pipe)
15210 {
15211         struct drm_i915_private *dev_priv = to_i915(dev);
15212         struct intel_crtc *intel_crtc;
15213         struct intel_crtc_state *crtc_state = NULL;
15214         struct drm_plane *primary = NULL;
15215         struct drm_plane *cursor = NULL;
15216         int ret;
15217
15218         intel_crtc = kzalloc(sizeof(*intel_crtc), GFP_KERNEL);
15219         if (intel_crtc == NULL)
15220                 return;
15221
15222         crtc_state = kzalloc(sizeof(*crtc_state), GFP_KERNEL);
15223         if (!crtc_state)
15224                 goto fail;
15225         intel_crtc->config = crtc_state;
15226         intel_crtc->base.state = &crtc_state->base;
15227         crtc_state->base.crtc = &intel_crtc->base;
15228
15229         /* initialize shared scalers */
15230         if (INTEL_INFO(dev)->gen >= 9) {
15231                 if (pipe == PIPE_C)
15232                         intel_crtc->num_scalers = 1;
15233                 else
15234                         intel_crtc->num_scalers = SKL_NUM_SCALERS;
15235
15236                 skl_init_scalers(dev, intel_crtc, crtc_state);
15237         }
15238
15239         primary = intel_primary_plane_create(dev, pipe);
15240         if (!primary)
15241                 goto fail;
15242
15243         cursor = intel_cursor_plane_create(dev, pipe);
15244         if (!cursor)
15245                 goto fail;
15246
15247         ret = drm_crtc_init_with_planes(dev, &intel_crtc->base, primary,
15248                                         cursor, &intel_crtc_funcs,
15249                                         "pipe %c", pipe_name(pipe));
15250         if (ret)
15251                 goto fail;
15252
15253         /*
15254          * On gen2/3 only plane A can do fbc, but the panel fitter and lvds port
15255          * is hooked to pipe B. Hence we want plane A feeding pipe B.
15256          */
15257         intel_crtc->pipe = pipe;
15258         intel_crtc->plane = pipe;
15259         if (HAS_FBC(dev) && INTEL_INFO(dev)->gen < 4) {
15260                 DRM_DEBUG_KMS("swapping pipes & planes for FBC\n");
15261                 intel_crtc->plane = !pipe;
15262         }
15263
15264         intel_crtc->cursor_base = ~0;
15265         intel_crtc->cursor_cntl = ~0;
15266         intel_crtc->cursor_size = ~0;
15267
15268         intel_crtc->wm.cxsr_allowed = true;
15269
15270         BUG_ON(pipe >= ARRAY_SIZE(dev_priv->plane_to_crtc_mapping) ||
15271                dev_priv->plane_to_crtc_mapping[intel_crtc->plane] != NULL);
15272         dev_priv->plane_to_crtc_mapping[intel_crtc->plane] = &intel_crtc->base;
15273         dev_priv->pipe_to_crtc_mapping[intel_crtc->pipe] = &intel_crtc->base;
15274
15275         drm_crtc_helper_add(&intel_crtc->base, &intel_helper_funcs);
15276
15277         intel_color_init(&intel_crtc->base);
15278
15279         WARN_ON(drm_crtc_index(&intel_crtc->base) != intel_crtc->pipe);
15280         return;
15281
15282 fail:
15283         intel_plane_destroy(primary);
15284         intel_plane_destroy(cursor);
15285         kfree(crtc_state);
15286         kfree(intel_crtc);
15287 }
15288
15289 enum pipe intel_get_pipe_from_connector(struct intel_connector *connector)
15290 {
15291         struct drm_encoder *encoder = connector->base.encoder;
15292         struct drm_device *dev = connector->base.dev;
15293
15294         WARN_ON(!drm_modeset_is_locked(&dev->mode_config.connection_mutex));
15295
15296         if (!encoder || WARN_ON(!encoder->crtc))
15297                 return INVALID_PIPE;
15298
15299         return to_intel_crtc(encoder->crtc)->pipe;
15300 }
15301
15302 int intel_get_pipe_from_crtc_id(struct drm_device *dev, void *data,
15303                                 struct drm_file *file)
15304 {
15305         struct drm_i915_get_pipe_from_crtc_id *pipe_from_crtc_id = data;
15306         struct drm_crtc *drmmode_crtc;
15307         struct intel_crtc *crtc;
15308
15309         drmmode_crtc = drm_crtc_find(dev, pipe_from_crtc_id->crtc_id);
15310         if (!drmmode_crtc)
15311                 return -ENOENT;
15312
15313         crtc = to_intel_crtc(drmmode_crtc);
15314         pipe_from_crtc_id->pipe = crtc->pipe;
15315
15316         return 0;
15317 }
15318
15319 static int intel_encoder_clones(struct intel_encoder *encoder)
15320 {
15321         struct drm_device *dev = encoder->base.dev;
15322         struct intel_encoder *source_encoder;
15323         int index_mask = 0;
15324         int entry = 0;
15325
15326         for_each_intel_encoder(dev, source_encoder) {
15327                 if (encoders_cloneable(encoder, source_encoder))
15328                         index_mask |= (1 << entry);
15329
15330                 entry++;
15331         }
15332
15333         return index_mask;
15334 }
15335
15336 static bool has_edp_a(struct drm_device *dev)
15337 {
15338         struct drm_i915_private *dev_priv = to_i915(dev);
15339
15340         if (!IS_MOBILE(dev))
15341                 return false;
15342
15343         if ((I915_READ(DP_A) & DP_DETECTED) == 0)
15344                 return false;
15345
15346         if (IS_GEN5(dev) && (I915_READ(FUSE_STRAP) & ILK_eDP_A_DISABLE))
15347                 return false;
15348
15349         return true;
15350 }
15351
15352 static bool intel_crt_present(struct drm_device *dev)
15353 {
15354         struct drm_i915_private *dev_priv = to_i915(dev);
15355
15356         if (INTEL_INFO(dev)->gen >= 9)
15357                 return false;
15358
15359         if (IS_HSW_ULT(dev) || IS_BDW_ULT(dev))
15360                 return false;
15361
15362         if (IS_CHERRYVIEW(dev))
15363                 return false;
15364
15365         if (HAS_PCH_LPT_H(dev) && I915_READ(SFUSE_STRAP) & SFUSE_STRAP_CRT_DISABLED)
15366                 return false;
15367
15368         /* DDI E can't be used if DDI A requires 4 lanes */
15369         if (HAS_DDI(dev) && I915_READ(DDI_BUF_CTL(PORT_A)) & DDI_A_4_LANES)
15370                 return false;
15371
15372         if (!dev_priv->vbt.int_crt_support)
15373                 return false;
15374
15375         return true;
15376 }
15377
15378 void intel_pps_unlock_regs_wa(struct drm_i915_private *dev_priv)
15379 {
15380         int pps_num;
15381         int pps_idx;
15382
15383         if (HAS_DDI(dev_priv))
15384                 return;
15385         /*
15386          * This w/a is needed at least on CPT/PPT, but to be sure apply it
15387          * everywhere where registers can be write protected.
15388          */
15389         if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
15390                 pps_num = 2;
15391         else
15392                 pps_num = 1;
15393
15394         for (pps_idx = 0; pps_idx < pps_num; pps_idx++) {
15395                 u32 val = I915_READ(PP_CONTROL(pps_idx));
15396
15397                 val = (val & ~PANEL_UNLOCK_MASK) | PANEL_UNLOCK_REGS;
15398                 I915_WRITE(PP_CONTROL(pps_idx), val);
15399         }
15400 }
15401
15402 static void intel_pps_init(struct drm_i915_private *dev_priv)
15403 {
15404         if (HAS_PCH_SPLIT(dev_priv) || IS_BROXTON(dev_priv))
15405                 dev_priv->pps_mmio_base = PCH_PPS_BASE;
15406         else if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
15407                 dev_priv->pps_mmio_base = VLV_PPS_BASE;
15408         else
15409                 dev_priv->pps_mmio_base = PPS_BASE;
15410
15411         intel_pps_unlock_regs_wa(dev_priv);
15412 }
15413
15414 static void intel_setup_outputs(struct drm_device *dev)
15415 {
15416         struct drm_i915_private *dev_priv = to_i915(dev);
15417         struct intel_encoder *encoder;
15418         bool dpd_is_edp = false;
15419
15420         intel_pps_init(dev_priv);
15421
15422         /*
15423          * intel_edp_init_connector() depends on this completing first, to
15424          * prevent the registeration of both eDP and LVDS and the incorrect
15425          * sharing of the PPS.
15426          */
15427         intel_lvds_init(dev);
15428
15429         if (intel_crt_present(dev))
15430                 intel_crt_init(dev);
15431
15432         if (IS_BROXTON(dev)) {
15433                 /*
15434                  * FIXME: Broxton doesn't support port detection via the
15435                  * DDI_BUF_CTL_A or SFUSE_STRAP registers, find another way to
15436                  * detect the ports.
15437                  */
15438                 intel_ddi_init(dev, PORT_A);
15439                 intel_ddi_init(dev, PORT_B);
15440                 intel_ddi_init(dev, PORT_C);
15441
15442                 intel_dsi_init(dev);
15443         } else if (HAS_DDI(dev)) {
15444                 int found;
15445
15446                 /*
15447                  * Haswell uses DDI functions to detect digital outputs.
15448                  * On SKL pre-D0 the strap isn't connected, so we assume
15449                  * it's there.
15450                  */
15451                 found = I915_READ(DDI_BUF_CTL(PORT_A)) & DDI_INIT_DISPLAY_DETECTED;
15452                 /* WaIgnoreDDIAStrap: skl */
15453                 if (found || IS_SKYLAKE(dev) || IS_KABYLAKE(dev))
15454                         intel_ddi_init(dev, PORT_A);
15455
15456                 /* DDI B, C and D detection is indicated by the SFUSE_STRAP
15457                  * register */
15458                 found = I915_READ(SFUSE_STRAP);
15459
15460                 if (found & SFUSE_STRAP_DDIB_DETECTED)
15461                         intel_ddi_init(dev, PORT_B);
15462                 if (found & SFUSE_STRAP_DDIC_DETECTED)
15463                         intel_ddi_init(dev, PORT_C);
15464                 if (found & SFUSE_STRAP_DDID_DETECTED)
15465                         intel_ddi_init(dev, PORT_D);
15466                 /*
15467                  * On SKL we don't have a way to detect DDI-E so we rely on VBT.
15468                  */
15469                 if ((IS_SKYLAKE(dev) || IS_KABYLAKE(dev)) &&
15470                     (dev_priv->vbt.ddi_port_info[PORT_E].supports_dp ||
15471                      dev_priv->vbt.ddi_port_info[PORT_E].supports_dvi ||
15472                      dev_priv->vbt.ddi_port_info[PORT_E].supports_hdmi))
15473                         intel_ddi_init(dev, PORT_E);
15474
15475         } else if (HAS_PCH_SPLIT(dev)) {
15476                 int found;
15477                 dpd_is_edp = intel_dp_is_edp(dev, PORT_D);
15478
15479                 if (has_edp_a(dev))
15480                         intel_dp_init(dev, DP_A, PORT_A);
15481
15482                 if (I915_READ(PCH_HDMIB) & SDVO_DETECTED) {
15483                         /* PCH SDVOB multiplex with HDMIB */
15484                         found = intel_sdvo_init(dev, PCH_SDVOB, PORT_B);
15485                         if (!found)
15486                                 intel_hdmi_init(dev, PCH_HDMIB, PORT_B);
15487                         if (!found && (I915_READ(PCH_DP_B) & DP_DETECTED))
15488                                 intel_dp_init(dev, PCH_DP_B, PORT_B);
15489                 }
15490
15491                 if (I915_READ(PCH_HDMIC) & SDVO_DETECTED)
15492                         intel_hdmi_init(dev, PCH_HDMIC, PORT_C);
15493
15494                 if (!dpd_is_edp && I915_READ(PCH_HDMID) & SDVO_DETECTED)
15495                         intel_hdmi_init(dev, PCH_HDMID, PORT_D);
15496
15497                 if (I915_READ(PCH_DP_C) & DP_DETECTED)
15498                         intel_dp_init(dev, PCH_DP_C, PORT_C);
15499
15500                 if (I915_READ(PCH_DP_D) & DP_DETECTED)
15501                         intel_dp_init(dev, PCH_DP_D, PORT_D);
15502         } else if (IS_VALLEYVIEW(dev) || IS_CHERRYVIEW(dev)) {
15503                 bool has_edp, has_port;
15504
15505                 /*
15506                  * The DP_DETECTED bit is the latched state of the DDC
15507                  * SDA pin at boot. However since eDP doesn't require DDC
15508                  * (no way to plug in a DP->HDMI dongle) the DDC pins for
15509                  * eDP ports may have been muxed to an alternate function.
15510                  * Thus we can't rely on the DP_DETECTED bit alone to detect
15511                  * eDP ports. Consult the VBT as well as DP_DETECTED to
15512                  * detect eDP ports.
15513                  *
15514                  * Sadly the straps seem to be missing sometimes even for HDMI
15515                  * ports (eg. on Voyo V3 - CHT x7-Z8700), so check both strap
15516                  * and VBT for the presence of the port. Additionally we can't
15517                  * trust the port type the VBT declares as we've seen at least
15518                  * HDMI ports that the VBT claim are DP or eDP.
15519                  */
15520                 has_edp = intel_dp_is_edp(dev, PORT_B);
15521                 has_port = intel_bios_is_port_present(dev_priv, PORT_B);
15522                 if (I915_READ(VLV_DP_B) & DP_DETECTED || has_port)
15523                         has_edp &= intel_dp_init(dev, VLV_DP_B, PORT_B);
15524                 if ((I915_READ(VLV_HDMIB) & SDVO_DETECTED || has_port) && !has_edp)
15525                         intel_hdmi_init(dev, VLV_HDMIB, PORT_B);
15526
15527                 has_edp = intel_dp_is_edp(dev, PORT_C);
15528                 has_port = intel_bios_is_port_present(dev_priv, PORT_C);
15529                 if (I915_READ(VLV_DP_C) & DP_DETECTED || has_port)
15530                         has_edp &= intel_dp_init(dev, VLV_DP_C, PORT_C);
15531                 if ((I915_READ(VLV_HDMIC) & SDVO_DETECTED || has_port) && !has_edp)
15532                         intel_hdmi_init(dev, VLV_HDMIC, PORT_C);
15533
15534                 if (IS_CHERRYVIEW(dev)) {
15535                         /*
15536                          * eDP not supported on port D,
15537                          * so no need to worry about it
15538                          */
15539                         has_port = intel_bios_is_port_present(dev_priv, PORT_D);
15540                         if (I915_READ(CHV_DP_D) & DP_DETECTED || has_port)
15541                                 intel_dp_init(dev, CHV_DP_D, PORT_D);
15542                         if (I915_READ(CHV_HDMID) & SDVO_DETECTED || has_port)
15543                                 intel_hdmi_init(dev, CHV_HDMID, PORT_D);
15544                 }
15545
15546                 intel_dsi_init(dev);
15547         } else if (!IS_GEN2(dev) && !IS_PINEVIEW(dev)) {
15548                 bool found = false;
15549
15550                 if (I915_READ(GEN3_SDVOB) & SDVO_DETECTED) {
15551                         DRM_DEBUG_KMS("probing SDVOB\n");
15552                         found = intel_sdvo_init(dev, GEN3_SDVOB, PORT_B);
15553                         if (!found && IS_G4X(dev)) {
15554                                 DRM_DEBUG_KMS("probing HDMI on SDVOB\n");
15555                                 intel_hdmi_init(dev, GEN4_HDMIB, PORT_B);
15556                         }
15557
15558                         if (!found && IS_G4X(dev))
15559                                 intel_dp_init(dev, DP_B, PORT_B);
15560                 }
15561
15562                 /* Before G4X SDVOC doesn't have its own detect register */
15563
15564                 if (I915_READ(GEN3_SDVOB) & SDVO_DETECTED) {
15565                         DRM_DEBUG_KMS("probing SDVOC\n");
15566                         found = intel_sdvo_init(dev, GEN3_SDVOC, PORT_C);
15567                 }
15568
15569                 if (!found && (I915_READ(GEN3_SDVOC) & SDVO_DETECTED)) {
15570
15571                         if (IS_G4X(dev)) {
15572                                 DRM_DEBUG_KMS("probing HDMI on SDVOC\n");
15573                                 intel_hdmi_init(dev, GEN4_HDMIC, PORT_C);
15574                         }
15575                         if (IS_G4X(dev))
15576                                 intel_dp_init(dev, DP_C, PORT_C);
15577                 }
15578
15579                 if (IS_G4X(dev) &&
15580                     (I915_READ(DP_D) & DP_DETECTED))
15581                         intel_dp_init(dev, DP_D, PORT_D);
15582         } else if (IS_GEN2(dev))
15583                 intel_dvo_init(dev);
15584
15585         if (SUPPORTS_TV(dev))
15586                 intel_tv_init(dev);
15587
15588         intel_psr_init(dev);
15589
15590         for_each_intel_encoder(dev, encoder) {
15591                 encoder->base.possible_crtcs = encoder->crtc_mask;
15592                 encoder->base.possible_clones =
15593                         intel_encoder_clones(encoder);
15594         }
15595
15596         intel_init_pch_refclk(dev);
15597
15598         drm_helper_move_panel_connectors_to_head(dev);
15599 }
15600
15601 static void intel_user_framebuffer_destroy(struct drm_framebuffer *fb)
15602 {
15603         struct drm_device *dev = fb->dev;
15604         struct intel_framebuffer *intel_fb = to_intel_framebuffer(fb);
15605
15606         drm_framebuffer_cleanup(fb);
15607         mutex_lock(&dev->struct_mutex);
15608         WARN_ON(!intel_fb->obj->framebuffer_references--);
15609         i915_gem_object_put(intel_fb->obj);
15610         mutex_unlock(&dev->struct_mutex);
15611         kfree(intel_fb);
15612 }
15613
15614 static int intel_user_framebuffer_create_handle(struct drm_framebuffer *fb,
15615                                                 struct drm_file *file,
15616                                                 unsigned int *handle)
15617 {
15618         struct intel_framebuffer *intel_fb = to_intel_framebuffer(fb);
15619         struct drm_i915_gem_object *obj = intel_fb->obj;
15620
15621         if (obj->userptr.mm) {
15622                 DRM_DEBUG("attempting to use a userptr for a framebuffer, denied\n");
15623                 return -EINVAL;
15624         }
15625
15626         return drm_gem_handle_create(file, &obj->base, handle);
15627 }
15628
15629 static int intel_user_framebuffer_dirty(struct drm_framebuffer *fb,
15630                                         struct drm_file *file,
15631                                         unsigned flags, unsigned color,
15632                                         struct drm_clip_rect *clips,
15633                                         unsigned num_clips)
15634 {
15635         struct drm_device *dev = fb->dev;
15636         struct intel_framebuffer *intel_fb = to_intel_framebuffer(fb);
15637         struct drm_i915_gem_object *obj = intel_fb->obj;
15638
15639         mutex_lock(&dev->struct_mutex);
15640         intel_fb_obj_flush(obj, false, ORIGIN_DIRTYFB);
15641         mutex_unlock(&dev->struct_mutex);
15642
15643         return 0;
15644 }
15645
15646 static const struct drm_framebuffer_funcs intel_fb_funcs = {
15647         .destroy = intel_user_framebuffer_destroy,
15648         .create_handle = intel_user_framebuffer_create_handle,
15649         .dirty = intel_user_framebuffer_dirty,
15650 };
15651
15652 static
15653 u32 intel_fb_pitch_limit(struct drm_device *dev, uint64_t fb_modifier,
15654                          uint32_t pixel_format)
15655 {
15656         u32 gen = INTEL_INFO(dev)->gen;
15657
15658         if (gen >= 9) {
15659                 int cpp = drm_format_plane_cpp(pixel_format, 0);
15660
15661                 /* "The stride in bytes must not exceed the of the size of 8K
15662                  *  pixels and 32K bytes."
15663                  */
15664                 return min(8192 * cpp, 32768);
15665         } else if (gen >= 5 && !IS_VALLEYVIEW(dev) && !IS_CHERRYVIEW(dev)) {
15666                 return 32*1024;
15667         } else if (gen >= 4) {
15668                 if (fb_modifier == I915_FORMAT_MOD_X_TILED)
15669                         return 16*1024;
15670                 else
15671                         return 32*1024;
15672         } else if (gen >= 3) {
15673                 if (fb_modifier == I915_FORMAT_MOD_X_TILED)
15674                         return 8*1024;
15675                 else
15676                         return 16*1024;
15677         } else {
15678                 /* XXX DSPC is limited to 4k tiled */
15679                 return 8*1024;
15680         }
15681 }
15682
15683 static int intel_framebuffer_init(struct drm_device *dev,
15684                                   struct intel_framebuffer *intel_fb,
15685                                   struct drm_mode_fb_cmd2 *mode_cmd,
15686                                   struct drm_i915_gem_object *obj)
15687 {
15688         struct drm_i915_private *dev_priv = to_i915(dev);
15689         unsigned int tiling = i915_gem_object_get_tiling(obj);
15690         int ret;
15691         u32 pitch_limit, stride_alignment;
15692         char *format_name;
15693
15694         WARN_ON(!mutex_is_locked(&dev->struct_mutex));
15695
15696         if (mode_cmd->flags & DRM_MODE_FB_MODIFIERS) {
15697                 /*
15698                  * If there's a fence, enforce that
15699                  * the fb modifier and tiling mode match.
15700                  */
15701                 if (tiling != I915_TILING_NONE &&
15702                     tiling != intel_fb_modifier_to_tiling(mode_cmd->modifier[0])) {
15703                         DRM_DEBUG("tiling_mode doesn't match fb modifier\n");
15704                         return -EINVAL;
15705                 }
15706         } else {
15707                 if (tiling == I915_TILING_X) {
15708                         mode_cmd->modifier[0] = I915_FORMAT_MOD_X_TILED;
15709                 } else if (tiling == I915_TILING_Y) {
15710                         DRM_DEBUG("No Y tiling for legacy addfb\n");
15711                         return -EINVAL;
15712                 }
15713         }
15714
15715         /* Passed in modifier sanity checking. */
15716         switch (mode_cmd->modifier[0]) {
15717         case I915_FORMAT_MOD_Y_TILED:
15718         case I915_FORMAT_MOD_Yf_TILED:
15719                 if (INTEL_INFO(dev)->gen < 9) {
15720                         DRM_DEBUG("Unsupported tiling 0x%llx!\n",
15721                                   mode_cmd->modifier[0]);
15722                         return -EINVAL;
15723                 }
15724         case DRM_FORMAT_MOD_NONE:
15725         case I915_FORMAT_MOD_X_TILED:
15726                 break;
15727         default:
15728                 DRM_DEBUG("Unsupported fb modifier 0x%llx!\n",
15729                           mode_cmd->modifier[0]);
15730                 return -EINVAL;
15731         }
15732
15733         /*
15734          * gen2/3 display engine uses the fence if present,
15735          * so the tiling mode must match the fb modifier exactly.
15736          */
15737         if (INTEL_INFO(dev_priv)->gen < 4 &&
15738             tiling != intel_fb_modifier_to_tiling(mode_cmd->modifier[0])) {
15739                 DRM_DEBUG("tiling_mode must match fb modifier exactly on gen2/3\n");
15740                 return -EINVAL;
15741         }
15742
15743         stride_alignment = intel_fb_stride_alignment(dev_priv,
15744                                                      mode_cmd->modifier[0],
15745                                                      mode_cmd->pixel_format);
15746         if (mode_cmd->pitches[0] & (stride_alignment - 1)) {
15747                 DRM_DEBUG("pitch (%d) must be at least %u byte aligned\n",
15748                           mode_cmd->pitches[0], stride_alignment);
15749                 return -EINVAL;
15750         }
15751
15752         pitch_limit = intel_fb_pitch_limit(dev, mode_cmd->modifier[0],
15753                                            mode_cmd->pixel_format);
15754         if (mode_cmd->pitches[0] > pitch_limit) {
15755                 DRM_DEBUG("%s pitch (%u) must be at less than %d\n",
15756                           mode_cmd->modifier[0] != DRM_FORMAT_MOD_NONE ?
15757                           "tiled" : "linear",
15758                           mode_cmd->pitches[0], pitch_limit);
15759                 return -EINVAL;
15760         }
15761
15762         /*
15763          * If there's a fence, enforce that
15764          * the fb pitch and fence stride match.
15765          */
15766         if (tiling != I915_TILING_NONE &&
15767             mode_cmd->pitches[0] != i915_gem_object_get_stride(obj)) {
15768                 DRM_DEBUG("pitch (%d) must match tiling stride (%d)\n",
15769                           mode_cmd->pitches[0],
15770                           i915_gem_object_get_stride(obj));
15771                 return -EINVAL;
15772         }
15773
15774         /* Reject formats not supported by any plane early. */
15775         switch (mode_cmd->pixel_format) {
15776         case DRM_FORMAT_C8:
15777         case DRM_FORMAT_RGB565:
15778         case DRM_FORMAT_XRGB8888:
15779         case DRM_FORMAT_ARGB8888:
15780                 break;
15781         case DRM_FORMAT_XRGB1555:
15782                 if (INTEL_INFO(dev)->gen > 3) {
15783                         format_name = drm_get_format_name(mode_cmd->pixel_format);
15784                         DRM_DEBUG("unsupported pixel format: %s\n", format_name);
15785                         kfree(format_name);
15786                         return -EINVAL;
15787                 }
15788                 break;
15789         case DRM_FORMAT_ABGR8888:
15790                 if (!IS_VALLEYVIEW(dev) && !IS_CHERRYVIEW(dev) &&
15791                     INTEL_INFO(dev)->gen < 9) {
15792                         format_name = drm_get_format_name(mode_cmd->pixel_format);
15793                         DRM_DEBUG("unsupported pixel format: %s\n", format_name);
15794                         kfree(format_name);
15795                         return -EINVAL;
15796                 }
15797                 break;
15798         case DRM_FORMAT_XBGR8888:
15799         case DRM_FORMAT_XRGB2101010:
15800         case DRM_FORMAT_XBGR2101010:
15801                 if (INTEL_INFO(dev)->gen < 4) {
15802                         format_name = drm_get_format_name(mode_cmd->pixel_format);
15803                         DRM_DEBUG("unsupported pixel format: %s\n", format_name);
15804                         kfree(format_name);
15805                         return -EINVAL;
15806                 }
15807                 break;
15808         case DRM_FORMAT_ABGR2101010:
15809                 if (!IS_VALLEYVIEW(dev) && !IS_CHERRYVIEW(dev)) {
15810                         format_name = drm_get_format_name(mode_cmd->pixel_format);
15811                         DRM_DEBUG("unsupported pixel format: %s\n", format_name);
15812                         kfree(format_name);
15813                         return -EINVAL;
15814                 }
15815                 break;
15816         case DRM_FORMAT_YUYV:
15817         case DRM_FORMAT_UYVY:
15818         case DRM_FORMAT_YVYU:
15819         case DRM_FORMAT_VYUY:
15820                 if (INTEL_INFO(dev)->gen < 5) {
15821                         format_name = drm_get_format_name(mode_cmd->pixel_format);
15822                         DRM_DEBUG("unsupported pixel format: %s\n", format_name);
15823                         kfree(format_name);
15824                         return -EINVAL;
15825                 }
15826                 break;
15827         default:
15828                 format_name = drm_get_format_name(mode_cmd->pixel_format);
15829                 DRM_DEBUG("unsupported pixel format: %s\n", format_name);
15830                 kfree(format_name);
15831                 return -EINVAL;
15832         }
15833
15834         /* FIXME need to adjust LINOFF/TILEOFF accordingly. */
15835         if (mode_cmd->offsets[0] != 0)
15836                 return -EINVAL;
15837
15838         drm_helper_mode_fill_fb_struct(&intel_fb->base, mode_cmd);
15839         intel_fb->obj = obj;
15840
15841         ret = intel_fill_fb_info(dev_priv, &intel_fb->base);
15842         if (ret)
15843                 return ret;
15844
15845         ret = drm_framebuffer_init(dev, &intel_fb->base, &intel_fb_funcs);
15846         if (ret) {
15847                 DRM_ERROR("framebuffer init failed %d\n", ret);
15848                 return ret;
15849         }
15850
15851         intel_fb->obj->framebuffer_references++;
15852
15853         return 0;
15854 }
15855
15856 static struct drm_framebuffer *
15857 intel_user_framebuffer_create(struct drm_device *dev,
15858                               struct drm_file *filp,
15859                               const struct drm_mode_fb_cmd2 *user_mode_cmd)
15860 {
15861         struct drm_framebuffer *fb;
15862         struct drm_i915_gem_object *obj;
15863         struct drm_mode_fb_cmd2 mode_cmd = *user_mode_cmd;
15864
15865         obj = i915_gem_object_lookup(filp, mode_cmd.handles[0]);
15866         if (!obj)
15867                 return ERR_PTR(-ENOENT);
15868
15869         fb = intel_framebuffer_create(dev, &mode_cmd, obj);
15870         if (IS_ERR(fb))
15871                 i915_gem_object_put_unlocked(obj);
15872
15873         return fb;
15874 }
15875
15876 #ifndef CONFIG_DRM_FBDEV_EMULATION
15877 static inline void intel_fbdev_output_poll_changed(struct drm_device *dev)
15878 {
15879 }
15880 #endif
15881
15882 static const struct drm_mode_config_funcs intel_mode_funcs = {
15883         .fb_create = intel_user_framebuffer_create,
15884         .output_poll_changed = intel_fbdev_output_poll_changed,
15885         .atomic_check = intel_atomic_check,
15886         .atomic_commit = intel_atomic_commit,
15887         .atomic_state_alloc = intel_atomic_state_alloc,
15888         .atomic_state_clear = intel_atomic_state_clear,
15889 };
15890
15891 /**
15892  * intel_init_display_hooks - initialize the display modesetting hooks
15893  * @dev_priv: device private
15894  */
15895 void intel_init_display_hooks(struct drm_i915_private *dev_priv)
15896 {
15897         if (INTEL_INFO(dev_priv)->gen >= 9) {
15898                 dev_priv->display.get_pipe_config = haswell_get_pipe_config;
15899                 dev_priv->display.get_initial_plane_config =
15900                         skylake_get_initial_plane_config;
15901                 dev_priv->display.crtc_compute_clock =
15902                         haswell_crtc_compute_clock;
15903                 dev_priv->display.crtc_enable = haswell_crtc_enable;
15904                 dev_priv->display.crtc_disable = haswell_crtc_disable;
15905         } else if (HAS_DDI(dev_priv)) {
15906                 dev_priv->display.get_pipe_config = haswell_get_pipe_config;
15907                 dev_priv->display.get_initial_plane_config =
15908                         ironlake_get_initial_plane_config;
15909                 dev_priv->display.crtc_compute_clock =
15910                         haswell_crtc_compute_clock;
15911                 dev_priv->display.crtc_enable = haswell_crtc_enable;
15912                 dev_priv->display.crtc_disable = haswell_crtc_disable;
15913         } else if (HAS_PCH_SPLIT(dev_priv)) {
15914                 dev_priv->display.get_pipe_config = ironlake_get_pipe_config;
15915                 dev_priv->display.get_initial_plane_config =
15916                         ironlake_get_initial_plane_config;
15917                 dev_priv->display.crtc_compute_clock =
15918                         ironlake_crtc_compute_clock;
15919                 dev_priv->display.crtc_enable = ironlake_crtc_enable;
15920                 dev_priv->display.crtc_disable = ironlake_crtc_disable;
15921         } else if (IS_CHERRYVIEW(dev_priv)) {
15922                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
15923                 dev_priv->display.get_initial_plane_config =
15924                         i9xx_get_initial_plane_config;
15925                 dev_priv->display.crtc_compute_clock = chv_crtc_compute_clock;
15926                 dev_priv->display.crtc_enable = valleyview_crtc_enable;
15927                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
15928         } else if (IS_VALLEYVIEW(dev_priv)) {
15929                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
15930                 dev_priv->display.get_initial_plane_config =
15931                         i9xx_get_initial_plane_config;
15932                 dev_priv->display.crtc_compute_clock = vlv_crtc_compute_clock;
15933                 dev_priv->display.crtc_enable = valleyview_crtc_enable;
15934                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
15935         } else if (IS_G4X(dev_priv)) {
15936                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
15937                 dev_priv->display.get_initial_plane_config =
15938                         i9xx_get_initial_plane_config;
15939                 dev_priv->display.crtc_compute_clock = g4x_crtc_compute_clock;
15940                 dev_priv->display.crtc_enable = i9xx_crtc_enable;
15941                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
15942         } else if (IS_PINEVIEW(dev_priv)) {
15943                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
15944                 dev_priv->display.get_initial_plane_config =
15945                         i9xx_get_initial_plane_config;
15946                 dev_priv->display.crtc_compute_clock = pnv_crtc_compute_clock;
15947                 dev_priv->display.crtc_enable = i9xx_crtc_enable;
15948                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
15949         } else if (!IS_GEN2(dev_priv)) {
15950                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
15951                 dev_priv->display.get_initial_plane_config =
15952                         i9xx_get_initial_plane_config;
15953                 dev_priv->display.crtc_compute_clock = i9xx_crtc_compute_clock;
15954                 dev_priv->display.crtc_enable = i9xx_crtc_enable;
15955                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
15956         } else {
15957                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
15958                 dev_priv->display.get_initial_plane_config =
15959                         i9xx_get_initial_plane_config;
15960                 dev_priv->display.crtc_compute_clock = i8xx_crtc_compute_clock;
15961                 dev_priv->display.crtc_enable = i9xx_crtc_enable;
15962                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
15963         }
15964
15965         /* Returns the core display clock speed */
15966         if (IS_SKYLAKE(dev_priv) || IS_KABYLAKE(dev_priv))
15967                 dev_priv->display.get_display_clock_speed =
15968                         skylake_get_display_clock_speed;
15969         else if (IS_BROXTON(dev_priv))
15970                 dev_priv->display.get_display_clock_speed =
15971                         broxton_get_display_clock_speed;
15972         else if (IS_BROADWELL(dev_priv))
15973                 dev_priv->display.get_display_clock_speed =
15974                         broadwell_get_display_clock_speed;
15975         else if (IS_HASWELL(dev_priv))
15976                 dev_priv->display.get_display_clock_speed =
15977                         haswell_get_display_clock_speed;
15978         else if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
15979                 dev_priv->display.get_display_clock_speed =
15980                         valleyview_get_display_clock_speed;
15981         else if (IS_GEN5(dev_priv))
15982                 dev_priv->display.get_display_clock_speed =
15983                         ilk_get_display_clock_speed;
15984         else if (IS_I945G(dev_priv) || IS_BROADWATER(dev_priv) ||
15985                  IS_GEN6(dev_priv) || IS_IVYBRIDGE(dev_priv))
15986                 dev_priv->display.get_display_clock_speed =
15987                         i945_get_display_clock_speed;
15988         else if (IS_GM45(dev_priv))
15989                 dev_priv->display.get_display_clock_speed =
15990                         gm45_get_display_clock_speed;
15991         else if (IS_CRESTLINE(dev_priv))
15992                 dev_priv->display.get_display_clock_speed =
15993                         i965gm_get_display_clock_speed;
15994         else if (IS_PINEVIEW(dev_priv))
15995                 dev_priv->display.get_display_clock_speed =
15996                         pnv_get_display_clock_speed;
15997         else if (IS_G33(dev_priv) || IS_G4X(dev_priv))
15998                 dev_priv->display.get_display_clock_speed =
15999                         g33_get_display_clock_speed;
16000         else if (IS_I915G(dev_priv))
16001                 dev_priv->display.get_display_clock_speed =
16002                         i915_get_display_clock_speed;
16003         else if (IS_I945GM(dev_priv) || IS_845G(dev_priv))
16004                 dev_priv->display.get_display_clock_speed =
16005                         i9xx_misc_get_display_clock_speed;
16006         else if (IS_I915GM(dev_priv))
16007                 dev_priv->display.get_display_clock_speed =
16008                         i915gm_get_display_clock_speed;
16009         else if (IS_I865G(dev_priv))
16010                 dev_priv->display.get_display_clock_speed =
16011                         i865_get_display_clock_speed;
16012         else if (IS_I85X(dev_priv))
16013                 dev_priv->display.get_display_clock_speed =
16014                         i85x_get_display_clock_speed;
16015         else { /* 830 */
16016                 WARN(!IS_I830(dev_priv), "Unknown platform. Assuming 133 MHz CDCLK\n");
16017                 dev_priv->display.get_display_clock_speed =
16018                         i830_get_display_clock_speed;
16019         }
16020
16021         if (IS_GEN5(dev_priv)) {
16022                 dev_priv->display.fdi_link_train = ironlake_fdi_link_train;
16023         } else if (IS_GEN6(dev_priv)) {
16024                 dev_priv->display.fdi_link_train = gen6_fdi_link_train;
16025         } else if (IS_IVYBRIDGE(dev_priv)) {
16026                 /* FIXME: detect B0+ stepping and use auto training */
16027                 dev_priv->display.fdi_link_train = ivb_manual_fdi_link_train;
16028         } else if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv)) {
16029                 dev_priv->display.fdi_link_train = hsw_fdi_link_train;
16030         }
16031
16032         if (IS_BROADWELL(dev_priv)) {
16033                 dev_priv->display.modeset_commit_cdclk =
16034                         broadwell_modeset_commit_cdclk;
16035                 dev_priv->display.modeset_calc_cdclk =
16036                         broadwell_modeset_calc_cdclk;
16037         } else if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv)) {
16038                 dev_priv->display.modeset_commit_cdclk =
16039                         valleyview_modeset_commit_cdclk;
16040                 dev_priv->display.modeset_calc_cdclk =
16041                         valleyview_modeset_calc_cdclk;
16042         } else if (IS_BROXTON(dev_priv)) {
16043                 dev_priv->display.modeset_commit_cdclk =
16044                         bxt_modeset_commit_cdclk;
16045                 dev_priv->display.modeset_calc_cdclk =
16046                         bxt_modeset_calc_cdclk;
16047         } else if (IS_SKYLAKE(dev_priv) || IS_KABYLAKE(dev_priv)) {
16048                 dev_priv->display.modeset_commit_cdclk =
16049                         skl_modeset_commit_cdclk;
16050                 dev_priv->display.modeset_calc_cdclk =
16051                         skl_modeset_calc_cdclk;
16052         }
16053
16054         if (dev_priv->info.gen >= 9)
16055                 dev_priv->display.update_crtcs = skl_update_crtcs;
16056         else
16057                 dev_priv->display.update_crtcs = intel_update_crtcs;
16058
16059         switch (INTEL_INFO(dev_priv)->gen) {
16060         case 2:
16061                 dev_priv->display.queue_flip = intel_gen2_queue_flip;
16062                 break;
16063
16064         case 3:
16065                 dev_priv->display.queue_flip = intel_gen3_queue_flip;
16066                 break;
16067
16068         case 4:
16069         case 5:
16070                 dev_priv->display.queue_flip = intel_gen4_queue_flip;
16071                 break;
16072
16073         case 6:
16074                 dev_priv->display.queue_flip = intel_gen6_queue_flip;
16075                 break;
16076         case 7:
16077         case 8: /* FIXME(BDW): Check that the gen8 RCS flip works. */
16078                 dev_priv->display.queue_flip = intel_gen7_queue_flip;
16079                 break;
16080         case 9:
16081                 /* Drop through - unsupported since execlist only. */
16082         default:
16083                 /* Default just returns -ENODEV to indicate unsupported */
16084                 dev_priv->display.queue_flip = intel_default_queue_flip;
16085         }
16086 }
16087
16088 /*
16089  * Some BIOSes insist on assuming the GPU's pipe A is enabled at suspend,
16090  * resume, or other times.  This quirk makes sure that's the case for
16091  * affected systems.
16092  */
16093 static void quirk_pipea_force(struct drm_device *dev)
16094 {
16095         struct drm_i915_private *dev_priv = to_i915(dev);
16096
16097         dev_priv->quirks |= QUIRK_PIPEA_FORCE;
16098         DRM_INFO("applying pipe a force quirk\n");
16099 }
16100
16101 static void quirk_pipeb_force(struct drm_device *dev)
16102 {
16103         struct drm_i915_private *dev_priv = to_i915(dev);
16104
16105         dev_priv->quirks |= QUIRK_PIPEB_FORCE;
16106         DRM_INFO("applying pipe b force quirk\n");
16107 }
16108
16109 /*
16110  * Some machines (Lenovo U160) do not work with SSC on LVDS for some reason
16111  */
16112 static void quirk_ssc_force_disable(struct drm_device *dev)
16113 {
16114         struct drm_i915_private *dev_priv = to_i915(dev);
16115         dev_priv->quirks |= QUIRK_LVDS_SSC_DISABLE;
16116         DRM_INFO("applying lvds SSC disable quirk\n");
16117 }
16118
16119 /*
16120  * A machine (e.g. Acer Aspire 5734Z) may need to invert the panel backlight
16121  * brightness value
16122  */
16123 static void quirk_invert_brightness(struct drm_device *dev)
16124 {
16125         struct drm_i915_private *dev_priv = to_i915(dev);
16126         dev_priv->quirks |= QUIRK_INVERT_BRIGHTNESS;
16127         DRM_INFO("applying inverted panel brightness quirk\n");
16128 }
16129
16130 /* Some VBT's incorrectly indicate no backlight is present */
16131 static void quirk_backlight_present(struct drm_device *dev)
16132 {
16133         struct drm_i915_private *dev_priv = to_i915(dev);
16134         dev_priv->quirks |= QUIRK_BACKLIGHT_PRESENT;
16135         DRM_INFO("applying backlight present quirk\n");
16136 }
16137
16138 struct intel_quirk {
16139         int device;
16140         int subsystem_vendor;
16141         int subsystem_device;
16142         void (*hook)(struct drm_device *dev);
16143 };
16144
16145 /* For systems that don't have a meaningful PCI subdevice/subvendor ID */
16146 struct intel_dmi_quirk {
16147         void (*hook)(struct drm_device *dev);
16148         const struct dmi_system_id (*dmi_id_list)[];
16149 };
16150
16151 static int intel_dmi_reverse_brightness(const struct dmi_system_id *id)
16152 {
16153         DRM_INFO("Backlight polarity reversed on %s\n", id->ident);
16154         return 1;
16155 }
16156
16157 static const struct intel_dmi_quirk intel_dmi_quirks[] = {
16158         {
16159                 .dmi_id_list = &(const struct dmi_system_id[]) {
16160                         {
16161                                 .callback = intel_dmi_reverse_brightness,
16162                                 .ident = "NCR Corporation",
16163                                 .matches = {DMI_MATCH(DMI_SYS_VENDOR, "NCR Corporation"),
16164                                             DMI_MATCH(DMI_PRODUCT_NAME, ""),
16165                                 },
16166                         },
16167                         { }  /* terminating entry */
16168                 },
16169                 .hook = quirk_invert_brightness,
16170         },
16171 };
16172
16173 static struct intel_quirk intel_quirks[] = {
16174         /* Toshiba Protege R-205, S-209 needs pipe A force quirk */
16175         { 0x2592, 0x1179, 0x0001, quirk_pipea_force },
16176
16177         /* ThinkPad T60 needs pipe A force quirk (bug #16494) */
16178         { 0x2782, 0x17aa, 0x201a, quirk_pipea_force },
16179
16180         /* 830 needs to leave pipe A & dpll A up */
16181         { 0x3577, PCI_ANY_ID, PCI_ANY_ID, quirk_pipea_force },
16182
16183         /* 830 needs to leave pipe B & dpll B up */
16184         { 0x3577, PCI_ANY_ID, PCI_ANY_ID, quirk_pipeb_force },
16185
16186         /* Lenovo U160 cannot use SSC on LVDS */
16187         { 0x0046, 0x17aa, 0x3920, quirk_ssc_force_disable },
16188
16189         /* Sony Vaio Y cannot use SSC on LVDS */
16190         { 0x0046, 0x104d, 0x9076, quirk_ssc_force_disable },
16191
16192         /* Acer Aspire 5734Z must invert backlight brightness */
16193         { 0x2a42, 0x1025, 0x0459, quirk_invert_brightness },
16194
16195         /* Acer/eMachines G725 */
16196         { 0x2a42, 0x1025, 0x0210, quirk_invert_brightness },
16197
16198         /* Acer/eMachines e725 */
16199         { 0x2a42, 0x1025, 0x0212, quirk_invert_brightness },
16200
16201         /* Acer/Packard Bell NCL20 */
16202         { 0x2a42, 0x1025, 0x034b, quirk_invert_brightness },
16203
16204         /* Acer Aspire 4736Z */
16205         { 0x2a42, 0x1025, 0x0260, quirk_invert_brightness },
16206
16207         /* Acer Aspire 5336 */
16208         { 0x2a42, 0x1025, 0x048a, quirk_invert_brightness },
16209
16210         /* Acer C720 and C720P Chromebooks (Celeron 2955U) have backlights */
16211         { 0x0a06, 0x1025, 0x0a11, quirk_backlight_present },
16212
16213         /* Acer C720 Chromebook (Core i3 4005U) */
16214         { 0x0a16, 0x1025, 0x0a11, quirk_backlight_present },
16215
16216         /* Apple Macbook 2,1 (Core 2 T7400) */
16217         { 0x27a2, 0x8086, 0x7270, quirk_backlight_present },
16218
16219         /* Apple Macbook 4,1 */
16220         { 0x2a02, 0x106b, 0x00a1, quirk_backlight_present },
16221
16222         /* Toshiba CB35 Chromebook (Celeron 2955U) */
16223         { 0x0a06, 0x1179, 0x0a88, quirk_backlight_present },
16224
16225         /* HP Chromebook 14 (Celeron 2955U) */
16226         { 0x0a06, 0x103c, 0x21ed, quirk_backlight_present },
16227
16228         /* Dell Chromebook 11 */
16229         { 0x0a06, 0x1028, 0x0a35, quirk_backlight_present },
16230
16231         /* Dell Chromebook 11 (2015 version) */
16232         { 0x0a16, 0x1028, 0x0a35, quirk_backlight_present },
16233 };
16234
16235 static void intel_init_quirks(struct drm_device *dev)
16236 {
16237         struct pci_dev *d = dev->pdev;
16238         int i;
16239
16240         for (i = 0; i < ARRAY_SIZE(intel_quirks); i++) {
16241                 struct intel_quirk *q = &intel_quirks[i];
16242
16243                 if (d->device == q->device &&
16244                     (d->subsystem_vendor == q->subsystem_vendor ||
16245                      q->subsystem_vendor == PCI_ANY_ID) &&
16246                     (d->subsystem_device == q->subsystem_device ||
16247                      q->subsystem_device == PCI_ANY_ID))
16248                         q->hook(dev);
16249         }
16250         for (i = 0; i < ARRAY_SIZE(intel_dmi_quirks); i++) {
16251                 if (dmi_check_system(*intel_dmi_quirks[i].dmi_id_list) != 0)
16252                         intel_dmi_quirks[i].hook(dev);
16253         }
16254 }
16255
16256 /* Disable the VGA plane that we never use */
16257 static void i915_disable_vga(struct drm_device *dev)
16258 {
16259         struct drm_i915_private *dev_priv = to_i915(dev);
16260         struct pci_dev *pdev = dev_priv->drm.pdev;
16261         u8 sr1;
16262         i915_reg_t vga_reg = i915_vgacntrl_reg(dev);
16263
16264         /* WaEnableVGAAccessThroughIOPort:ctg,elk,ilk,snb,ivb,vlv,hsw */
16265         vga_get_uninterruptible(pdev, VGA_RSRC_LEGACY_IO);
16266         outb(SR01, VGA_SR_INDEX);
16267         sr1 = inb(VGA_SR_DATA);
16268         outb(sr1 | 1<<5, VGA_SR_DATA);
16269         vga_put(pdev, VGA_RSRC_LEGACY_IO);
16270         udelay(300);
16271
16272         I915_WRITE(vga_reg, VGA_DISP_DISABLE);
16273         POSTING_READ(vga_reg);
16274 }
16275
16276 void intel_modeset_init_hw(struct drm_device *dev)
16277 {
16278         struct drm_i915_private *dev_priv = to_i915(dev);
16279
16280         intel_update_cdclk(dev);
16281
16282         dev_priv->atomic_cdclk_freq = dev_priv->cdclk_freq;
16283
16284         intel_init_clock_gating(dev);
16285 }
16286
16287 /*
16288  * Calculate what we think the watermarks should be for the state we've read
16289  * out of the hardware and then immediately program those watermarks so that
16290  * we ensure the hardware settings match our internal state.
16291  *
16292  * We can calculate what we think WM's should be by creating a duplicate of the
16293  * current state (which was constructed during hardware readout) and running it
16294  * through the atomic check code to calculate new watermark values in the
16295  * state object.
16296  */
16297 static void sanitize_watermarks(struct drm_device *dev)
16298 {
16299         struct drm_i915_private *dev_priv = to_i915(dev);
16300         struct drm_atomic_state *state;
16301         struct drm_crtc *crtc;
16302         struct drm_crtc_state *cstate;
16303         struct drm_modeset_acquire_ctx ctx;
16304         int ret;
16305         int i;
16306
16307         /* Only supported on platforms that use atomic watermark design */
16308         if (!dev_priv->display.optimize_watermarks)
16309                 return;
16310
16311         /*
16312          * We need to hold connection_mutex before calling duplicate_state so
16313          * that the connector loop is protected.
16314          */
16315         drm_modeset_acquire_init(&ctx, 0);
16316 retry:
16317         ret = drm_modeset_lock_all_ctx(dev, &ctx);
16318         if (ret == -EDEADLK) {
16319                 drm_modeset_backoff(&ctx);
16320                 goto retry;
16321         } else if (WARN_ON(ret)) {
16322                 goto fail;
16323         }
16324
16325         state = drm_atomic_helper_duplicate_state(dev, &ctx);
16326         if (WARN_ON(IS_ERR(state)))
16327                 goto fail;
16328
16329         /*
16330          * Hardware readout is the only time we don't want to calculate
16331          * intermediate watermarks (since we don't trust the current
16332          * watermarks).
16333          */
16334         to_intel_atomic_state(state)->skip_intermediate_wm = true;
16335
16336         ret = intel_atomic_check(dev, state);
16337         if (ret) {
16338                 /*
16339                  * If we fail here, it means that the hardware appears to be
16340                  * programmed in a way that shouldn't be possible, given our
16341                  * understanding of watermark requirements.  This might mean a
16342                  * mistake in the hardware readout code or a mistake in the
16343                  * watermark calculations for a given platform.  Raise a WARN
16344                  * so that this is noticeable.
16345                  *
16346                  * If this actually happens, we'll have to just leave the
16347                  * BIOS-programmed watermarks untouched and hope for the best.
16348                  */
16349                 WARN(true, "Could not determine valid watermarks for inherited state\n");
16350                 goto fail;
16351         }
16352
16353         /* Write calculated watermark values back */
16354         for_each_crtc_in_state(state, crtc, cstate, i) {
16355                 struct intel_crtc_state *cs = to_intel_crtc_state(cstate);
16356
16357                 cs->wm.need_postvbl_update = true;
16358                 dev_priv->display.optimize_watermarks(cs);
16359         }
16360
16361         drm_atomic_state_free(state);
16362 fail:
16363         drm_modeset_drop_locks(&ctx);
16364         drm_modeset_acquire_fini(&ctx);
16365 }
16366
16367 void intel_modeset_init(struct drm_device *dev)
16368 {
16369         struct drm_i915_private *dev_priv = to_i915(dev);
16370         struct i915_ggtt *ggtt = &dev_priv->ggtt;
16371         int sprite, ret;
16372         enum pipe pipe;
16373         struct intel_crtc *crtc;
16374
16375         drm_mode_config_init(dev);
16376
16377         dev->mode_config.min_width = 0;
16378         dev->mode_config.min_height = 0;
16379
16380         dev->mode_config.preferred_depth = 24;
16381         dev->mode_config.prefer_shadow = 1;
16382
16383         dev->mode_config.allow_fb_modifiers = true;
16384
16385         dev->mode_config.funcs = &intel_mode_funcs;
16386
16387         intel_init_quirks(dev);
16388
16389         intel_init_pm(dev);
16390
16391         if (INTEL_INFO(dev)->num_pipes == 0)
16392                 return;
16393
16394         /*
16395          * There may be no VBT; and if the BIOS enabled SSC we can
16396          * just keep using it to avoid unnecessary flicker.  Whereas if the
16397          * BIOS isn't using it, don't assume it will work even if the VBT
16398          * indicates as much.
16399          */
16400         if (HAS_PCH_IBX(dev) || HAS_PCH_CPT(dev)) {
16401                 bool bios_lvds_use_ssc = !!(I915_READ(PCH_DREF_CONTROL) &
16402                                             DREF_SSC1_ENABLE);
16403
16404                 if (dev_priv->vbt.lvds_use_ssc != bios_lvds_use_ssc) {
16405                         DRM_DEBUG_KMS("SSC %sabled by BIOS, overriding VBT which says %sabled\n",
16406                                      bios_lvds_use_ssc ? "en" : "dis",
16407                                      dev_priv->vbt.lvds_use_ssc ? "en" : "dis");
16408                         dev_priv->vbt.lvds_use_ssc = bios_lvds_use_ssc;
16409                 }
16410         }
16411
16412         if (IS_GEN2(dev)) {
16413                 dev->mode_config.max_width = 2048;
16414                 dev->mode_config.max_height = 2048;
16415         } else if (IS_GEN3(dev)) {
16416                 dev->mode_config.max_width = 4096;
16417                 dev->mode_config.max_height = 4096;
16418         } else {
16419                 dev->mode_config.max_width = 8192;
16420                 dev->mode_config.max_height = 8192;
16421         }
16422
16423         if (IS_845G(dev) || IS_I865G(dev)) {
16424                 dev->mode_config.cursor_width = IS_845G(dev) ? 64 : 512;
16425                 dev->mode_config.cursor_height = 1023;
16426         } else if (IS_GEN2(dev)) {
16427                 dev->mode_config.cursor_width = GEN2_CURSOR_WIDTH;
16428                 dev->mode_config.cursor_height = GEN2_CURSOR_HEIGHT;
16429         } else {
16430                 dev->mode_config.cursor_width = MAX_CURSOR_WIDTH;
16431                 dev->mode_config.cursor_height = MAX_CURSOR_HEIGHT;
16432         }
16433
16434         dev->mode_config.fb_base = ggtt->mappable_base;
16435
16436         DRM_DEBUG_KMS("%d display pipe%s available.\n",
16437                       INTEL_INFO(dev)->num_pipes,
16438                       INTEL_INFO(dev)->num_pipes > 1 ? "s" : "");
16439
16440         for_each_pipe(dev_priv, pipe) {
16441                 intel_crtc_init(dev, pipe);
16442                 for_each_sprite(dev_priv, pipe, sprite) {
16443                         ret = intel_plane_init(dev, pipe, sprite);
16444                         if (ret)
16445                                 DRM_DEBUG_KMS("pipe %c sprite %c init failed: %d\n",
16446                                               pipe_name(pipe), sprite_name(pipe, sprite), ret);
16447                 }
16448         }
16449
16450         intel_update_czclk(dev_priv);
16451         intel_update_cdclk(dev);
16452         dev_priv->atomic_cdclk_freq = dev_priv->cdclk_freq;
16453
16454         intel_shared_dpll_init(dev);
16455
16456         if (dev_priv->max_cdclk_freq == 0)
16457                 intel_update_max_cdclk(dev);
16458
16459         /* Just disable it once at startup */
16460         i915_disable_vga(dev);
16461         intel_setup_outputs(dev);
16462
16463         drm_modeset_lock_all(dev);
16464         intel_modeset_setup_hw_state(dev);
16465         drm_modeset_unlock_all(dev);
16466
16467         for_each_intel_crtc(dev, crtc) {
16468                 struct intel_initial_plane_config plane_config = {};
16469
16470                 if (!crtc->active)
16471                         continue;
16472
16473                 /*
16474                  * Note that reserving the BIOS fb up front prevents us
16475                  * from stuffing other stolen allocations like the ring
16476                  * on top.  This prevents some ugliness at boot time, and
16477                  * can even allow for smooth boot transitions if the BIOS
16478                  * fb is large enough for the active pipe configuration.
16479                  */
16480                 dev_priv->display.get_initial_plane_config(crtc,
16481                                                            &plane_config);
16482
16483                 /*
16484                  * If the fb is shared between multiple heads, we'll
16485                  * just get the first one.
16486                  */
16487                 intel_find_initial_plane_obj(crtc, &plane_config);
16488         }
16489
16490         /*
16491          * Make sure hardware watermarks really match the state we read out.
16492          * Note that we need to do this after reconstructing the BIOS fb's
16493          * since the watermark calculation done here will use pstate->fb.
16494          */
16495         sanitize_watermarks(dev);
16496 }
16497
16498 static void intel_enable_pipe_a(struct drm_device *dev)
16499 {
16500         struct intel_connector *connector;
16501         struct drm_connector *crt = NULL;
16502         struct intel_load_detect_pipe load_detect_temp;
16503         struct drm_modeset_acquire_ctx *ctx = dev->mode_config.acquire_ctx;
16504
16505         /* We can't just switch on the pipe A, we need to set things up with a
16506          * proper mode and output configuration. As a gross hack, enable pipe A
16507          * by enabling the load detect pipe once. */
16508         for_each_intel_connector(dev, connector) {
16509                 if (connector->encoder->type == INTEL_OUTPUT_ANALOG) {
16510                         crt = &connector->base;
16511                         break;
16512                 }
16513         }
16514
16515         if (!crt)
16516                 return;
16517
16518         if (intel_get_load_detect_pipe(crt, NULL, &load_detect_temp, ctx))
16519                 intel_release_load_detect_pipe(crt, &load_detect_temp, ctx);
16520 }
16521
16522 static bool
16523 intel_check_plane_mapping(struct intel_crtc *crtc)
16524 {
16525         struct drm_device *dev = crtc->base.dev;
16526         struct drm_i915_private *dev_priv = to_i915(dev);
16527         u32 val;
16528
16529         if (INTEL_INFO(dev)->num_pipes == 1)
16530                 return true;
16531
16532         val = I915_READ(DSPCNTR(!crtc->plane));
16533
16534         if ((val & DISPLAY_PLANE_ENABLE) &&
16535             (!!(val & DISPPLANE_SEL_PIPE_MASK) == crtc->pipe))
16536                 return false;
16537
16538         return true;
16539 }
16540
16541 static bool intel_crtc_has_encoders(struct intel_crtc *crtc)
16542 {
16543         struct drm_device *dev = crtc->base.dev;
16544         struct intel_encoder *encoder;
16545
16546         for_each_encoder_on_crtc(dev, &crtc->base, encoder)
16547                 return true;
16548
16549         return false;
16550 }
16551
16552 static struct intel_connector *intel_encoder_find_connector(struct intel_encoder *encoder)
16553 {
16554         struct drm_device *dev = encoder->base.dev;
16555         struct intel_connector *connector;
16556
16557         for_each_connector_on_encoder(dev, &encoder->base, connector)
16558                 return connector;
16559
16560         return NULL;
16561 }
16562
16563 static bool has_pch_trancoder(struct drm_i915_private *dev_priv,
16564                               enum transcoder pch_transcoder)
16565 {
16566         return HAS_PCH_IBX(dev_priv) || HAS_PCH_CPT(dev_priv) ||
16567                 (HAS_PCH_LPT_H(dev_priv) && pch_transcoder == TRANSCODER_A);
16568 }
16569
16570 static void intel_sanitize_crtc(struct intel_crtc *crtc)
16571 {
16572         struct drm_device *dev = crtc->base.dev;
16573         struct drm_i915_private *dev_priv = to_i915(dev);
16574         enum transcoder cpu_transcoder = crtc->config->cpu_transcoder;
16575
16576         /* Clear any frame start delays used for debugging left by the BIOS */
16577         if (!transcoder_is_dsi(cpu_transcoder)) {
16578                 i915_reg_t reg = PIPECONF(cpu_transcoder);
16579
16580                 I915_WRITE(reg,
16581                            I915_READ(reg) & ~PIPECONF_FRAME_START_DELAY_MASK);
16582         }
16583
16584         /* restore vblank interrupts to correct state */
16585         drm_crtc_vblank_reset(&crtc->base);
16586         if (crtc->active) {
16587                 struct intel_plane *plane;
16588
16589                 drm_crtc_vblank_on(&crtc->base);
16590
16591                 /* Disable everything but the primary plane */
16592                 for_each_intel_plane_on_crtc(dev, crtc, plane) {
16593                         if (plane->base.type == DRM_PLANE_TYPE_PRIMARY)
16594                                 continue;
16595
16596                         plane->disable_plane(&plane->base, &crtc->base);
16597                 }
16598         }
16599
16600         /* We need to sanitize the plane -> pipe mapping first because this will
16601          * disable the crtc (and hence change the state) if it is wrong. Note
16602          * that gen4+ has a fixed plane -> pipe mapping.  */
16603         if (INTEL_INFO(dev)->gen < 4 && !intel_check_plane_mapping(crtc)) {
16604                 bool plane;
16605
16606                 DRM_DEBUG_KMS("[CRTC:%d:%s] wrong plane connection detected!\n",
16607                               crtc->base.base.id, crtc->base.name);
16608
16609                 /* Pipe has the wrong plane attached and the plane is active.
16610                  * Temporarily change the plane mapping and disable everything
16611                  * ...  */
16612                 plane = crtc->plane;
16613                 to_intel_plane_state(crtc->base.primary->state)->base.visible = true;
16614                 crtc->plane = !plane;
16615                 intel_crtc_disable_noatomic(&crtc->base);
16616                 crtc->plane = plane;
16617         }
16618
16619         if (dev_priv->quirks & QUIRK_PIPEA_FORCE &&
16620             crtc->pipe == PIPE_A && !crtc->active) {
16621                 /* BIOS forgot to enable pipe A, this mostly happens after
16622                  * resume. Force-enable the pipe to fix this, the update_dpms
16623                  * call below we restore the pipe to the right state, but leave
16624                  * the required bits on. */
16625                 intel_enable_pipe_a(dev);
16626         }
16627
16628         /* Adjust the state of the output pipe according to whether we
16629          * have active connectors/encoders. */
16630         if (crtc->active && !intel_crtc_has_encoders(crtc))
16631                 intel_crtc_disable_noatomic(&crtc->base);
16632
16633         if (crtc->active || HAS_GMCH_DISPLAY(dev)) {
16634                 /*
16635                  * We start out with underrun reporting disabled to avoid races.
16636                  * For correct bookkeeping mark this on active crtcs.
16637                  *
16638                  * Also on gmch platforms we dont have any hardware bits to
16639                  * disable the underrun reporting. Which means we need to start
16640                  * out with underrun reporting disabled also on inactive pipes,
16641                  * since otherwise we'll complain about the garbage we read when
16642                  * e.g. coming up after runtime pm.
16643                  *
16644                  * No protection against concurrent access is required - at
16645                  * worst a fifo underrun happens which also sets this to false.
16646                  */
16647                 crtc->cpu_fifo_underrun_disabled = true;
16648                 /*
16649                  * We track the PCH trancoder underrun reporting state
16650                  * within the crtc. With crtc for pipe A housing the underrun
16651                  * reporting state for PCH transcoder A, crtc for pipe B housing
16652                  * it for PCH transcoder B, etc. LPT-H has only PCH transcoder A,
16653                  * and marking underrun reporting as disabled for the non-existing
16654                  * PCH transcoders B and C would prevent enabling the south
16655                  * error interrupt (see cpt_can_enable_serr_int()).
16656                  */
16657                 if (has_pch_trancoder(dev_priv, (enum transcoder)crtc->pipe))
16658                         crtc->pch_fifo_underrun_disabled = true;
16659         }
16660 }
16661
16662 static void intel_sanitize_encoder(struct intel_encoder *encoder)
16663 {
16664         struct intel_connector *connector;
16665
16666         /* We need to check both for a crtc link (meaning that the
16667          * encoder is active and trying to read from a pipe) and the
16668          * pipe itself being active. */
16669         bool has_active_crtc = encoder->base.crtc &&
16670                 to_intel_crtc(encoder->base.crtc)->active;
16671
16672         connector = intel_encoder_find_connector(encoder);
16673         if (connector && !has_active_crtc) {
16674                 DRM_DEBUG_KMS("[ENCODER:%d:%s] has active connectors but no active pipe!\n",
16675                               encoder->base.base.id,
16676                               encoder->base.name);
16677
16678                 /* Connector is active, but has no active pipe. This is
16679                  * fallout from our resume register restoring. Disable
16680                  * the encoder manually again. */
16681                 if (encoder->base.crtc) {
16682                         struct drm_crtc_state *crtc_state = encoder->base.crtc->state;
16683
16684                         DRM_DEBUG_KMS("[ENCODER:%d:%s] manually disabled\n",
16685                                       encoder->base.base.id,
16686                                       encoder->base.name);
16687                         encoder->disable(encoder, to_intel_crtc_state(crtc_state), connector->base.state);
16688                         if (encoder->post_disable)
16689                                 encoder->post_disable(encoder, to_intel_crtc_state(crtc_state), connector->base.state);
16690                 }
16691                 encoder->base.crtc = NULL;
16692
16693                 /* Inconsistent output/port/pipe state happens presumably due to
16694                  * a bug in one of the get_hw_state functions. Or someplace else
16695                  * in our code, like the register restore mess on resume. Clamp
16696                  * things to off as a safer default. */
16697
16698                 connector->base.dpms = DRM_MODE_DPMS_OFF;
16699                 connector->base.encoder = NULL;
16700         }
16701         /* Enabled encoders without active connectors will be fixed in
16702          * the crtc fixup. */
16703 }
16704
16705 void i915_redisable_vga_power_on(struct drm_device *dev)
16706 {
16707         struct drm_i915_private *dev_priv = to_i915(dev);
16708         i915_reg_t vga_reg = i915_vgacntrl_reg(dev);
16709
16710         if (!(I915_READ(vga_reg) & VGA_DISP_DISABLE)) {
16711                 DRM_DEBUG_KMS("Something enabled VGA plane, disabling it\n");
16712                 i915_disable_vga(dev);
16713         }
16714 }
16715
16716 void i915_redisable_vga(struct drm_device *dev)
16717 {
16718         struct drm_i915_private *dev_priv = to_i915(dev);
16719
16720         /* This function can be called both from intel_modeset_setup_hw_state or
16721          * at a very early point in our resume sequence, where the power well
16722          * structures are not yet restored. Since this function is at a very
16723          * paranoid "someone might have enabled VGA while we were not looking"
16724          * level, just check if the power well is enabled instead of trying to
16725          * follow the "don't touch the power well if we don't need it" policy
16726          * the rest of the driver uses. */
16727         if (!intel_display_power_get_if_enabled(dev_priv, POWER_DOMAIN_VGA))
16728                 return;
16729
16730         i915_redisable_vga_power_on(dev);
16731
16732         intel_display_power_put(dev_priv, POWER_DOMAIN_VGA);
16733 }
16734
16735 static bool primary_get_hw_state(struct intel_plane *plane)
16736 {
16737         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
16738
16739         return I915_READ(DSPCNTR(plane->plane)) & DISPLAY_PLANE_ENABLE;
16740 }
16741
16742 /* FIXME read out full plane state for all planes */
16743 static void readout_plane_state(struct intel_crtc *crtc)
16744 {
16745         struct drm_plane *primary = crtc->base.primary;
16746         struct intel_plane_state *plane_state =
16747                 to_intel_plane_state(primary->state);
16748
16749         plane_state->base.visible = crtc->active &&
16750                 primary_get_hw_state(to_intel_plane(primary));
16751
16752         if (plane_state->base.visible)
16753                 crtc->base.state->plane_mask |= 1 << drm_plane_index(primary);
16754 }
16755
16756 static void intel_modeset_readout_hw_state(struct drm_device *dev)
16757 {
16758         struct drm_i915_private *dev_priv = to_i915(dev);
16759         enum pipe pipe;
16760         struct intel_crtc *crtc;
16761         struct intel_encoder *encoder;
16762         struct intel_connector *connector;
16763         int i;
16764
16765         dev_priv->active_crtcs = 0;
16766
16767         for_each_intel_crtc(dev, crtc) {
16768                 struct intel_crtc_state *crtc_state = crtc->config;
16769
16770                 __drm_atomic_helper_crtc_destroy_state(&crtc_state->base);
16771                 memset(crtc_state, 0, sizeof(*crtc_state));
16772                 crtc_state->base.crtc = &crtc->base;
16773
16774                 crtc_state->base.active = crtc_state->base.enable =
16775                         dev_priv->display.get_pipe_config(crtc, crtc_state);
16776
16777                 crtc->base.enabled = crtc_state->base.enable;
16778                 crtc->active = crtc_state->base.active;
16779
16780                 if (crtc_state->base.active)
16781                         dev_priv->active_crtcs |= 1 << crtc->pipe;
16782
16783                 readout_plane_state(crtc);
16784
16785                 DRM_DEBUG_KMS("[CRTC:%d:%s] hw state readout: %s\n",
16786                               crtc->base.base.id, crtc->base.name,
16787                               crtc->active ? "enabled" : "disabled");
16788         }
16789
16790         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
16791                 struct intel_shared_dpll *pll = &dev_priv->shared_dplls[i];
16792
16793                 pll->on = pll->funcs.get_hw_state(dev_priv, pll,
16794                                                   &pll->config.hw_state);
16795                 pll->config.crtc_mask = 0;
16796                 for_each_intel_crtc(dev, crtc) {
16797                         if (crtc->active && crtc->config->shared_dpll == pll)
16798                                 pll->config.crtc_mask |= 1 << crtc->pipe;
16799                 }
16800                 pll->active_mask = pll->config.crtc_mask;
16801
16802                 DRM_DEBUG_KMS("%s hw state readout: crtc_mask 0x%08x, on %i\n",
16803                               pll->name, pll->config.crtc_mask, pll->on);
16804         }
16805
16806         for_each_intel_encoder(dev, encoder) {
16807                 pipe = 0;
16808
16809                 if (encoder->get_hw_state(encoder, &pipe)) {
16810                         crtc = to_intel_crtc(dev_priv->pipe_to_crtc_mapping[pipe]);
16811                         encoder->base.crtc = &crtc->base;
16812                         crtc->config->output_types |= 1 << encoder->type;
16813                         encoder->get_config(encoder, crtc->config);
16814                 } else {
16815                         encoder->base.crtc = NULL;
16816                 }
16817
16818                 DRM_DEBUG_KMS("[ENCODER:%d:%s] hw state readout: %s, pipe %c\n",
16819                               encoder->base.base.id,
16820                               encoder->base.name,
16821                               encoder->base.crtc ? "enabled" : "disabled",
16822                               pipe_name(pipe));
16823         }
16824
16825         for_each_intel_connector(dev, connector) {
16826                 if (connector->get_hw_state(connector)) {
16827                         connector->base.dpms = DRM_MODE_DPMS_ON;
16828
16829                         encoder = connector->encoder;
16830                         connector->base.encoder = &encoder->base;
16831
16832                         if (encoder->base.crtc &&
16833                             encoder->base.crtc->state->active) {
16834                                 /*
16835                                  * This has to be done during hardware readout
16836                                  * because anything calling .crtc_disable may
16837                                  * rely on the connector_mask being accurate.
16838                                  */
16839                                 encoder->base.crtc->state->connector_mask |=
16840                                         1 << drm_connector_index(&connector->base);
16841                                 encoder->base.crtc->state->encoder_mask |=
16842                                         1 << drm_encoder_index(&encoder->base);
16843                         }
16844
16845                 } else {
16846                         connector->base.dpms = DRM_MODE_DPMS_OFF;
16847                         connector->base.encoder = NULL;
16848                 }
16849                 DRM_DEBUG_KMS("[CONNECTOR:%d:%s] hw state readout: %s\n",
16850                               connector->base.base.id,
16851                               connector->base.name,
16852                               connector->base.encoder ? "enabled" : "disabled");
16853         }
16854
16855         for_each_intel_crtc(dev, crtc) {
16856                 int pixclk = 0;
16857
16858                 crtc->base.hwmode = crtc->config->base.adjusted_mode;
16859
16860                 memset(&crtc->base.mode, 0, sizeof(crtc->base.mode));
16861                 if (crtc->base.state->active) {
16862                         intel_mode_from_pipe_config(&crtc->base.mode, crtc->config);
16863                         intel_mode_from_pipe_config(&crtc->base.state->adjusted_mode, crtc->config);
16864                         WARN_ON(drm_atomic_set_mode_for_crtc(crtc->base.state, &crtc->base.mode));
16865
16866                         /*
16867                          * The initial mode needs to be set in order to keep
16868                          * the atomic core happy. It wants a valid mode if the
16869                          * crtc's enabled, so we do the above call.
16870                          *
16871                          * At this point some state updated by the connectors
16872                          * in their ->detect() callback has not run yet, so
16873                          * no recalculation can be done yet.
16874                          *
16875                          * Even if we could do a recalculation and modeset
16876                          * right now it would cause a double modeset if
16877                          * fbdev or userspace chooses a different initial mode.
16878                          *
16879                          * If that happens, someone indicated they wanted a
16880                          * mode change, which means it's safe to do a full
16881                          * recalculation.
16882                          */
16883                         crtc->base.state->mode.private_flags = I915_MODE_FLAG_INHERITED;
16884
16885                         if (INTEL_GEN(dev_priv) >= 9 || IS_BROADWELL(dev_priv))
16886                                 pixclk = ilk_pipe_pixel_rate(crtc->config);
16887                         else if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
16888                                 pixclk = crtc->config->base.adjusted_mode.crtc_clock;
16889                         else
16890                                 WARN_ON(dev_priv->display.modeset_calc_cdclk);
16891
16892                         /* pixel rate mustn't exceed 95% of cdclk with IPS on BDW */
16893                         if (IS_BROADWELL(dev_priv) && crtc->config->ips_enabled)
16894                                 pixclk = DIV_ROUND_UP(pixclk * 100, 95);
16895
16896                         drm_calc_timestamping_constants(&crtc->base, &crtc->base.hwmode);
16897                         update_scanline_offset(crtc);
16898                 }
16899
16900                 dev_priv->min_pixclk[crtc->pipe] = pixclk;
16901
16902                 intel_pipe_config_sanity_check(dev_priv, crtc->config);
16903         }
16904 }
16905
16906 /* Scan out the current hw modeset state,
16907  * and sanitizes it to the current state
16908  */
16909 static void
16910 intel_modeset_setup_hw_state(struct drm_device *dev)
16911 {
16912         struct drm_i915_private *dev_priv = to_i915(dev);
16913         enum pipe pipe;
16914         struct intel_crtc *crtc;
16915         struct intel_encoder *encoder;
16916         int i;
16917
16918         intel_modeset_readout_hw_state(dev);
16919
16920         /* HW state is read out, now we need to sanitize this mess. */
16921         for_each_intel_encoder(dev, encoder) {
16922                 intel_sanitize_encoder(encoder);
16923         }
16924
16925         for_each_pipe(dev_priv, pipe) {
16926                 crtc = to_intel_crtc(dev_priv->pipe_to_crtc_mapping[pipe]);
16927                 intel_sanitize_crtc(crtc);
16928                 intel_dump_pipe_config(crtc, crtc->config,
16929                                        "[setup_hw_state]");
16930         }
16931
16932         intel_modeset_update_connector_atomic_state(dev);
16933
16934         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
16935                 struct intel_shared_dpll *pll = &dev_priv->shared_dplls[i];
16936
16937                 if (!pll->on || pll->active_mask)
16938                         continue;
16939
16940                 DRM_DEBUG_KMS("%s enabled but not in use, disabling\n", pll->name);
16941
16942                 pll->funcs.disable(dev_priv, pll);
16943                 pll->on = false;
16944         }
16945
16946         if (IS_VALLEYVIEW(dev) || IS_CHERRYVIEW(dev))
16947                 vlv_wm_get_hw_state(dev);
16948         else if (IS_GEN9(dev))
16949                 skl_wm_get_hw_state(dev);
16950         else if (HAS_PCH_SPLIT(dev))
16951                 ilk_wm_get_hw_state(dev);
16952
16953         for_each_intel_crtc(dev, crtc) {
16954                 unsigned long put_domains;
16955
16956                 put_domains = modeset_get_crtc_power_domains(&crtc->base, crtc->config);
16957                 if (WARN_ON(put_domains))
16958                         modeset_put_power_domains(dev_priv, put_domains);
16959         }
16960         intel_display_set_init_power(dev_priv, false);
16961
16962         intel_fbc_init_pipe_state(dev_priv);
16963 }
16964
16965 void intel_display_resume(struct drm_device *dev)
16966 {
16967         struct drm_i915_private *dev_priv = to_i915(dev);
16968         struct drm_atomic_state *state = dev_priv->modeset_restore_state;
16969         struct drm_modeset_acquire_ctx ctx;
16970         int ret;
16971
16972         dev_priv->modeset_restore_state = NULL;
16973         if (state)
16974                 state->acquire_ctx = &ctx;
16975
16976         /*
16977          * This is a cludge because with real atomic modeset mode_config.mutex
16978          * won't be taken. Unfortunately some probed state like
16979          * audio_codec_enable is still protected by mode_config.mutex, so lock
16980          * it here for now.
16981          */
16982         mutex_lock(&dev->mode_config.mutex);
16983         drm_modeset_acquire_init(&ctx, 0);
16984
16985         while (1) {
16986                 ret = drm_modeset_lock_all_ctx(dev, &ctx);
16987                 if (ret != -EDEADLK)
16988                         break;
16989
16990                 drm_modeset_backoff(&ctx);
16991         }
16992
16993         if (!ret)
16994                 ret = __intel_display_resume(dev, state);
16995
16996         drm_modeset_drop_locks(&ctx);
16997         drm_modeset_acquire_fini(&ctx);
16998         mutex_unlock(&dev->mode_config.mutex);
16999
17000         if (ret) {
17001                 DRM_ERROR("Restoring old state failed with %i\n", ret);
17002                 drm_atomic_state_free(state);
17003         }
17004 }
17005
17006 void intel_modeset_gem_init(struct drm_device *dev)
17007 {
17008         struct drm_i915_private *dev_priv = to_i915(dev);
17009         struct drm_crtc *c;
17010         struct drm_i915_gem_object *obj;
17011
17012         intel_init_gt_powersave(dev_priv);
17013
17014         intel_modeset_init_hw(dev);
17015
17016         intel_setup_overlay(dev_priv);
17017
17018         /*
17019          * Make sure any fbs we allocated at startup are properly
17020          * pinned & fenced.  When we do the allocation it's too early
17021          * for this.
17022          */
17023         for_each_crtc(dev, c) {
17024                 struct i915_vma *vma;
17025
17026                 obj = intel_fb_obj(c->primary->fb);
17027                 if (obj == NULL)
17028                         continue;
17029
17030                 mutex_lock(&dev->struct_mutex);
17031                 vma = intel_pin_and_fence_fb_obj(c->primary->fb,
17032                                                  c->primary->state->rotation);
17033                 mutex_unlock(&dev->struct_mutex);
17034                 if (IS_ERR(vma)) {
17035                         DRM_ERROR("failed to pin boot fb on pipe %d\n",
17036                                   to_intel_crtc(c)->pipe);
17037                         drm_framebuffer_unreference(c->primary->fb);
17038                         c->primary->fb = NULL;
17039                         c->primary->crtc = c->primary->state->crtc = NULL;
17040                         update_state_fb(c->primary);
17041                         c->state->plane_mask &= ~(1 << drm_plane_index(c->primary));
17042                 }
17043         }
17044 }
17045
17046 int intel_connector_register(struct drm_connector *connector)
17047 {
17048         struct intel_connector *intel_connector = to_intel_connector(connector);
17049         int ret;
17050
17051         ret = intel_backlight_device_register(intel_connector);
17052         if (ret)
17053                 goto err;
17054
17055         return 0;
17056
17057 err:
17058         return ret;
17059 }
17060
17061 void intel_connector_unregister(struct drm_connector *connector)
17062 {
17063         struct intel_connector *intel_connector = to_intel_connector(connector);
17064
17065         intel_backlight_device_unregister(intel_connector);
17066         intel_panel_destroy_backlight(connector);
17067 }
17068
17069 void intel_modeset_cleanup(struct drm_device *dev)
17070 {
17071         struct drm_i915_private *dev_priv = to_i915(dev);
17072
17073         intel_disable_gt_powersave(dev_priv);
17074
17075         /*
17076          * Interrupts and polling as the first thing to avoid creating havoc.
17077          * Too much stuff here (turning of connectors, ...) would
17078          * experience fancy races otherwise.
17079          */
17080         intel_irq_uninstall(dev_priv);
17081
17082         /*
17083          * Due to the hpd irq storm handling the hotplug work can re-arm the
17084          * poll handlers. Hence disable polling after hpd handling is shut down.
17085          */
17086         drm_kms_helper_poll_fini(dev);
17087
17088         intel_unregister_dsm_handler();
17089
17090         intel_fbc_global_disable(dev_priv);
17091
17092         /* flush any delayed tasks or pending work */
17093         flush_scheduled_work();
17094
17095         drm_mode_config_cleanup(dev);
17096
17097         intel_cleanup_overlay(dev_priv);
17098
17099         intel_cleanup_gt_powersave(dev_priv);
17100
17101         intel_teardown_gmbus(dev);
17102 }
17103
17104 void intel_connector_attach_encoder(struct intel_connector *connector,
17105                                     struct intel_encoder *encoder)
17106 {
17107         connector->encoder = encoder;
17108         drm_mode_connector_attach_encoder(&connector->base,
17109                                           &encoder->base);
17110 }
17111
17112 /*
17113  * set vga decode state - true == enable VGA decode
17114  */
17115 int intel_modeset_vga_set_state(struct drm_device *dev, bool state)
17116 {
17117         struct drm_i915_private *dev_priv = to_i915(dev);
17118         unsigned reg = INTEL_INFO(dev)->gen >= 6 ? SNB_GMCH_CTRL : INTEL_GMCH_CTRL;
17119         u16 gmch_ctrl;
17120
17121         if (pci_read_config_word(dev_priv->bridge_dev, reg, &gmch_ctrl)) {
17122                 DRM_ERROR("failed to read control word\n");
17123                 return -EIO;
17124         }
17125
17126         if (!!(gmch_ctrl & INTEL_GMCH_VGA_DISABLE) == !state)
17127                 return 0;
17128
17129         if (state)
17130                 gmch_ctrl &= ~INTEL_GMCH_VGA_DISABLE;
17131         else
17132                 gmch_ctrl |= INTEL_GMCH_VGA_DISABLE;
17133
17134         if (pci_write_config_word(dev_priv->bridge_dev, reg, gmch_ctrl)) {
17135                 DRM_ERROR("failed to write control word\n");
17136                 return -EIO;
17137         }
17138
17139         return 0;
17140 }
17141
17142 struct intel_display_error_state {
17143
17144         u32 power_well_driver;
17145
17146         int num_transcoders;
17147
17148         struct intel_cursor_error_state {
17149                 u32 control;
17150                 u32 position;
17151                 u32 base;
17152                 u32 size;
17153         } cursor[I915_MAX_PIPES];
17154
17155         struct intel_pipe_error_state {
17156                 bool power_domain_on;
17157                 u32 source;
17158                 u32 stat;
17159         } pipe[I915_MAX_PIPES];
17160
17161         struct intel_plane_error_state {
17162                 u32 control;
17163                 u32 stride;
17164                 u32 size;
17165                 u32 pos;
17166                 u32 addr;
17167                 u32 surface;
17168                 u32 tile_offset;
17169         } plane[I915_MAX_PIPES];
17170
17171         struct intel_transcoder_error_state {
17172                 bool power_domain_on;
17173                 enum transcoder cpu_transcoder;
17174
17175                 u32 conf;
17176
17177                 u32 htotal;
17178                 u32 hblank;
17179                 u32 hsync;
17180                 u32 vtotal;
17181                 u32 vblank;
17182                 u32 vsync;
17183         } transcoder[4];
17184 };
17185
17186 struct intel_display_error_state *
17187 intel_display_capture_error_state(struct drm_i915_private *dev_priv)
17188 {
17189         struct intel_display_error_state *error;
17190         int transcoders[] = {
17191                 TRANSCODER_A,
17192                 TRANSCODER_B,
17193                 TRANSCODER_C,
17194                 TRANSCODER_EDP,
17195         };
17196         int i;
17197
17198         if (INTEL_INFO(dev_priv)->num_pipes == 0)
17199                 return NULL;
17200
17201         error = kzalloc(sizeof(*error), GFP_ATOMIC);
17202         if (error == NULL)
17203                 return NULL;
17204
17205         if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv))
17206                 error->power_well_driver = I915_READ(HSW_PWR_WELL_DRIVER);
17207
17208         for_each_pipe(dev_priv, i) {
17209                 error->pipe[i].power_domain_on =
17210                         __intel_display_power_is_enabled(dev_priv,
17211                                                          POWER_DOMAIN_PIPE(i));
17212                 if (!error->pipe[i].power_domain_on)
17213                         continue;
17214
17215                 error->cursor[i].control = I915_READ(CURCNTR(i));
17216                 error->cursor[i].position = I915_READ(CURPOS(i));
17217                 error->cursor[i].base = I915_READ(CURBASE(i));
17218
17219                 error->plane[i].control = I915_READ(DSPCNTR(i));
17220                 error->plane[i].stride = I915_READ(DSPSTRIDE(i));
17221                 if (INTEL_GEN(dev_priv) <= 3) {
17222                         error->plane[i].size = I915_READ(DSPSIZE(i));
17223                         error->plane[i].pos = I915_READ(DSPPOS(i));
17224                 }
17225                 if (INTEL_GEN(dev_priv) <= 7 && !IS_HASWELL(dev_priv))
17226                         error->plane[i].addr = I915_READ(DSPADDR(i));
17227                 if (INTEL_GEN(dev_priv) >= 4) {
17228                         error->plane[i].surface = I915_READ(DSPSURF(i));
17229                         error->plane[i].tile_offset = I915_READ(DSPTILEOFF(i));
17230                 }
17231
17232                 error->pipe[i].source = I915_READ(PIPESRC(i));
17233
17234                 if (HAS_GMCH_DISPLAY(dev_priv))
17235                         error->pipe[i].stat = I915_READ(PIPESTAT(i));
17236         }
17237
17238         /* Note: this does not include DSI transcoders. */
17239         error->num_transcoders = INTEL_INFO(dev_priv)->num_pipes;
17240         if (HAS_DDI(dev_priv))
17241                 error->num_transcoders++; /* Account for eDP. */
17242
17243         for (i = 0; i < error->num_transcoders; i++) {
17244                 enum transcoder cpu_transcoder = transcoders[i];
17245
17246                 error->transcoder[i].power_domain_on =
17247                         __intel_display_power_is_enabled(dev_priv,
17248                                 POWER_DOMAIN_TRANSCODER(cpu_transcoder));
17249                 if (!error->transcoder[i].power_domain_on)
17250                         continue;
17251
17252                 error->transcoder[i].cpu_transcoder = cpu_transcoder;
17253
17254                 error->transcoder[i].conf = I915_READ(PIPECONF(cpu_transcoder));
17255                 error->transcoder[i].htotal = I915_READ(HTOTAL(cpu_transcoder));
17256                 error->transcoder[i].hblank = I915_READ(HBLANK(cpu_transcoder));
17257                 error->transcoder[i].hsync = I915_READ(HSYNC(cpu_transcoder));
17258                 error->transcoder[i].vtotal = I915_READ(VTOTAL(cpu_transcoder));
17259                 error->transcoder[i].vblank = I915_READ(VBLANK(cpu_transcoder));
17260                 error->transcoder[i].vsync = I915_READ(VSYNC(cpu_transcoder));
17261         }
17262
17263         return error;
17264 }
17265
17266 #define err_printf(e, ...) i915_error_printf(e, __VA_ARGS__)
17267
17268 void
17269 intel_display_print_error_state(struct drm_i915_error_state_buf *m,
17270                                 struct drm_device *dev,
17271                                 struct intel_display_error_state *error)
17272 {
17273         struct drm_i915_private *dev_priv = to_i915(dev);
17274         int i;
17275
17276         if (!error)
17277                 return;
17278
17279         err_printf(m, "Num Pipes: %d\n", INTEL_INFO(dev)->num_pipes);
17280         if (IS_HASWELL(dev) || IS_BROADWELL(dev))
17281                 err_printf(m, "PWR_WELL_CTL2: %08x\n",
17282                            error->power_well_driver);
17283         for_each_pipe(dev_priv, i) {
17284                 err_printf(m, "Pipe [%d]:\n", i);
17285                 err_printf(m, "  Power: %s\n",
17286                            onoff(error->pipe[i].power_domain_on));
17287                 err_printf(m, "  SRC: %08x\n", error->pipe[i].source);
17288                 err_printf(m, "  STAT: %08x\n", error->pipe[i].stat);
17289
17290                 err_printf(m, "Plane [%d]:\n", i);
17291                 err_printf(m, "  CNTR: %08x\n", error->plane[i].control);
17292                 err_printf(m, "  STRIDE: %08x\n", error->plane[i].stride);
17293                 if (INTEL_INFO(dev)->gen <= 3) {
17294                         err_printf(m, "  SIZE: %08x\n", error->plane[i].size);
17295                         err_printf(m, "  POS: %08x\n", error->plane[i].pos);
17296                 }
17297                 if (INTEL_INFO(dev)->gen <= 7 && !IS_HASWELL(dev))
17298                         err_printf(m, "  ADDR: %08x\n", error->plane[i].addr);
17299                 if (INTEL_INFO(dev)->gen >= 4) {
17300                         err_printf(m, "  SURF: %08x\n", error->plane[i].surface);
17301                         err_printf(m, "  TILEOFF: %08x\n", error->plane[i].tile_offset);
17302                 }
17303
17304                 err_printf(m, "Cursor [%d]:\n", i);
17305                 err_printf(m, "  CNTR: %08x\n", error->cursor[i].control);
17306                 err_printf(m, "  POS: %08x\n", error->cursor[i].position);
17307                 err_printf(m, "  BASE: %08x\n", error->cursor[i].base);
17308         }
17309
17310         for (i = 0; i < error->num_transcoders; i++) {
17311                 err_printf(m, "CPU transcoder: %s\n",
17312                            transcoder_name(error->transcoder[i].cpu_transcoder));
17313                 err_printf(m, "  Power: %s\n",
17314                            onoff(error->transcoder[i].power_domain_on));
17315                 err_printf(m, "  CONF: %08x\n", error->transcoder[i].conf);
17316                 err_printf(m, "  HTOTAL: %08x\n", error->transcoder[i].htotal);
17317                 err_printf(m, "  HBLANK: %08x\n", error->transcoder[i].hblank);
17318                 err_printf(m, "  HSYNC: %08x\n", error->transcoder[i].hsync);
17319                 err_printf(m, "  VTOTAL: %08x\n", error->transcoder[i].vtotal);
17320                 err_printf(m, "  VBLANK: %08x\n", error->transcoder[i].vblank);
17321                 err_printf(m, "  VSYNC: %08x\n", error->transcoder[i].vsync);
17322         }
17323 }