Merge tag 'drm-intel-next-2016-08-08' of git://anongit.freedesktop.org/drm-intel...
[cascardo/linux.git] / drivers / gpu / drm / i915 / intel_display.c
1 /*
2  * Copyright © 2006-2007 Intel Corporation
3  *
4  * Permission is hereby granted, free of charge, to any person obtaining a
5  * copy of this software and associated documentation files (the "Software"),
6  * to deal in the Software without restriction, including without limitation
7  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
8  * and/or sell copies of the Software, and to permit persons to whom the
9  * Software is furnished to do so, subject to the following conditions:
10  *
11  * The above copyright notice and this permission notice (including the next
12  * paragraph) shall be included in all copies or substantial portions of the
13  * Software.
14  *
15  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
18  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
21  * DEALINGS IN THE SOFTWARE.
22  *
23  * Authors:
24  *      Eric Anholt <eric@anholt.net>
25  */
26
27 #include <linux/dmi.h>
28 #include <linux/module.h>
29 #include <linux/input.h>
30 #include <linux/i2c.h>
31 #include <linux/kernel.h>
32 #include <linux/slab.h>
33 #include <linux/vgaarb.h>
34 #include <drm/drm_edid.h>
35 #include <drm/drmP.h>
36 #include "intel_drv.h"
37 #include "intel_frontbuffer.h"
38 #include <drm/i915_drm.h>
39 #include "i915_drv.h"
40 #include "i915_gem_dmabuf.h"
41 #include "intel_dsi.h"
42 #include "i915_trace.h"
43 #include <drm/drm_atomic.h>
44 #include <drm/drm_atomic_helper.h>
45 #include <drm/drm_dp_helper.h>
46 #include <drm/drm_crtc_helper.h>
47 #include <drm/drm_plane_helper.h>
48 #include <drm/drm_rect.h>
49 #include <linux/dma_remapping.h>
50 #include <linux/reservation.h>
51
52 static bool is_mmio_work(struct intel_flip_work *work)
53 {
54         return work->mmio_work.func;
55 }
56
57 /* Primary plane formats for gen <= 3 */
58 static const uint32_t i8xx_primary_formats[] = {
59         DRM_FORMAT_C8,
60         DRM_FORMAT_RGB565,
61         DRM_FORMAT_XRGB1555,
62         DRM_FORMAT_XRGB8888,
63 };
64
65 /* Primary plane formats for gen >= 4 */
66 static const uint32_t i965_primary_formats[] = {
67         DRM_FORMAT_C8,
68         DRM_FORMAT_RGB565,
69         DRM_FORMAT_XRGB8888,
70         DRM_FORMAT_XBGR8888,
71         DRM_FORMAT_XRGB2101010,
72         DRM_FORMAT_XBGR2101010,
73 };
74
75 static const uint32_t skl_primary_formats[] = {
76         DRM_FORMAT_C8,
77         DRM_FORMAT_RGB565,
78         DRM_FORMAT_XRGB8888,
79         DRM_FORMAT_XBGR8888,
80         DRM_FORMAT_ARGB8888,
81         DRM_FORMAT_ABGR8888,
82         DRM_FORMAT_XRGB2101010,
83         DRM_FORMAT_XBGR2101010,
84         DRM_FORMAT_YUYV,
85         DRM_FORMAT_YVYU,
86         DRM_FORMAT_UYVY,
87         DRM_FORMAT_VYUY,
88 };
89
90 /* Cursor formats */
91 static const uint32_t intel_cursor_formats[] = {
92         DRM_FORMAT_ARGB8888,
93 };
94
95 static void i9xx_crtc_clock_get(struct intel_crtc *crtc,
96                                 struct intel_crtc_state *pipe_config);
97 static void ironlake_pch_clock_get(struct intel_crtc *crtc,
98                                    struct intel_crtc_state *pipe_config);
99
100 static int intel_framebuffer_init(struct drm_device *dev,
101                                   struct intel_framebuffer *ifb,
102                                   struct drm_mode_fb_cmd2 *mode_cmd,
103                                   struct drm_i915_gem_object *obj);
104 static void i9xx_set_pipeconf(struct intel_crtc *intel_crtc);
105 static void intel_set_pipe_timings(struct intel_crtc *intel_crtc);
106 static void intel_set_pipe_src_size(struct intel_crtc *intel_crtc);
107 static void intel_cpu_transcoder_set_m_n(struct intel_crtc *crtc,
108                                          struct intel_link_m_n *m_n,
109                                          struct intel_link_m_n *m2_n2);
110 static void ironlake_set_pipeconf(struct drm_crtc *crtc);
111 static void haswell_set_pipeconf(struct drm_crtc *crtc);
112 static void haswell_set_pipemisc(struct drm_crtc *crtc);
113 static void vlv_prepare_pll(struct intel_crtc *crtc,
114                             const struct intel_crtc_state *pipe_config);
115 static void chv_prepare_pll(struct intel_crtc *crtc,
116                             const struct intel_crtc_state *pipe_config);
117 static void intel_begin_crtc_commit(struct drm_crtc *, struct drm_crtc_state *);
118 static void intel_finish_crtc_commit(struct drm_crtc *, struct drm_crtc_state *);
119 static void skl_init_scalers(struct drm_device *dev, struct intel_crtc *intel_crtc,
120         struct intel_crtc_state *crtc_state);
121 static void skylake_pfit_enable(struct intel_crtc *crtc);
122 static void ironlake_pfit_disable(struct intel_crtc *crtc, bool force);
123 static void ironlake_pfit_enable(struct intel_crtc *crtc);
124 static void intel_modeset_setup_hw_state(struct drm_device *dev);
125 static void intel_pre_disable_primary_noatomic(struct drm_crtc *crtc);
126 static int ilk_max_pixel_rate(struct drm_atomic_state *state);
127 static int bxt_calc_cdclk(int max_pixclk);
128
129 struct intel_limit {
130         struct {
131                 int min, max;
132         } dot, vco, n, m, m1, m2, p, p1;
133
134         struct {
135                 int dot_limit;
136                 int p2_slow, p2_fast;
137         } p2;
138 };
139
140 /* returns HPLL frequency in kHz */
141 static int valleyview_get_vco(struct drm_i915_private *dev_priv)
142 {
143         int hpll_freq, vco_freq[] = { 800, 1600, 2000, 2400 };
144
145         /* Obtain SKU information */
146         mutex_lock(&dev_priv->sb_lock);
147         hpll_freq = vlv_cck_read(dev_priv, CCK_FUSE_REG) &
148                 CCK_FUSE_HPLL_FREQ_MASK;
149         mutex_unlock(&dev_priv->sb_lock);
150
151         return vco_freq[hpll_freq] * 1000;
152 }
153
154 int vlv_get_cck_clock(struct drm_i915_private *dev_priv,
155                       const char *name, u32 reg, int ref_freq)
156 {
157         u32 val;
158         int divider;
159
160         mutex_lock(&dev_priv->sb_lock);
161         val = vlv_cck_read(dev_priv, reg);
162         mutex_unlock(&dev_priv->sb_lock);
163
164         divider = val & CCK_FREQUENCY_VALUES;
165
166         WARN((val & CCK_FREQUENCY_STATUS) !=
167              (divider << CCK_FREQUENCY_STATUS_SHIFT),
168              "%s change in progress\n", name);
169
170         return DIV_ROUND_CLOSEST(ref_freq << 1, divider + 1);
171 }
172
173 static int vlv_get_cck_clock_hpll(struct drm_i915_private *dev_priv,
174                                   const char *name, u32 reg)
175 {
176         if (dev_priv->hpll_freq == 0)
177                 dev_priv->hpll_freq = valleyview_get_vco(dev_priv);
178
179         return vlv_get_cck_clock(dev_priv, name, reg,
180                                  dev_priv->hpll_freq);
181 }
182
183 static int
184 intel_pch_rawclk(struct drm_i915_private *dev_priv)
185 {
186         return (I915_READ(PCH_RAWCLK_FREQ) & RAWCLK_FREQ_MASK) * 1000;
187 }
188
189 static int
190 intel_vlv_hrawclk(struct drm_i915_private *dev_priv)
191 {
192         /* RAWCLK_FREQ_VLV register updated from power well code */
193         return vlv_get_cck_clock_hpll(dev_priv, "hrawclk",
194                                       CCK_DISPLAY_REF_CLOCK_CONTROL);
195 }
196
197 static int
198 intel_g4x_hrawclk(struct drm_i915_private *dev_priv)
199 {
200         uint32_t clkcfg;
201
202         /* hrawclock is 1/4 the FSB frequency */
203         clkcfg = I915_READ(CLKCFG);
204         switch (clkcfg & CLKCFG_FSB_MASK) {
205         case CLKCFG_FSB_400:
206                 return 100000;
207         case CLKCFG_FSB_533:
208                 return 133333;
209         case CLKCFG_FSB_667:
210                 return 166667;
211         case CLKCFG_FSB_800:
212                 return 200000;
213         case CLKCFG_FSB_1067:
214                 return 266667;
215         case CLKCFG_FSB_1333:
216                 return 333333;
217         /* these two are just a guess; one of them might be right */
218         case CLKCFG_FSB_1600:
219         case CLKCFG_FSB_1600_ALT:
220                 return 400000;
221         default:
222                 return 133333;
223         }
224 }
225
226 void intel_update_rawclk(struct drm_i915_private *dev_priv)
227 {
228         if (HAS_PCH_SPLIT(dev_priv))
229                 dev_priv->rawclk_freq = intel_pch_rawclk(dev_priv);
230         else if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
231                 dev_priv->rawclk_freq = intel_vlv_hrawclk(dev_priv);
232         else if (IS_G4X(dev_priv) || IS_PINEVIEW(dev_priv))
233                 dev_priv->rawclk_freq = intel_g4x_hrawclk(dev_priv);
234         else
235                 return; /* no rawclk on other platforms, or no need to know it */
236
237         DRM_DEBUG_DRIVER("rawclk rate: %d kHz\n", dev_priv->rawclk_freq);
238 }
239
240 static void intel_update_czclk(struct drm_i915_private *dev_priv)
241 {
242         if (!(IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv)))
243                 return;
244
245         dev_priv->czclk_freq = vlv_get_cck_clock_hpll(dev_priv, "czclk",
246                                                       CCK_CZ_CLOCK_CONTROL);
247
248         DRM_DEBUG_DRIVER("CZ clock rate: %d kHz\n", dev_priv->czclk_freq);
249 }
250
251 static inline u32 /* units of 100MHz */
252 intel_fdi_link_freq(struct drm_i915_private *dev_priv,
253                     const struct intel_crtc_state *pipe_config)
254 {
255         if (HAS_DDI(dev_priv))
256                 return pipe_config->port_clock; /* SPLL */
257         else if (IS_GEN5(dev_priv))
258                 return ((I915_READ(FDI_PLL_BIOS_0) & FDI_PLL_FB_CLOCK_MASK) + 2) * 10000;
259         else
260                 return 270000;
261 }
262
263 static const struct intel_limit intel_limits_i8xx_dac = {
264         .dot = { .min = 25000, .max = 350000 },
265         .vco = { .min = 908000, .max = 1512000 },
266         .n = { .min = 2, .max = 16 },
267         .m = { .min = 96, .max = 140 },
268         .m1 = { .min = 18, .max = 26 },
269         .m2 = { .min = 6, .max = 16 },
270         .p = { .min = 4, .max = 128 },
271         .p1 = { .min = 2, .max = 33 },
272         .p2 = { .dot_limit = 165000,
273                 .p2_slow = 4, .p2_fast = 2 },
274 };
275
276 static const struct intel_limit intel_limits_i8xx_dvo = {
277         .dot = { .min = 25000, .max = 350000 },
278         .vco = { .min = 908000, .max = 1512000 },
279         .n = { .min = 2, .max = 16 },
280         .m = { .min = 96, .max = 140 },
281         .m1 = { .min = 18, .max = 26 },
282         .m2 = { .min = 6, .max = 16 },
283         .p = { .min = 4, .max = 128 },
284         .p1 = { .min = 2, .max = 33 },
285         .p2 = { .dot_limit = 165000,
286                 .p2_slow = 4, .p2_fast = 4 },
287 };
288
289 static const struct intel_limit intel_limits_i8xx_lvds = {
290         .dot = { .min = 25000, .max = 350000 },
291         .vco = { .min = 908000, .max = 1512000 },
292         .n = { .min = 2, .max = 16 },
293         .m = { .min = 96, .max = 140 },
294         .m1 = { .min = 18, .max = 26 },
295         .m2 = { .min = 6, .max = 16 },
296         .p = { .min = 4, .max = 128 },
297         .p1 = { .min = 1, .max = 6 },
298         .p2 = { .dot_limit = 165000,
299                 .p2_slow = 14, .p2_fast = 7 },
300 };
301
302 static const struct intel_limit intel_limits_i9xx_sdvo = {
303         .dot = { .min = 20000, .max = 400000 },
304         .vco = { .min = 1400000, .max = 2800000 },
305         .n = { .min = 1, .max = 6 },
306         .m = { .min = 70, .max = 120 },
307         .m1 = { .min = 8, .max = 18 },
308         .m2 = { .min = 3, .max = 7 },
309         .p = { .min = 5, .max = 80 },
310         .p1 = { .min = 1, .max = 8 },
311         .p2 = { .dot_limit = 200000,
312                 .p2_slow = 10, .p2_fast = 5 },
313 };
314
315 static const struct intel_limit intel_limits_i9xx_lvds = {
316         .dot = { .min = 20000, .max = 400000 },
317         .vco = { .min = 1400000, .max = 2800000 },
318         .n = { .min = 1, .max = 6 },
319         .m = { .min = 70, .max = 120 },
320         .m1 = { .min = 8, .max = 18 },
321         .m2 = { .min = 3, .max = 7 },
322         .p = { .min = 7, .max = 98 },
323         .p1 = { .min = 1, .max = 8 },
324         .p2 = { .dot_limit = 112000,
325                 .p2_slow = 14, .p2_fast = 7 },
326 };
327
328
329 static const struct intel_limit intel_limits_g4x_sdvo = {
330         .dot = { .min = 25000, .max = 270000 },
331         .vco = { .min = 1750000, .max = 3500000},
332         .n = { .min = 1, .max = 4 },
333         .m = { .min = 104, .max = 138 },
334         .m1 = { .min = 17, .max = 23 },
335         .m2 = { .min = 5, .max = 11 },
336         .p = { .min = 10, .max = 30 },
337         .p1 = { .min = 1, .max = 3},
338         .p2 = { .dot_limit = 270000,
339                 .p2_slow = 10,
340                 .p2_fast = 10
341         },
342 };
343
344 static const struct intel_limit intel_limits_g4x_hdmi = {
345         .dot = { .min = 22000, .max = 400000 },
346         .vco = { .min = 1750000, .max = 3500000},
347         .n = { .min = 1, .max = 4 },
348         .m = { .min = 104, .max = 138 },
349         .m1 = { .min = 16, .max = 23 },
350         .m2 = { .min = 5, .max = 11 },
351         .p = { .min = 5, .max = 80 },
352         .p1 = { .min = 1, .max = 8},
353         .p2 = { .dot_limit = 165000,
354                 .p2_slow = 10, .p2_fast = 5 },
355 };
356
357 static const struct intel_limit intel_limits_g4x_single_channel_lvds = {
358         .dot = { .min = 20000, .max = 115000 },
359         .vco = { .min = 1750000, .max = 3500000 },
360         .n = { .min = 1, .max = 3 },
361         .m = { .min = 104, .max = 138 },
362         .m1 = { .min = 17, .max = 23 },
363         .m2 = { .min = 5, .max = 11 },
364         .p = { .min = 28, .max = 112 },
365         .p1 = { .min = 2, .max = 8 },
366         .p2 = { .dot_limit = 0,
367                 .p2_slow = 14, .p2_fast = 14
368         },
369 };
370
371 static const struct intel_limit intel_limits_g4x_dual_channel_lvds = {
372         .dot = { .min = 80000, .max = 224000 },
373         .vco = { .min = 1750000, .max = 3500000 },
374         .n = { .min = 1, .max = 3 },
375         .m = { .min = 104, .max = 138 },
376         .m1 = { .min = 17, .max = 23 },
377         .m2 = { .min = 5, .max = 11 },
378         .p = { .min = 14, .max = 42 },
379         .p1 = { .min = 2, .max = 6 },
380         .p2 = { .dot_limit = 0,
381                 .p2_slow = 7, .p2_fast = 7
382         },
383 };
384
385 static const struct intel_limit intel_limits_pineview_sdvo = {
386         .dot = { .min = 20000, .max = 400000},
387         .vco = { .min = 1700000, .max = 3500000 },
388         /* Pineview's Ncounter is a ring counter */
389         .n = { .min = 3, .max = 6 },
390         .m = { .min = 2, .max = 256 },
391         /* Pineview only has one combined m divider, which we treat as m2. */
392         .m1 = { .min = 0, .max = 0 },
393         .m2 = { .min = 0, .max = 254 },
394         .p = { .min = 5, .max = 80 },
395         .p1 = { .min = 1, .max = 8 },
396         .p2 = { .dot_limit = 200000,
397                 .p2_slow = 10, .p2_fast = 5 },
398 };
399
400 static const struct intel_limit intel_limits_pineview_lvds = {
401         .dot = { .min = 20000, .max = 400000 },
402         .vco = { .min = 1700000, .max = 3500000 },
403         .n = { .min = 3, .max = 6 },
404         .m = { .min = 2, .max = 256 },
405         .m1 = { .min = 0, .max = 0 },
406         .m2 = { .min = 0, .max = 254 },
407         .p = { .min = 7, .max = 112 },
408         .p1 = { .min = 1, .max = 8 },
409         .p2 = { .dot_limit = 112000,
410                 .p2_slow = 14, .p2_fast = 14 },
411 };
412
413 /* Ironlake / Sandybridge
414  *
415  * We calculate clock using (register_value + 2) for N/M1/M2, so here
416  * the range value for them is (actual_value - 2).
417  */
418 static const struct intel_limit intel_limits_ironlake_dac = {
419         .dot = { .min = 25000, .max = 350000 },
420         .vco = { .min = 1760000, .max = 3510000 },
421         .n = { .min = 1, .max = 5 },
422         .m = { .min = 79, .max = 127 },
423         .m1 = { .min = 12, .max = 22 },
424         .m2 = { .min = 5, .max = 9 },
425         .p = { .min = 5, .max = 80 },
426         .p1 = { .min = 1, .max = 8 },
427         .p2 = { .dot_limit = 225000,
428                 .p2_slow = 10, .p2_fast = 5 },
429 };
430
431 static const struct intel_limit intel_limits_ironlake_single_lvds = {
432         .dot = { .min = 25000, .max = 350000 },
433         .vco = { .min = 1760000, .max = 3510000 },
434         .n = { .min = 1, .max = 3 },
435         .m = { .min = 79, .max = 118 },
436         .m1 = { .min = 12, .max = 22 },
437         .m2 = { .min = 5, .max = 9 },
438         .p = { .min = 28, .max = 112 },
439         .p1 = { .min = 2, .max = 8 },
440         .p2 = { .dot_limit = 225000,
441                 .p2_slow = 14, .p2_fast = 14 },
442 };
443
444 static const struct intel_limit intel_limits_ironlake_dual_lvds = {
445         .dot = { .min = 25000, .max = 350000 },
446         .vco = { .min = 1760000, .max = 3510000 },
447         .n = { .min = 1, .max = 3 },
448         .m = { .min = 79, .max = 127 },
449         .m1 = { .min = 12, .max = 22 },
450         .m2 = { .min = 5, .max = 9 },
451         .p = { .min = 14, .max = 56 },
452         .p1 = { .min = 2, .max = 8 },
453         .p2 = { .dot_limit = 225000,
454                 .p2_slow = 7, .p2_fast = 7 },
455 };
456
457 /* LVDS 100mhz refclk limits. */
458 static const struct intel_limit intel_limits_ironlake_single_lvds_100m = {
459         .dot = { .min = 25000, .max = 350000 },
460         .vco = { .min = 1760000, .max = 3510000 },
461         .n = { .min = 1, .max = 2 },
462         .m = { .min = 79, .max = 126 },
463         .m1 = { .min = 12, .max = 22 },
464         .m2 = { .min = 5, .max = 9 },
465         .p = { .min = 28, .max = 112 },
466         .p1 = { .min = 2, .max = 8 },
467         .p2 = { .dot_limit = 225000,
468                 .p2_slow = 14, .p2_fast = 14 },
469 };
470
471 static const struct intel_limit intel_limits_ironlake_dual_lvds_100m = {
472         .dot = { .min = 25000, .max = 350000 },
473         .vco = { .min = 1760000, .max = 3510000 },
474         .n = { .min = 1, .max = 3 },
475         .m = { .min = 79, .max = 126 },
476         .m1 = { .min = 12, .max = 22 },
477         .m2 = { .min = 5, .max = 9 },
478         .p = { .min = 14, .max = 42 },
479         .p1 = { .min = 2, .max = 6 },
480         .p2 = { .dot_limit = 225000,
481                 .p2_slow = 7, .p2_fast = 7 },
482 };
483
484 static const struct intel_limit intel_limits_vlv = {
485          /*
486           * These are the data rate limits (measured in fast clocks)
487           * since those are the strictest limits we have. The fast
488           * clock and actual rate limits are more relaxed, so checking
489           * them would make no difference.
490           */
491         .dot = { .min = 25000 * 5, .max = 270000 * 5 },
492         .vco = { .min = 4000000, .max = 6000000 },
493         .n = { .min = 1, .max = 7 },
494         .m1 = { .min = 2, .max = 3 },
495         .m2 = { .min = 11, .max = 156 },
496         .p1 = { .min = 2, .max = 3 },
497         .p2 = { .p2_slow = 2, .p2_fast = 20 }, /* slow=min, fast=max */
498 };
499
500 static const struct intel_limit intel_limits_chv = {
501         /*
502          * These are the data rate limits (measured in fast clocks)
503          * since those are the strictest limits we have.  The fast
504          * clock and actual rate limits are more relaxed, so checking
505          * them would make no difference.
506          */
507         .dot = { .min = 25000 * 5, .max = 540000 * 5},
508         .vco = { .min = 4800000, .max = 6480000 },
509         .n = { .min = 1, .max = 1 },
510         .m1 = { .min = 2, .max = 2 },
511         .m2 = { .min = 24 << 22, .max = 175 << 22 },
512         .p1 = { .min = 2, .max = 4 },
513         .p2 = { .p2_slow = 1, .p2_fast = 14 },
514 };
515
516 static const struct intel_limit intel_limits_bxt = {
517         /* FIXME: find real dot limits */
518         .dot = { .min = 0, .max = INT_MAX },
519         .vco = { .min = 4800000, .max = 6700000 },
520         .n = { .min = 1, .max = 1 },
521         .m1 = { .min = 2, .max = 2 },
522         /* FIXME: find real m2 limits */
523         .m2 = { .min = 2 << 22, .max = 255 << 22 },
524         .p1 = { .min = 2, .max = 4 },
525         .p2 = { .p2_slow = 1, .p2_fast = 20 },
526 };
527
528 static bool
529 needs_modeset(struct drm_crtc_state *state)
530 {
531         return drm_atomic_crtc_needs_modeset(state);
532 }
533
534 /*
535  * Platform specific helpers to calculate the port PLL loopback- (clock.m),
536  * and post-divider (clock.p) values, pre- (clock.vco) and post-divided fast
537  * (clock.dot) clock rates. This fast dot clock is fed to the port's IO logic.
538  * The helpers' return value is the rate of the clock that is fed to the
539  * display engine's pipe which can be the above fast dot clock rate or a
540  * divided-down version of it.
541  */
542 /* m1 is reserved as 0 in Pineview, n is a ring counter */
543 static int pnv_calc_dpll_params(int refclk, struct dpll *clock)
544 {
545         clock->m = clock->m2 + 2;
546         clock->p = clock->p1 * clock->p2;
547         if (WARN_ON(clock->n == 0 || clock->p == 0))
548                 return 0;
549         clock->vco = DIV_ROUND_CLOSEST(refclk * clock->m, clock->n);
550         clock->dot = DIV_ROUND_CLOSEST(clock->vco, clock->p);
551
552         return clock->dot;
553 }
554
555 static uint32_t i9xx_dpll_compute_m(struct dpll *dpll)
556 {
557         return 5 * (dpll->m1 + 2) + (dpll->m2 + 2);
558 }
559
560 static int i9xx_calc_dpll_params(int refclk, struct dpll *clock)
561 {
562         clock->m = i9xx_dpll_compute_m(clock);
563         clock->p = clock->p1 * clock->p2;
564         if (WARN_ON(clock->n + 2 == 0 || clock->p == 0))
565                 return 0;
566         clock->vco = DIV_ROUND_CLOSEST(refclk * clock->m, clock->n + 2);
567         clock->dot = DIV_ROUND_CLOSEST(clock->vco, clock->p);
568
569         return clock->dot;
570 }
571
572 static int vlv_calc_dpll_params(int refclk, struct dpll *clock)
573 {
574         clock->m = clock->m1 * clock->m2;
575         clock->p = clock->p1 * clock->p2;
576         if (WARN_ON(clock->n == 0 || clock->p == 0))
577                 return 0;
578         clock->vco = DIV_ROUND_CLOSEST(refclk * clock->m, clock->n);
579         clock->dot = DIV_ROUND_CLOSEST(clock->vco, clock->p);
580
581         return clock->dot / 5;
582 }
583
584 int chv_calc_dpll_params(int refclk, struct dpll *clock)
585 {
586         clock->m = clock->m1 * clock->m2;
587         clock->p = clock->p1 * clock->p2;
588         if (WARN_ON(clock->n == 0 || clock->p == 0))
589                 return 0;
590         clock->vco = DIV_ROUND_CLOSEST_ULL((uint64_t)refclk * clock->m,
591                         clock->n << 22);
592         clock->dot = DIV_ROUND_CLOSEST(clock->vco, clock->p);
593
594         return clock->dot / 5;
595 }
596
597 #define INTELPllInvalid(s)   do { /* DRM_DEBUG(s); */ return false; } while (0)
598 /**
599  * Returns whether the given set of divisors are valid for a given refclk with
600  * the given connectors.
601  */
602
603 static bool intel_PLL_is_valid(struct drm_device *dev,
604                                const struct intel_limit *limit,
605                                const struct dpll *clock)
606 {
607         if (clock->n   < limit->n.min   || limit->n.max   < clock->n)
608                 INTELPllInvalid("n out of range\n");
609         if (clock->p1  < limit->p1.min  || limit->p1.max  < clock->p1)
610                 INTELPllInvalid("p1 out of range\n");
611         if (clock->m2  < limit->m2.min  || limit->m2.max  < clock->m2)
612                 INTELPllInvalid("m2 out of range\n");
613         if (clock->m1  < limit->m1.min  || limit->m1.max  < clock->m1)
614                 INTELPllInvalid("m1 out of range\n");
615
616         if (!IS_PINEVIEW(dev) && !IS_VALLEYVIEW(dev) &&
617             !IS_CHERRYVIEW(dev) && !IS_BROXTON(dev))
618                 if (clock->m1 <= clock->m2)
619                         INTELPllInvalid("m1 <= m2\n");
620
621         if (!IS_VALLEYVIEW(dev) && !IS_CHERRYVIEW(dev) && !IS_BROXTON(dev)) {
622                 if (clock->p < limit->p.min || limit->p.max < clock->p)
623                         INTELPllInvalid("p out of range\n");
624                 if (clock->m < limit->m.min || limit->m.max < clock->m)
625                         INTELPllInvalid("m out of range\n");
626         }
627
628         if (clock->vco < limit->vco.min || limit->vco.max < clock->vco)
629                 INTELPllInvalid("vco out of range\n");
630         /* XXX: We may need to be checking "Dot clock" depending on the multiplier,
631          * connector, etc., rather than just a single range.
632          */
633         if (clock->dot < limit->dot.min || limit->dot.max < clock->dot)
634                 INTELPllInvalid("dot out of range\n");
635
636         return true;
637 }
638
639 static int
640 i9xx_select_p2_div(const struct intel_limit *limit,
641                    const struct intel_crtc_state *crtc_state,
642                    int target)
643 {
644         struct drm_device *dev = crtc_state->base.crtc->dev;
645
646         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
647                 /*
648                  * For LVDS just rely on its current settings for dual-channel.
649                  * We haven't figured out how to reliably set up different
650                  * single/dual channel state, if we even can.
651                  */
652                 if (intel_is_dual_link_lvds(dev))
653                         return limit->p2.p2_fast;
654                 else
655                         return limit->p2.p2_slow;
656         } else {
657                 if (target < limit->p2.dot_limit)
658                         return limit->p2.p2_slow;
659                 else
660                         return limit->p2.p2_fast;
661         }
662 }
663
664 /*
665  * Returns a set of divisors for the desired target clock with the given
666  * refclk, or FALSE.  The returned values represent the clock equation:
667  * reflck * (5 * (m1 + 2) + (m2 + 2)) / (n + 2) / p1 / p2.
668  *
669  * Target and reference clocks are specified in kHz.
670  *
671  * If match_clock is provided, then best_clock P divider must match the P
672  * divider from @match_clock used for LVDS downclocking.
673  */
674 static bool
675 i9xx_find_best_dpll(const struct intel_limit *limit,
676                     struct intel_crtc_state *crtc_state,
677                     int target, int refclk, struct dpll *match_clock,
678                     struct dpll *best_clock)
679 {
680         struct drm_device *dev = crtc_state->base.crtc->dev;
681         struct dpll clock;
682         int err = target;
683
684         memset(best_clock, 0, sizeof(*best_clock));
685
686         clock.p2 = i9xx_select_p2_div(limit, crtc_state, target);
687
688         for (clock.m1 = limit->m1.min; clock.m1 <= limit->m1.max;
689              clock.m1++) {
690                 for (clock.m2 = limit->m2.min;
691                      clock.m2 <= limit->m2.max; clock.m2++) {
692                         if (clock.m2 >= clock.m1)
693                                 break;
694                         for (clock.n = limit->n.min;
695                              clock.n <= limit->n.max; clock.n++) {
696                                 for (clock.p1 = limit->p1.min;
697                                         clock.p1 <= limit->p1.max; clock.p1++) {
698                                         int this_err;
699
700                                         i9xx_calc_dpll_params(refclk, &clock);
701                                         if (!intel_PLL_is_valid(dev, limit,
702                                                                 &clock))
703                                                 continue;
704                                         if (match_clock &&
705                                             clock.p != match_clock->p)
706                                                 continue;
707
708                                         this_err = abs(clock.dot - target);
709                                         if (this_err < err) {
710                                                 *best_clock = clock;
711                                                 err = this_err;
712                                         }
713                                 }
714                         }
715                 }
716         }
717
718         return (err != target);
719 }
720
721 /*
722  * Returns a set of divisors for the desired target clock with the given
723  * refclk, or FALSE.  The returned values represent the clock equation:
724  * reflck * (5 * (m1 + 2) + (m2 + 2)) / (n + 2) / p1 / p2.
725  *
726  * Target and reference clocks are specified in kHz.
727  *
728  * If match_clock is provided, then best_clock P divider must match the P
729  * divider from @match_clock used for LVDS downclocking.
730  */
731 static bool
732 pnv_find_best_dpll(const struct intel_limit *limit,
733                    struct intel_crtc_state *crtc_state,
734                    int target, int refclk, struct dpll *match_clock,
735                    struct dpll *best_clock)
736 {
737         struct drm_device *dev = crtc_state->base.crtc->dev;
738         struct dpll clock;
739         int err = target;
740
741         memset(best_clock, 0, sizeof(*best_clock));
742
743         clock.p2 = i9xx_select_p2_div(limit, crtc_state, target);
744
745         for (clock.m1 = limit->m1.min; clock.m1 <= limit->m1.max;
746              clock.m1++) {
747                 for (clock.m2 = limit->m2.min;
748                      clock.m2 <= limit->m2.max; clock.m2++) {
749                         for (clock.n = limit->n.min;
750                              clock.n <= limit->n.max; clock.n++) {
751                                 for (clock.p1 = limit->p1.min;
752                                         clock.p1 <= limit->p1.max; clock.p1++) {
753                                         int this_err;
754
755                                         pnv_calc_dpll_params(refclk, &clock);
756                                         if (!intel_PLL_is_valid(dev, limit,
757                                                                 &clock))
758                                                 continue;
759                                         if (match_clock &&
760                                             clock.p != match_clock->p)
761                                                 continue;
762
763                                         this_err = abs(clock.dot - target);
764                                         if (this_err < err) {
765                                                 *best_clock = clock;
766                                                 err = this_err;
767                                         }
768                                 }
769                         }
770                 }
771         }
772
773         return (err != target);
774 }
775
776 /*
777  * Returns a set of divisors for the desired target clock with the given
778  * refclk, or FALSE.  The returned values represent the clock equation:
779  * reflck * (5 * (m1 + 2) + (m2 + 2)) / (n + 2) / p1 / p2.
780  *
781  * Target and reference clocks are specified in kHz.
782  *
783  * If match_clock is provided, then best_clock P divider must match the P
784  * divider from @match_clock used for LVDS downclocking.
785  */
786 static bool
787 g4x_find_best_dpll(const struct intel_limit *limit,
788                    struct intel_crtc_state *crtc_state,
789                    int target, int refclk, struct dpll *match_clock,
790                    struct dpll *best_clock)
791 {
792         struct drm_device *dev = crtc_state->base.crtc->dev;
793         struct dpll clock;
794         int max_n;
795         bool found = false;
796         /* approximately equals target * 0.00585 */
797         int err_most = (target >> 8) + (target >> 9);
798
799         memset(best_clock, 0, sizeof(*best_clock));
800
801         clock.p2 = i9xx_select_p2_div(limit, crtc_state, target);
802
803         max_n = limit->n.max;
804         /* based on hardware requirement, prefer smaller n to precision */
805         for (clock.n = limit->n.min; clock.n <= max_n; clock.n++) {
806                 /* based on hardware requirement, prefere larger m1,m2 */
807                 for (clock.m1 = limit->m1.max;
808                      clock.m1 >= limit->m1.min; clock.m1--) {
809                         for (clock.m2 = limit->m2.max;
810                              clock.m2 >= limit->m2.min; clock.m2--) {
811                                 for (clock.p1 = limit->p1.max;
812                                      clock.p1 >= limit->p1.min; clock.p1--) {
813                                         int this_err;
814
815                                         i9xx_calc_dpll_params(refclk, &clock);
816                                         if (!intel_PLL_is_valid(dev, limit,
817                                                                 &clock))
818                                                 continue;
819
820                                         this_err = abs(clock.dot - target);
821                                         if (this_err < err_most) {
822                                                 *best_clock = clock;
823                                                 err_most = this_err;
824                                                 max_n = clock.n;
825                                                 found = true;
826                                         }
827                                 }
828                         }
829                 }
830         }
831         return found;
832 }
833
834 /*
835  * Check if the calculated PLL configuration is more optimal compared to the
836  * best configuration and error found so far. Return the calculated error.
837  */
838 static bool vlv_PLL_is_optimal(struct drm_device *dev, int target_freq,
839                                const struct dpll *calculated_clock,
840                                const struct dpll *best_clock,
841                                unsigned int best_error_ppm,
842                                unsigned int *error_ppm)
843 {
844         /*
845          * For CHV ignore the error and consider only the P value.
846          * Prefer a bigger P value based on HW requirements.
847          */
848         if (IS_CHERRYVIEW(dev)) {
849                 *error_ppm = 0;
850
851                 return calculated_clock->p > best_clock->p;
852         }
853
854         if (WARN_ON_ONCE(!target_freq))
855                 return false;
856
857         *error_ppm = div_u64(1000000ULL *
858                                 abs(target_freq - calculated_clock->dot),
859                              target_freq);
860         /*
861          * Prefer a better P value over a better (smaller) error if the error
862          * is small. Ensure this preference for future configurations too by
863          * setting the error to 0.
864          */
865         if (*error_ppm < 100 && calculated_clock->p > best_clock->p) {
866                 *error_ppm = 0;
867
868                 return true;
869         }
870
871         return *error_ppm + 10 < best_error_ppm;
872 }
873
874 /*
875  * Returns a set of divisors for the desired target clock with the given
876  * refclk, or FALSE.  The returned values represent the clock equation:
877  * reflck * (5 * (m1 + 2) + (m2 + 2)) / (n + 2) / p1 / p2.
878  */
879 static bool
880 vlv_find_best_dpll(const struct intel_limit *limit,
881                    struct intel_crtc_state *crtc_state,
882                    int target, int refclk, struct dpll *match_clock,
883                    struct dpll *best_clock)
884 {
885         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
886         struct drm_device *dev = crtc->base.dev;
887         struct dpll clock;
888         unsigned int bestppm = 1000000;
889         /* min update 19.2 MHz */
890         int max_n = min(limit->n.max, refclk / 19200);
891         bool found = false;
892
893         target *= 5; /* fast clock */
894
895         memset(best_clock, 0, sizeof(*best_clock));
896
897         /* based on hardware requirement, prefer smaller n to precision */
898         for (clock.n = limit->n.min; clock.n <= max_n; clock.n++) {
899                 for (clock.p1 = limit->p1.max; clock.p1 >= limit->p1.min; clock.p1--) {
900                         for (clock.p2 = limit->p2.p2_fast; clock.p2 >= limit->p2.p2_slow;
901                              clock.p2 -= clock.p2 > 10 ? 2 : 1) {
902                                 clock.p = clock.p1 * clock.p2;
903                                 /* based on hardware requirement, prefer bigger m1,m2 values */
904                                 for (clock.m1 = limit->m1.min; clock.m1 <= limit->m1.max; clock.m1++) {
905                                         unsigned int ppm;
906
907                                         clock.m2 = DIV_ROUND_CLOSEST(target * clock.p * clock.n,
908                                                                      refclk * clock.m1);
909
910                                         vlv_calc_dpll_params(refclk, &clock);
911
912                                         if (!intel_PLL_is_valid(dev, limit,
913                                                                 &clock))
914                                                 continue;
915
916                                         if (!vlv_PLL_is_optimal(dev, target,
917                                                                 &clock,
918                                                                 best_clock,
919                                                                 bestppm, &ppm))
920                                                 continue;
921
922                                         *best_clock = clock;
923                                         bestppm = ppm;
924                                         found = true;
925                                 }
926                         }
927                 }
928         }
929
930         return found;
931 }
932
933 /*
934  * Returns a set of divisors for the desired target clock with the given
935  * refclk, or FALSE.  The returned values represent the clock equation:
936  * reflck * (5 * (m1 + 2) + (m2 + 2)) / (n + 2) / p1 / p2.
937  */
938 static bool
939 chv_find_best_dpll(const struct intel_limit *limit,
940                    struct intel_crtc_state *crtc_state,
941                    int target, int refclk, struct dpll *match_clock,
942                    struct dpll *best_clock)
943 {
944         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
945         struct drm_device *dev = crtc->base.dev;
946         unsigned int best_error_ppm;
947         struct dpll clock;
948         uint64_t m2;
949         int found = false;
950
951         memset(best_clock, 0, sizeof(*best_clock));
952         best_error_ppm = 1000000;
953
954         /*
955          * Based on hardware doc, the n always set to 1, and m1 always
956          * set to 2.  If requires to support 200Mhz refclk, we need to
957          * revisit this because n may not 1 anymore.
958          */
959         clock.n = 1, clock.m1 = 2;
960         target *= 5;    /* fast clock */
961
962         for (clock.p1 = limit->p1.max; clock.p1 >= limit->p1.min; clock.p1--) {
963                 for (clock.p2 = limit->p2.p2_fast;
964                                 clock.p2 >= limit->p2.p2_slow;
965                                 clock.p2 -= clock.p2 > 10 ? 2 : 1) {
966                         unsigned int error_ppm;
967
968                         clock.p = clock.p1 * clock.p2;
969
970                         m2 = DIV_ROUND_CLOSEST_ULL(((uint64_t)target * clock.p *
971                                         clock.n) << 22, refclk * clock.m1);
972
973                         if (m2 > INT_MAX/clock.m1)
974                                 continue;
975
976                         clock.m2 = m2;
977
978                         chv_calc_dpll_params(refclk, &clock);
979
980                         if (!intel_PLL_is_valid(dev, limit, &clock))
981                                 continue;
982
983                         if (!vlv_PLL_is_optimal(dev, target, &clock, best_clock,
984                                                 best_error_ppm, &error_ppm))
985                                 continue;
986
987                         *best_clock = clock;
988                         best_error_ppm = error_ppm;
989                         found = true;
990                 }
991         }
992
993         return found;
994 }
995
996 bool bxt_find_best_dpll(struct intel_crtc_state *crtc_state, int target_clock,
997                         struct dpll *best_clock)
998 {
999         int refclk = 100000;
1000         const struct intel_limit *limit = &intel_limits_bxt;
1001
1002         return chv_find_best_dpll(limit, crtc_state,
1003                                   target_clock, refclk, NULL, best_clock);
1004 }
1005
1006 bool intel_crtc_active(struct drm_crtc *crtc)
1007 {
1008         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
1009
1010         /* Be paranoid as we can arrive here with only partial
1011          * state retrieved from the hardware during setup.
1012          *
1013          * We can ditch the adjusted_mode.crtc_clock check as soon
1014          * as Haswell has gained clock readout/fastboot support.
1015          *
1016          * We can ditch the crtc->primary->fb check as soon as we can
1017          * properly reconstruct framebuffers.
1018          *
1019          * FIXME: The intel_crtc->active here should be switched to
1020          * crtc->state->active once we have proper CRTC states wired up
1021          * for atomic.
1022          */
1023         return intel_crtc->active && crtc->primary->state->fb &&
1024                 intel_crtc->config->base.adjusted_mode.crtc_clock;
1025 }
1026
1027 enum transcoder intel_pipe_to_cpu_transcoder(struct drm_i915_private *dev_priv,
1028                                              enum pipe pipe)
1029 {
1030         struct drm_crtc *crtc = dev_priv->pipe_to_crtc_mapping[pipe];
1031         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
1032
1033         return intel_crtc->config->cpu_transcoder;
1034 }
1035
1036 static bool pipe_dsl_stopped(struct drm_device *dev, enum pipe pipe)
1037 {
1038         struct drm_i915_private *dev_priv = to_i915(dev);
1039         i915_reg_t reg = PIPEDSL(pipe);
1040         u32 line1, line2;
1041         u32 line_mask;
1042
1043         if (IS_GEN2(dev))
1044                 line_mask = DSL_LINEMASK_GEN2;
1045         else
1046                 line_mask = DSL_LINEMASK_GEN3;
1047
1048         line1 = I915_READ(reg) & line_mask;
1049         msleep(5);
1050         line2 = I915_READ(reg) & line_mask;
1051
1052         return line1 == line2;
1053 }
1054
1055 /*
1056  * intel_wait_for_pipe_off - wait for pipe to turn off
1057  * @crtc: crtc whose pipe to wait for
1058  *
1059  * After disabling a pipe, we can't wait for vblank in the usual way,
1060  * spinning on the vblank interrupt status bit, since we won't actually
1061  * see an interrupt when the pipe is disabled.
1062  *
1063  * On Gen4 and above:
1064  *   wait for the pipe register state bit to turn off
1065  *
1066  * Otherwise:
1067  *   wait for the display line value to settle (it usually
1068  *   ends up stopping at the start of the next frame).
1069  *
1070  */
1071 static void intel_wait_for_pipe_off(struct intel_crtc *crtc)
1072 {
1073         struct drm_device *dev = crtc->base.dev;
1074         struct drm_i915_private *dev_priv = to_i915(dev);
1075         enum transcoder cpu_transcoder = crtc->config->cpu_transcoder;
1076         enum pipe pipe = crtc->pipe;
1077
1078         if (INTEL_INFO(dev)->gen >= 4) {
1079                 i915_reg_t reg = PIPECONF(cpu_transcoder);
1080
1081                 /* Wait for the Pipe State to go off */
1082                 if (intel_wait_for_register(dev_priv,
1083                                             reg, I965_PIPECONF_ACTIVE, 0,
1084                                             100))
1085                         WARN(1, "pipe_off wait timed out\n");
1086         } else {
1087                 /* Wait for the display line to settle */
1088                 if (wait_for(pipe_dsl_stopped(dev, pipe), 100))
1089                         WARN(1, "pipe_off wait timed out\n");
1090         }
1091 }
1092
1093 /* Only for pre-ILK configs */
1094 void assert_pll(struct drm_i915_private *dev_priv,
1095                 enum pipe pipe, bool state)
1096 {
1097         u32 val;
1098         bool cur_state;
1099
1100         val = I915_READ(DPLL(pipe));
1101         cur_state = !!(val & DPLL_VCO_ENABLE);
1102         I915_STATE_WARN(cur_state != state,
1103              "PLL state assertion failure (expected %s, current %s)\n",
1104                         onoff(state), onoff(cur_state));
1105 }
1106
1107 /* XXX: the dsi pll is shared between MIPI DSI ports */
1108 void assert_dsi_pll(struct drm_i915_private *dev_priv, bool state)
1109 {
1110         u32 val;
1111         bool cur_state;
1112
1113         mutex_lock(&dev_priv->sb_lock);
1114         val = vlv_cck_read(dev_priv, CCK_REG_DSI_PLL_CONTROL);
1115         mutex_unlock(&dev_priv->sb_lock);
1116
1117         cur_state = val & DSI_PLL_VCO_EN;
1118         I915_STATE_WARN(cur_state != state,
1119              "DSI PLL state assertion failure (expected %s, current %s)\n",
1120                         onoff(state), onoff(cur_state));
1121 }
1122
1123 static void assert_fdi_tx(struct drm_i915_private *dev_priv,
1124                           enum pipe pipe, bool state)
1125 {
1126         bool cur_state;
1127         enum transcoder cpu_transcoder = intel_pipe_to_cpu_transcoder(dev_priv,
1128                                                                       pipe);
1129
1130         if (HAS_DDI(dev_priv)) {
1131                 /* DDI does not have a specific FDI_TX register */
1132                 u32 val = I915_READ(TRANS_DDI_FUNC_CTL(cpu_transcoder));
1133                 cur_state = !!(val & TRANS_DDI_FUNC_ENABLE);
1134         } else {
1135                 u32 val = I915_READ(FDI_TX_CTL(pipe));
1136                 cur_state = !!(val & FDI_TX_ENABLE);
1137         }
1138         I915_STATE_WARN(cur_state != state,
1139              "FDI TX state assertion failure (expected %s, current %s)\n",
1140                         onoff(state), onoff(cur_state));
1141 }
1142 #define assert_fdi_tx_enabled(d, p) assert_fdi_tx(d, p, true)
1143 #define assert_fdi_tx_disabled(d, p) assert_fdi_tx(d, p, false)
1144
1145 static void assert_fdi_rx(struct drm_i915_private *dev_priv,
1146                           enum pipe pipe, bool state)
1147 {
1148         u32 val;
1149         bool cur_state;
1150
1151         val = I915_READ(FDI_RX_CTL(pipe));
1152         cur_state = !!(val & FDI_RX_ENABLE);
1153         I915_STATE_WARN(cur_state != state,
1154              "FDI RX state assertion failure (expected %s, current %s)\n",
1155                         onoff(state), onoff(cur_state));
1156 }
1157 #define assert_fdi_rx_enabled(d, p) assert_fdi_rx(d, p, true)
1158 #define assert_fdi_rx_disabled(d, p) assert_fdi_rx(d, p, false)
1159
1160 static void assert_fdi_tx_pll_enabled(struct drm_i915_private *dev_priv,
1161                                       enum pipe pipe)
1162 {
1163         u32 val;
1164
1165         /* ILK FDI PLL is always enabled */
1166         if (IS_GEN5(dev_priv))
1167                 return;
1168
1169         /* On Haswell, DDI ports are responsible for the FDI PLL setup */
1170         if (HAS_DDI(dev_priv))
1171                 return;
1172
1173         val = I915_READ(FDI_TX_CTL(pipe));
1174         I915_STATE_WARN(!(val & FDI_TX_PLL_ENABLE), "FDI TX PLL assertion failure, should be active but is disabled\n");
1175 }
1176
1177 void assert_fdi_rx_pll(struct drm_i915_private *dev_priv,
1178                        enum pipe pipe, bool state)
1179 {
1180         u32 val;
1181         bool cur_state;
1182
1183         val = I915_READ(FDI_RX_CTL(pipe));
1184         cur_state = !!(val & FDI_RX_PLL_ENABLE);
1185         I915_STATE_WARN(cur_state != state,
1186              "FDI RX PLL assertion failure (expected %s, current %s)\n",
1187                         onoff(state), onoff(cur_state));
1188 }
1189
1190 void assert_panel_unlocked(struct drm_i915_private *dev_priv,
1191                            enum pipe pipe)
1192 {
1193         struct drm_device *dev = &dev_priv->drm;
1194         i915_reg_t pp_reg;
1195         u32 val;
1196         enum pipe panel_pipe = PIPE_A;
1197         bool locked = true;
1198
1199         if (WARN_ON(HAS_DDI(dev)))
1200                 return;
1201
1202         if (HAS_PCH_SPLIT(dev)) {
1203                 u32 port_sel;
1204
1205                 pp_reg = PCH_PP_CONTROL;
1206                 port_sel = I915_READ(PCH_PP_ON_DELAYS) & PANEL_PORT_SELECT_MASK;
1207
1208                 if (port_sel == PANEL_PORT_SELECT_LVDS &&
1209                     I915_READ(PCH_LVDS) & LVDS_PIPEB_SELECT)
1210                         panel_pipe = PIPE_B;
1211                 /* XXX: else fix for eDP */
1212         } else if (IS_VALLEYVIEW(dev) || IS_CHERRYVIEW(dev)) {
1213                 /* presumably write lock depends on pipe, not port select */
1214                 pp_reg = VLV_PIPE_PP_CONTROL(pipe);
1215                 panel_pipe = pipe;
1216         } else {
1217                 pp_reg = PP_CONTROL;
1218                 if (I915_READ(LVDS) & LVDS_PIPEB_SELECT)
1219                         panel_pipe = PIPE_B;
1220         }
1221
1222         val = I915_READ(pp_reg);
1223         if (!(val & PANEL_POWER_ON) ||
1224             ((val & PANEL_UNLOCK_MASK) == PANEL_UNLOCK_REGS))
1225                 locked = false;
1226
1227         I915_STATE_WARN(panel_pipe == pipe && locked,
1228              "panel assertion failure, pipe %c regs locked\n",
1229              pipe_name(pipe));
1230 }
1231
1232 static void assert_cursor(struct drm_i915_private *dev_priv,
1233                           enum pipe pipe, bool state)
1234 {
1235         struct drm_device *dev = &dev_priv->drm;
1236         bool cur_state;
1237
1238         if (IS_845G(dev) || IS_I865G(dev))
1239                 cur_state = I915_READ(CURCNTR(PIPE_A)) & CURSOR_ENABLE;
1240         else
1241                 cur_state = I915_READ(CURCNTR(pipe)) & CURSOR_MODE;
1242
1243         I915_STATE_WARN(cur_state != state,
1244              "cursor on pipe %c assertion failure (expected %s, current %s)\n",
1245                         pipe_name(pipe), onoff(state), onoff(cur_state));
1246 }
1247 #define assert_cursor_enabled(d, p) assert_cursor(d, p, true)
1248 #define assert_cursor_disabled(d, p) assert_cursor(d, p, false)
1249
1250 void assert_pipe(struct drm_i915_private *dev_priv,
1251                  enum pipe pipe, bool state)
1252 {
1253         bool cur_state;
1254         enum transcoder cpu_transcoder = intel_pipe_to_cpu_transcoder(dev_priv,
1255                                                                       pipe);
1256         enum intel_display_power_domain power_domain;
1257
1258         /* if we need the pipe quirk it must be always on */
1259         if ((pipe == PIPE_A && dev_priv->quirks & QUIRK_PIPEA_FORCE) ||
1260             (pipe == PIPE_B && dev_priv->quirks & QUIRK_PIPEB_FORCE))
1261                 state = true;
1262
1263         power_domain = POWER_DOMAIN_TRANSCODER(cpu_transcoder);
1264         if (intel_display_power_get_if_enabled(dev_priv, power_domain)) {
1265                 u32 val = I915_READ(PIPECONF(cpu_transcoder));
1266                 cur_state = !!(val & PIPECONF_ENABLE);
1267
1268                 intel_display_power_put(dev_priv, power_domain);
1269         } else {
1270                 cur_state = false;
1271         }
1272
1273         I915_STATE_WARN(cur_state != state,
1274              "pipe %c assertion failure (expected %s, current %s)\n",
1275                         pipe_name(pipe), onoff(state), onoff(cur_state));
1276 }
1277
1278 static void assert_plane(struct drm_i915_private *dev_priv,
1279                          enum plane plane, bool state)
1280 {
1281         u32 val;
1282         bool cur_state;
1283
1284         val = I915_READ(DSPCNTR(plane));
1285         cur_state = !!(val & DISPLAY_PLANE_ENABLE);
1286         I915_STATE_WARN(cur_state != state,
1287              "plane %c assertion failure (expected %s, current %s)\n",
1288                         plane_name(plane), onoff(state), onoff(cur_state));
1289 }
1290
1291 #define assert_plane_enabled(d, p) assert_plane(d, p, true)
1292 #define assert_plane_disabled(d, p) assert_plane(d, p, false)
1293
1294 static void assert_planes_disabled(struct drm_i915_private *dev_priv,
1295                                    enum pipe pipe)
1296 {
1297         struct drm_device *dev = &dev_priv->drm;
1298         int i;
1299
1300         /* Primary planes are fixed to pipes on gen4+ */
1301         if (INTEL_INFO(dev)->gen >= 4) {
1302                 u32 val = I915_READ(DSPCNTR(pipe));
1303                 I915_STATE_WARN(val & DISPLAY_PLANE_ENABLE,
1304                      "plane %c assertion failure, should be disabled but not\n",
1305                      plane_name(pipe));
1306                 return;
1307         }
1308
1309         /* Need to check both planes against the pipe */
1310         for_each_pipe(dev_priv, i) {
1311                 u32 val = I915_READ(DSPCNTR(i));
1312                 enum pipe cur_pipe = (val & DISPPLANE_SEL_PIPE_MASK) >>
1313                         DISPPLANE_SEL_PIPE_SHIFT;
1314                 I915_STATE_WARN((val & DISPLAY_PLANE_ENABLE) && pipe == cur_pipe,
1315                      "plane %c assertion failure, should be off on pipe %c but is still active\n",
1316                      plane_name(i), pipe_name(pipe));
1317         }
1318 }
1319
1320 static void assert_sprites_disabled(struct drm_i915_private *dev_priv,
1321                                     enum pipe pipe)
1322 {
1323         struct drm_device *dev = &dev_priv->drm;
1324         int sprite;
1325
1326         if (INTEL_INFO(dev)->gen >= 9) {
1327                 for_each_sprite(dev_priv, pipe, sprite) {
1328                         u32 val = I915_READ(PLANE_CTL(pipe, sprite));
1329                         I915_STATE_WARN(val & PLANE_CTL_ENABLE,
1330                              "plane %d assertion failure, should be off on pipe %c but is still active\n",
1331                              sprite, pipe_name(pipe));
1332                 }
1333         } else if (IS_VALLEYVIEW(dev) || IS_CHERRYVIEW(dev)) {
1334                 for_each_sprite(dev_priv, pipe, sprite) {
1335                         u32 val = I915_READ(SPCNTR(pipe, sprite));
1336                         I915_STATE_WARN(val & SP_ENABLE,
1337                              "sprite %c assertion failure, should be off on pipe %c but is still active\n",
1338                              sprite_name(pipe, sprite), pipe_name(pipe));
1339                 }
1340         } else if (INTEL_INFO(dev)->gen >= 7) {
1341                 u32 val = I915_READ(SPRCTL(pipe));
1342                 I915_STATE_WARN(val & SPRITE_ENABLE,
1343                      "sprite %c assertion failure, should be off on pipe %c but is still active\n",
1344                      plane_name(pipe), pipe_name(pipe));
1345         } else if (INTEL_INFO(dev)->gen >= 5) {
1346                 u32 val = I915_READ(DVSCNTR(pipe));
1347                 I915_STATE_WARN(val & DVS_ENABLE,
1348                      "sprite %c assertion failure, should be off on pipe %c but is still active\n",
1349                      plane_name(pipe), pipe_name(pipe));
1350         }
1351 }
1352
1353 static void assert_vblank_disabled(struct drm_crtc *crtc)
1354 {
1355         if (I915_STATE_WARN_ON(drm_crtc_vblank_get(crtc) == 0))
1356                 drm_crtc_vblank_put(crtc);
1357 }
1358
1359 void assert_pch_transcoder_disabled(struct drm_i915_private *dev_priv,
1360                                     enum pipe pipe)
1361 {
1362         u32 val;
1363         bool enabled;
1364
1365         val = I915_READ(PCH_TRANSCONF(pipe));
1366         enabled = !!(val & TRANS_ENABLE);
1367         I915_STATE_WARN(enabled,
1368              "transcoder assertion failed, should be off on pipe %c but is still active\n",
1369              pipe_name(pipe));
1370 }
1371
1372 static bool dp_pipe_enabled(struct drm_i915_private *dev_priv,
1373                             enum pipe pipe, u32 port_sel, u32 val)
1374 {
1375         if ((val & DP_PORT_EN) == 0)
1376                 return false;
1377
1378         if (HAS_PCH_CPT(dev_priv)) {
1379                 u32 trans_dp_ctl = I915_READ(TRANS_DP_CTL(pipe));
1380                 if ((trans_dp_ctl & TRANS_DP_PORT_SEL_MASK) != port_sel)
1381                         return false;
1382         } else if (IS_CHERRYVIEW(dev_priv)) {
1383                 if ((val & DP_PIPE_MASK_CHV) != DP_PIPE_SELECT_CHV(pipe))
1384                         return false;
1385         } else {
1386                 if ((val & DP_PIPE_MASK) != (pipe << 30))
1387                         return false;
1388         }
1389         return true;
1390 }
1391
1392 static bool hdmi_pipe_enabled(struct drm_i915_private *dev_priv,
1393                               enum pipe pipe, u32 val)
1394 {
1395         if ((val & SDVO_ENABLE) == 0)
1396                 return false;
1397
1398         if (HAS_PCH_CPT(dev_priv)) {
1399                 if ((val & SDVO_PIPE_SEL_MASK_CPT) != SDVO_PIPE_SEL_CPT(pipe))
1400                         return false;
1401         } else if (IS_CHERRYVIEW(dev_priv)) {
1402                 if ((val & SDVO_PIPE_SEL_MASK_CHV) != SDVO_PIPE_SEL_CHV(pipe))
1403                         return false;
1404         } else {
1405                 if ((val & SDVO_PIPE_SEL_MASK) != SDVO_PIPE_SEL(pipe))
1406                         return false;
1407         }
1408         return true;
1409 }
1410
1411 static bool lvds_pipe_enabled(struct drm_i915_private *dev_priv,
1412                               enum pipe pipe, u32 val)
1413 {
1414         if ((val & LVDS_PORT_EN) == 0)
1415                 return false;
1416
1417         if (HAS_PCH_CPT(dev_priv)) {
1418                 if ((val & PORT_TRANS_SEL_MASK) != PORT_TRANS_SEL_CPT(pipe))
1419                         return false;
1420         } else {
1421                 if ((val & LVDS_PIPE_MASK) != LVDS_PIPE(pipe))
1422                         return false;
1423         }
1424         return true;
1425 }
1426
1427 static bool adpa_pipe_enabled(struct drm_i915_private *dev_priv,
1428                               enum pipe pipe, u32 val)
1429 {
1430         if ((val & ADPA_DAC_ENABLE) == 0)
1431                 return false;
1432         if (HAS_PCH_CPT(dev_priv)) {
1433                 if ((val & PORT_TRANS_SEL_MASK) != PORT_TRANS_SEL_CPT(pipe))
1434                         return false;
1435         } else {
1436                 if ((val & ADPA_PIPE_SELECT_MASK) != ADPA_PIPE_SELECT(pipe))
1437                         return false;
1438         }
1439         return true;
1440 }
1441
1442 static void assert_pch_dp_disabled(struct drm_i915_private *dev_priv,
1443                                    enum pipe pipe, i915_reg_t reg,
1444                                    u32 port_sel)
1445 {
1446         u32 val = I915_READ(reg);
1447         I915_STATE_WARN(dp_pipe_enabled(dev_priv, pipe, port_sel, val),
1448              "PCH DP (0x%08x) enabled on transcoder %c, should be disabled\n",
1449              i915_mmio_reg_offset(reg), pipe_name(pipe));
1450
1451         I915_STATE_WARN(HAS_PCH_IBX(dev_priv) && (val & DP_PORT_EN) == 0
1452              && (val & DP_PIPEB_SELECT),
1453              "IBX PCH dp port still using transcoder B\n");
1454 }
1455
1456 static void assert_pch_hdmi_disabled(struct drm_i915_private *dev_priv,
1457                                      enum pipe pipe, i915_reg_t reg)
1458 {
1459         u32 val = I915_READ(reg);
1460         I915_STATE_WARN(hdmi_pipe_enabled(dev_priv, pipe, val),
1461              "PCH HDMI (0x%08x) enabled on transcoder %c, should be disabled\n",
1462              i915_mmio_reg_offset(reg), pipe_name(pipe));
1463
1464         I915_STATE_WARN(HAS_PCH_IBX(dev_priv) && (val & SDVO_ENABLE) == 0
1465              && (val & SDVO_PIPE_B_SELECT),
1466              "IBX PCH hdmi port still using transcoder B\n");
1467 }
1468
1469 static void assert_pch_ports_disabled(struct drm_i915_private *dev_priv,
1470                                       enum pipe pipe)
1471 {
1472         u32 val;
1473
1474         assert_pch_dp_disabled(dev_priv, pipe, PCH_DP_B, TRANS_DP_PORT_SEL_B);
1475         assert_pch_dp_disabled(dev_priv, pipe, PCH_DP_C, TRANS_DP_PORT_SEL_C);
1476         assert_pch_dp_disabled(dev_priv, pipe, PCH_DP_D, TRANS_DP_PORT_SEL_D);
1477
1478         val = I915_READ(PCH_ADPA);
1479         I915_STATE_WARN(adpa_pipe_enabled(dev_priv, pipe, val),
1480              "PCH VGA enabled on transcoder %c, should be disabled\n",
1481              pipe_name(pipe));
1482
1483         val = I915_READ(PCH_LVDS);
1484         I915_STATE_WARN(lvds_pipe_enabled(dev_priv, pipe, val),
1485              "PCH LVDS enabled on transcoder %c, should be disabled\n",
1486              pipe_name(pipe));
1487
1488         assert_pch_hdmi_disabled(dev_priv, pipe, PCH_HDMIB);
1489         assert_pch_hdmi_disabled(dev_priv, pipe, PCH_HDMIC);
1490         assert_pch_hdmi_disabled(dev_priv, pipe, PCH_HDMID);
1491 }
1492
1493 static void _vlv_enable_pll(struct intel_crtc *crtc,
1494                             const struct intel_crtc_state *pipe_config)
1495 {
1496         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1497         enum pipe pipe = crtc->pipe;
1498
1499         I915_WRITE(DPLL(pipe), pipe_config->dpll_hw_state.dpll);
1500         POSTING_READ(DPLL(pipe));
1501         udelay(150);
1502
1503         if (intel_wait_for_register(dev_priv,
1504                                     DPLL(pipe),
1505                                     DPLL_LOCK_VLV,
1506                                     DPLL_LOCK_VLV,
1507                                     1))
1508                 DRM_ERROR("DPLL %d failed to lock\n", pipe);
1509 }
1510
1511 static void vlv_enable_pll(struct intel_crtc *crtc,
1512                            const struct intel_crtc_state *pipe_config)
1513 {
1514         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1515         enum pipe pipe = crtc->pipe;
1516
1517         assert_pipe_disabled(dev_priv, pipe);
1518
1519         /* PLL is protected by panel, make sure we can write it */
1520         assert_panel_unlocked(dev_priv, pipe);
1521
1522         if (pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE)
1523                 _vlv_enable_pll(crtc, pipe_config);
1524
1525         I915_WRITE(DPLL_MD(pipe), pipe_config->dpll_hw_state.dpll_md);
1526         POSTING_READ(DPLL_MD(pipe));
1527 }
1528
1529
1530 static void _chv_enable_pll(struct intel_crtc *crtc,
1531                             const struct intel_crtc_state *pipe_config)
1532 {
1533         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1534         enum pipe pipe = crtc->pipe;
1535         enum dpio_channel port = vlv_pipe_to_channel(pipe);
1536         u32 tmp;
1537
1538         mutex_lock(&dev_priv->sb_lock);
1539
1540         /* Enable back the 10bit clock to display controller */
1541         tmp = vlv_dpio_read(dev_priv, pipe, CHV_CMN_DW14(port));
1542         tmp |= DPIO_DCLKP_EN;
1543         vlv_dpio_write(dev_priv, pipe, CHV_CMN_DW14(port), tmp);
1544
1545         mutex_unlock(&dev_priv->sb_lock);
1546
1547         /*
1548          * Need to wait > 100ns between dclkp clock enable bit and PLL enable.
1549          */
1550         udelay(1);
1551
1552         /* Enable PLL */
1553         I915_WRITE(DPLL(pipe), pipe_config->dpll_hw_state.dpll);
1554
1555         /* Check PLL is locked */
1556         if (intel_wait_for_register(dev_priv,
1557                                     DPLL(pipe), DPLL_LOCK_VLV, DPLL_LOCK_VLV,
1558                                     1))
1559                 DRM_ERROR("PLL %d failed to lock\n", pipe);
1560 }
1561
1562 static void chv_enable_pll(struct intel_crtc *crtc,
1563                            const struct intel_crtc_state *pipe_config)
1564 {
1565         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1566         enum pipe pipe = crtc->pipe;
1567
1568         assert_pipe_disabled(dev_priv, pipe);
1569
1570         /* PLL is protected by panel, make sure we can write it */
1571         assert_panel_unlocked(dev_priv, pipe);
1572
1573         if (pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE)
1574                 _chv_enable_pll(crtc, pipe_config);
1575
1576         if (pipe != PIPE_A) {
1577                 /*
1578                  * WaPixelRepeatModeFixForC0:chv
1579                  *
1580                  * DPLLCMD is AWOL. Use chicken bits to propagate
1581                  * the value from DPLLBMD to either pipe B or C.
1582                  */
1583                 I915_WRITE(CBR4_VLV, pipe == PIPE_B ? CBR_DPLLBMD_PIPE_B : CBR_DPLLBMD_PIPE_C);
1584                 I915_WRITE(DPLL_MD(PIPE_B), pipe_config->dpll_hw_state.dpll_md);
1585                 I915_WRITE(CBR4_VLV, 0);
1586                 dev_priv->chv_dpll_md[pipe] = pipe_config->dpll_hw_state.dpll_md;
1587
1588                 /*
1589                  * DPLLB VGA mode also seems to cause problems.
1590                  * We should always have it disabled.
1591                  */
1592                 WARN_ON((I915_READ(DPLL(PIPE_B)) & DPLL_VGA_MODE_DIS) == 0);
1593         } else {
1594                 I915_WRITE(DPLL_MD(pipe), pipe_config->dpll_hw_state.dpll_md);
1595                 POSTING_READ(DPLL_MD(pipe));
1596         }
1597 }
1598
1599 static int intel_num_dvo_pipes(struct drm_device *dev)
1600 {
1601         struct intel_crtc *crtc;
1602         int count = 0;
1603
1604         for_each_intel_crtc(dev, crtc) {
1605                 count += crtc->base.state->active &&
1606                         intel_crtc_has_type(crtc->config, INTEL_OUTPUT_DVO);
1607         }
1608
1609         return count;
1610 }
1611
1612 static void i9xx_enable_pll(struct intel_crtc *crtc)
1613 {
1614         struct drm_device *dev = crtc->base.dev;
1615         struct drm_i915_private *dev_priv = to_i915(dev);
1616         i915_reg_t reg = DPLL(crtc->pipe);
1617         u32 dpll = crtc->config->dpll_hw_state.dpll;
1618
1619         assert_pipe_disabled(dev_priv, crtc->pipe);
1620
1621         /* PLL is protected by panel, make sure we can write it */
1622         if (IS_MOBILE(dev) && !IS_I830(dev))
1623                 assert_panel_unlocked(dev_priv, crtc->pipe);
1624
1625         /* Enable DVO 2x clock on both PLLs if necessary */
1626         if (IS_I830(dev) && intel_num_dvo_pipes(dev) > 0) {
1627                 /*
1628                  * It appears to be important that we don't enable this
1629                  * for the current pipe before otherwise configuring the
1630                  * PLL. No idea how this should be handled if multiple
1631                  * DVO outputs are enabled simultaneosly.
1632                  */
1633                 dpll |= DPLL_DVO_2X_MODE;
1634                 I915_WRITE(DPLL(!crtc->pipe),
1635                            I915_READ(DPLL(!crtc->pipe)) | DPLL_DVO_2X_MODE);
1636         }
1637
1638         /*
1639          * Apparently we need to have VGA mode enabled prior to changing
1640          * the P1/P2 dividers. Otherwise the DPLL will keep using the old
1641          * dividers, even though the register value does change.
1642          */
1643         I915_WRITE(reg, 0);
1644
1645         I915_WRITE(reg, dpll);
1646
1647         /* Wait for the clocks to stabilize. */
1648         POSTING_READ(reg);
1649         udelay(150);
1650
1651         if (INTEL_INFO(dev)->gen >= 4) {
1652                 I915_WRITE(DPLL_MD(crtc->pipe),
1653                            crtc->config->dpll_hw_state.dpll_md);
1654         } else {
1655                 /* The pixel multiplier can only be updated once the
1656                  * DPLL is enabled and the clocks are stable.
1657                  *
1658                  * So write it again.
1659                  */
1660                 I915_WRITE(reg, dpll);
1661         }
1662
1663         /* We do this three times for luck */
1664         I915_WRITE(reg, dpll);
1665         POSTING_READ(reg);
1666         udelay(150); /* wait for warmup */
1667         I915_WRITE(reg, dpll);
1668         POSTING_READ(reg);
1669         udelay(150); /* wait for warmup */
1670         I915_WRITE(reg, dpll);
1671         POSTING_READ(reg);
1672         udelay(150); /* wait for warmup */
1673 }
1674
1675 /**
1676  * i9xx_disable_pll - disable a PLL
1677  * @dev_priv: i915 private structure
1678  * @pipe: pipe PLL to disable
1679  *
1680  * Disable the PLL for @pipe, making sure the pipe is off first.
1681  *
1682  * Note!  This is for pre-ILK only.
1683  */
1684 static void i9xx_disable_pll(struct intel_crtc *crtc)
1685 {
1686         struct drm_device *dev = crtc->base.dev;
1687         struct drm_i915_private *dev_priv = to_i915(dev);
1688         enum pipe pipe = crtc->pipe;
1689
1690         /* Disable DVO 2x clock on both PLLs if necessary */
1691         if (IS_I830(dev) &&
1692             intel_crtc_has_type(crtc->config, INTEL_OUTPUT_DVO) &&
1693             !intel_num_dvo_pipes(dev)) {
1694                 I915_WRITE(DPLL(PIPE_B),
1695                            I915_READ(DPLL(PIPE_B)) & ~DPLL_DVO_2X_MODE);
1696                 I915_WRITE(DPLL(PIPE_A),
1697                            I915_READ(DPLL(PIPE_A)) & ~DPLL_DVO_2X_MODE);
1698         }
1699
1700         /* Don't disable pipe or pipe PLLs if needed */
1701         if ((pipe == PIPE_A && dev_priv->quirks & QUIRK_PIPEA_FORCE) ||
1702             (pipe == PIPE_B && dev_priv->quirks & QUIRK_PIPEB_FORCE))
1703                 return;
1704
1705         /* Make sure the pipe isn't still relying on us */
1706         assert_pipe_disabled(dev_priv, pipe);
1707
1708         I915_WRITE(DPLL(pipe), DPLL_VGA_MODE_DIS);
1709         POSTING_READ(DPLL(pipe));
1710 }
1711
1712 static void vlv_disable_pll(struct drm_i915_private *dev_priv, enum pipe pipe)
1713 {
1714         u32 val;
1715
1716         /* Make sure the pipe isn't still relying on us */
1717         assert_pipe_disabled(dev_priv, pipe);
1718
1719         val = DPLL_INTEGRATED_REF_CLK_VLV |
1720                 DPLL_REF_CLK_ENABLE_VLV | DPLL_VGA_MODE_DIS;
1721         if (pipe != PIPE_A)
1722                 val |= DPLL_INTEGRATED_CRI_CLK_VLV;
1723
1724         I915_WRITE(DPLL(pipe), val);
1725         POSTING_READ(DPLL(pipe));
1726 }
1727
1728 static void chv_disable_pll(struct drm_i915_private *dev_priv, enum pipe pipe)
1729 {
1730         enum dpio_channel port = vlv_pipe_to_channel(pipe);
1731         u32 val;
1732
1733         /* Make sure the pipe isn't still relying on us */
1734         assert_pipe_disabled(dev_priv, pipe);
1735
1736         val = DPLL_SSC_REF_CLK_CHV |
1737                 DPLL_REF_CLK_ENABLE_VLV | DPLL_VGA_MODE_DIS;
1738         if (pipe != PIPE_A)
1739                 val |= DPLL_INTEGRATED_CRI_CLK_VLV;
1740
1741         I915_WRITE(DPLL(pipe), val);
1742         POSTING_READ(DPLL(pipe));
1743
1744         mutex_lock(&dev_priv->sb_lock);
1745
1746         /* Disable 10bit clock to display controller */
1747         val = vlv_dpio_read(dev_priv, pipe, CHV_CMN_DW14(port));
1748         val &= ~DPIO_DCLKP_EN;
1749         vlv_dpio_write(dev_priv, pipe, CHV_CMN_DW14(port), val);
1750
1751         mutex_unlock(&dev_priv->sb_lock);
1752 }
1753
1754 void vlv_wait_port_ready(struct drm_i915_private *dev_priv,
1755                          struct intel_digital_port *dport,
1756                          unsigned int expected_mask)
1757 {
1758         u32 port_mask;
1759         i915_reg_t dpll_reg;
1760
1761         switch (dport->port) {
1762         case PORT_B:
1763                 port_mask = DPLL_PORTB_READY_MASK;
1764                 dpll_reg = DPLL(0);
1765                 break;
1766         case PORT_C:
1767                 port_mask = DPLL_PORTC_READY_MASK;
1768                 dpll_reg = DPLL(0);
1769                 expected_mask <<= 4;
1770                 break;
1771         case PORT_D:
1772                 port_mask = DPLL_PORTD_READY_MASK;
1773                 dpll_reg = DPIO_PHY_STATUS;
1774                 break;
1775         default:
1776                 BUG();
1777         }
1778
1779         if (intel_wait_for_register(dev_priv,
1780                                     dpll_reg, port_mask, expected_mask,
1781                                     1000))
1782                 WARN(1, "timed out waiting for port %c ready: got 0x%x, expected 0x%x\n",
1783                      port_name(dport->port), I915_READ(dpll_reg) & port_mask, expected_mask);
1784 }
1785
1786 static void ironlake_enable_pch_transcoder(struct drm_i915_private *dev_priv,
1787                                            enum pipe pipe)
1788 {
1789         struct drm_device *dev = &dev_priv->drm;
1790         struct drm_crtc *crtc = dev_priv->pipe_to_crtc_mapping[pipe];
1791         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
1792         i915_reg_t reg;
1793         uint32_t val, pipeconf_val;
1794
1795         /* Make sure PCH DPLL is enabled */
1796         assert_shared_dpll_enabled(dev_priv, intel_crtc->config->shared_dpll);
1797
1798         /* FDI must be feeding us bits for PCH ports */
1799         assert_fdi_tx_enabled(dev_priv, pipe);
1800         assert_fdi_rx_enabled(dev_priv, pipe);
1801
1802         if (HAS_PCH_CPT(dev)) {
1803                 /* Workaround: Set the timing override bit before enabling the
1804                  * pch transcoder. */
1805                 reg = TRANS_CHICKEN2(pipe);
1806                 val = I915_READ(reg);
1807                 val |= TRANS_CHICKEN2_TIMING_OVERRIDE;
1808                 I915_WRITE(reg, val);
1809         }
1810
1811         reg = PCH_TRANSCONF(pipe);
1812         val = I915_READ(reg);
1813         pipeconf_val = I915_READ(PIPECONF(pipe));
1814
1815         if (HAS_PCH_IBX(dev_priv)) {
1816                 /*
1817                  * Make the BPC in transcoder be consistent with
1818                  * that in pipeconf reg. For HDMI we must use 8bpc
1819                  * here for both 8bpc and 12bpc.
1820                  */
1821                 val &= ~PIPECONF_BPC_MASK;
1822                 if (intel_crtc_has_type(intel_crtc->config, INTEL_OUTPUT_HDMI))
1823                         val |= PIPECONF_8BPC;
1824                 else
1825                         val |= pipeconf_val & PIPECONF_BPC_MASK;
1826         }
1827
1828         val &= ~TRANS_INTERLACE_MASK;
1829         if ((pipeconf_val & PIPECONF_INTERLACE_MASK) == PIPECONF_INTERLACED_ILK)
1830                 if (HAS_PCH_IBX(dev_priv) &&
1831                     intel_crtc_has_type(intel_crtc->config, INTEL_OUTPUT_SDVO))
1832                         val |= TRANS_LEGACY_INTERLACED_ILK;
1833                 else
1834                         val |= TRANS_INTERLACED;
1835         else
1836                 val |= TRANS_PROGRESSIVE;
1837
1838         I915_WRITE(reg, val | TRANS_ENABLE);
1839         if (intel_wait_for_register(dev_priv,
1840                                     reg, TRANS_STATE_ENABLE, TRANS_STATE_ENABLE,
1841                                     100))
1842                 DRM_ERROR("failed to enable transcoder %c\n", pipe_name(pipe));
1843 }
1844
1845 static void lpt_enable_pch_transcoder(struct drm_i915_private *dev_priv,
1846                                       enum transcoder cpu_transcoder)
1847 {
1848         u32 val, pipeconf_val;
1849
1850         /* FDI must be feeding us bits for PCH ports */
1851         assert_fdi_tx_enabled(dev_priv, (enum pipe) cpu_transcoder);
1852         assert_fdi_rx_enabled(dev_priv, TRANSCODER_A);
1853
1854         /* Workaround: set timing override bit. */
1855         val = I915_READ(TRANS_CHICKEN2(PIPE_A));
1856         val |= TRANS_CHICKEN2_TIMING_OVERRIDE;
1857         I915_WRITE(TRANS_CHICKEN2(PIPE_A), val);
1858
1859         val = TRANS_ENABLE;
1860         pipeconf_val = I915_READ(PIPECONF(cpu_transcoder));
1861
1862         if ((pipeconf_val & PIPECONF_INTERLACE_MASK_HSW) ==
1863             PIPECONF_INTERLACED_ILK)
1864                 val |= TRANS_INTERLACED;
1865         else
1866                 val |= TRANS_PROGRESSIVE;
1867
1868         I915_WRITE(LPT_TRANSCONF, val);
1869         if (intel_wait_for_register(dev_priv,
1870                                     LPT_TRANSCONF,
1871                                     TRANS_STATE_ENABLE,
1872                                     TRANS_STATE_ENABLE,
1873                                     100))
1874                 DRM_ERROR("Failed to enable PCH transcoder\n");
1875 }
1876
1877 static void ironlake_disable_pch_transcoder(struct drm_i915_private *dev_priv,
1878                                             enum pipe pipe)
1879 {
1880         struct drm_device *dev = &dev_priv->drm;
1881         i915_reg_t reg;
1882         uint32_t val;
1883
1884         /* FDI relies on the transcoder */
1885         assert_fdi_tx_disabled(dev_priv, pipe);
1886         assert_fdi_rx_disabled(dev_priv, pipe);
1887
1888         /* Ports must be off as well */
1889         assert_pch_ports_disabled(dev_priv, pipe);
1890
1891         reg = PCH_TRANSCONF(pipe);
1892         val = I915_READ(reg);
1893         val &= ~TRANS_ENABLE;
1894         I915_WRITE(reg, val);
1895         /* wait for PCH transcoder off, transcoder state */
1896         if (intel_wait_for_register(dev_priv,
1897                                     reg, TRANS_STATE_ENABLE, 0,
1898                                     50))
1899                 DRM_ERROR("failed to disable transcoder %c\n", pipe_name(pipe));
1900
1901         if (HAS_PCH_CPT(dev)) {
1902                 /* Workaround: Clear the timing override chicken bit again. */
1903                 reg = TRANS_CHICKEN2(pipe);
1904                 val = I915_READ(reg);
1905                 val &= ~TRANS_CHICKEN2_TIMING_OVERRIDE;
1906                 I915_WRITE(reg, val);
1907         }
1908 }
1909
1910 static void lpt_disable_pch_transcoder(struct drm_i915_private *dev_priv)
1911 {
1912         u32 val;
1913
1914         val = I915_READ(LPT_TRANSCONF);
1915         val &= ~TRANS_ENABLE;
1916         I915_WRITE(LPT_TRANSCONF, val);
1917         /* wait for PCH transcoder off, transcoder state */
1918         if (intel_wait_for_register(dev_priv,
1919                                     LPT_TRANSCONF, TRANS_STATE_ENABLE, 0,
1920                                     50))
1921                 DRM_ERROR("Failed to disable PCH transcoder\n");
1922
1923         /* Workaround: clear timing override bit. */
1924         val = I915_READ(TRANS_CHICKEN2(PIPE_A));
1925         val &= ~TRANS_CHICKEN2_TIMING_OVERRIDE;
1926         I915_WRITE(TRANS_CHICKEN2(PIPE_A), val);
1927 }
1928
1929 /**
1930  * intel_enable_pipe - enable a pipe, asserting requirements
1931  * @crtc: crtc responsible for the pipe
1932  *
1933  * Enable @crtc's pipe, making sure that various hardware specific requirements
1934  * are met, if applicable, e.g. PLL enabled, LVDS pairs enabled, etc.
1935  */
1936 static void intel_enable_pipe(struct intel_crtc *crtc)
1937 {
1938         struct drm_device *dev = crtc->base.dev;
1939         struct drm_i915_private *dev_priv = to_i915(dev);
1940         enum pipe pipe = crtc->pipe;
1941         enum transcoder cpu_transcoder = crtc->config->cpu_transcoder;
1942         enum pipe pch_transcoder;
1943         i915_reg_t reg;
1944         u32 val;
1945
1946         DRM_DEBUG_KMS("enabling pipe %c\n", pipe_name(pipe));
1947
1948         assert_planes_disabled(dev_priv, pipe);
1949         assert_cursor_disabled(dev_priv, pipe);
1950         assert_sprites_disabled(dev_priv, pipe);
1951
1952         if (HAS_PCH_LPT(dev_priv))
1953                 pch_transcoder = TRANSCODER_A;
1954         else
1955                 pch_transcoder = pipe;
1956
1957         /*
1958          * A pipe without a PLL won't actually be able to drive bits from
1959          * a plane.  On ILK+ the pipe PLLs are integrated, so we don't
1960          * need the check.
1961          */
1962         if (HAS_GMCH_DISPLAY(dev_priv))
1963                 if (intel_crtc_has_type(crtc->config, INTEL_OUTPUT_DSI))
1964                         assert_dsi_pll_enabled(dev_priv);
1965                 else
1966                         assert_pll_enabled(dev_priv, pipe);
1967         else {
1968                 if (crtc->config->has_pch_encoder) {
1969                         /* if driving the PCH, we need FDI enabled */
1970                         assert_fdi_rx_pll_enabled(dev_priv, pch_transcoder);
1971                         assert_fdi_tx_pll_enabled(dev_priv,
1972                                                   (enum pipe) cpu_transcoder);
1973                 }
1974                 /* FIXME: assert CPU port conditions for SNB+ */
1975         }
1976
1977         reg = PIPECONF(cpu_transcoder);
1978         val = I915_READ(reg);
1979         if (val & PIPECONF_ENABLE) {
1980                 WARN_ON(!((pipe == PIPE_A && dev_priv->quirks & QUIRK_PIPEA_FORCE) ||
1981                           (pipe == PIPE_B && dev_priv->quirks & QUIRK_PIPEB_FORCE)));
1982                 return;
1983         }
1984
1985         I915_WRITE(reg, val | PIPECONF_ENABLE);
1986         POSTING_READ(reg);
1987
1988         /*
1989          * Until the pipe starts DSL will read as 0, which would cause
1990          * an apparent vblank timestamp jump, which messes up also the
1991          * frame count when it's derived from the timestamps. So let's
1992          * wait for the pipe to start properly before we call
1993          * drm_crtc_vblank_on()
1994          */
1995         if (dev->max_vblank_count == 0 &&
1996             wait_for(intel_get_crtc_scanline(crtc) != crtc->scanline_offset, 50))
1997                 DRM_ERROR("pipe %c didn't start\n", pipe_name(pipe));
1998 }
1999
2000 /**
2001  * intel_disable_pipe - disable a pipe, asserting requirements
2002  * @crtc: crtc whose pipes is to be disabled
2003  *
2004  * Disable the pipe of @crtc, making sure that various hardware
2005  * specific requirements are met, if applicable, e.g. plane
2006  * disabled, panel fitter off, etc.
2007  *
2008  * Will wait until the pipe has shut down before returning.
2009  */
2010 static void intel_disable_pipe(struct intel_crtc *crtc)
2011 {
2012         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
2013         enum transcoder cpu_transcoder = crtc->config->cpu_transcoder;
2014         enum pipe pipe = crtc->pipe;
2015         i915_reg_t reg;
2016         u32 val;
2017
2018         DRM_DEBUG_KMS("disabling pipe %c\n", pipe_name(pipe));
2019
2020         /*
2021          * Make sure planes won't keep trying to pump pixels to us,
2022          * or we might hang the display.
2023          */
2024         assert_planes_disabled(dev_priv, pipe);
2025         assert_cursor_disabled(dev_priv, pipe);
2026         assert_sprites_disabled(dev_priv, pipe);
2027
2028         reg = PIPECONF(cpu_transcoder);
2029         val = I915_READ(reg);
2030         if ((val & PIPECONF_ENABLE) == 0)
2031                 return;
2032
2033         /*
2034          * Double wide has implications for planes
2035          * so best keep it disabled when not needed.
2036          */
2037         if (crtc->config->double_wide)
2038                 val &= ~PIPECONF_DOUBLE_WIDE;
2039
2040         /* Don't disable pipe or pipe PLLs if needed */
2041         if (!(pipe == PIPE_A && dev_priv->quirks & QUIRK_PIPEA_FORCE) &&
2042             !(pipe == PIPE_B && dev_priv->quirks & QUIRK_PIPEB_FORCE))
2043                 val &= ~PIPECONF_ENABLE;
2044
2045         I915_WRITE(reg, val);
2046         if ((val & PIPECONF_ENABLE) == 0)
2047                 intel_wait_for_pipe_off(crtc);
2048 }
2049
2050 static unsigned int intel_tile_size(const struct drm_i915_private *dev_priv)
2051 {
2052         return IS_GEN2(dev_priv) ? 2048 : 4096;
2053 }
2054
2055 static unsigned int intel_tile_width_bytes(const struct drm_i915_private *dev_priv,
2056                                            uint64_t fb_modifier, unsigned int cpp)
2057 {
2058         switch (fb_modifier) {
2059         case DRM_FORMAT_MOD_NONE:
2060                 return cpp;
2061         case I915_FORMAT_MOD_X_TILED:
2062                 if (IS_GEN2(dev_priv))
2063                         return 128;
2064                 else
2065                         return 512;
2066         case I915_FORMAT_MOD_Y_TILED:
2067                 if (IS_GEN2(dev_priv) || HAS_128_BYTE_Y_TILING(dev_priv))
2068                         return 128;
2069                 else
2070                         return 512;
2071         case I915_FORMAT_MOD_Yf_TILED:
2072                 switch (cpp) {
2073                 case 1:
2074                         return 64;
2075                 case 2:
2076                 case 4:
2077                         return 128;
2078                 case 8:
2079                 case 16:
2080                         return 256;
2081                 default:
2082                         MISSING_CASE(cpp);
2083                         return cpp;
2084                 }
2085                 break;
2086         default:
2087                 MISSING_CASE(fb_modifier);
2088                 return cpp;
2089         }
2090 }
2091
2092 unsigned int intel_tile_height(const struct drm_i915_private *dev_priv,
2093                                uint64_t fb_modifier, unsigned int cpp)
2094 {
2095         if (fb_modifier == DRM_FORMAT_MOD_NONE)
2096                 return 1;
2097         else
2098                 return intel_tile_size(dev_priv) /
2099                         intel_tile_width_bytes(dev_priv, fb_modifier, cpp);
2100 }
2101
2102 /* Return the tile dimensions in pixel units */
2103 static void intel_tile_dims(const struct drm_i915_private *dev_priv,
2104                             unsigned int *tile_width,
2105                             unsigned int *tile_height,
2106                             uint64_t fb_modifier,
2107                             unsigned int cpp)
2108 {
2109         unsigned int tile_width_bytes =
2110                 intel_tile_width_bytes(dev_priv, fb_modifier, cpp);
2111
2112         *tile_width = tile_width_bytes / cpp;
2113         *tile_height = intel_tile_size(dev_priv) / tile_width_bytes;
2114 }
2115
2116 unsigned int
2117 intel_fb_align_height(struct drm_device *dev, unsigned int height,
2118                       uint32_t pixel_format, uint64_t fb_modifier)
2119 {
2120         unsigned int cpp = drm_format_plane_cpp(pixel_format, 0);
2121         unsigned int tile_height = intel_tile_height(to_i915(dev), fb_modifier, cpp);
2122
2123         return ALIGN(height, tile_height);
2124 }
2125
2126 unsigned int intel_rotation_info_size(const struct intel_rotation_info *rot_info)
2127 {
2128         unsigned int size = 0;
2129         int i;
2130
2131         for (i = 0 ; i < ARRAY_SIZE(rot_info->plane); i++)
2132                 size += rot_info->plane[i].width * rot_info->plane[i].height;
2133
2134         return size;
2135 }
2136
2137 static void
2138 intel_fill_fb_ggtt_view(struct i915_ggtt_view *view,
2139                         const struct drm_framebuffer *fb,
2140                         unsigned int rotation)
2141 {
2142         if (intel_rotation_90_or_270(rotation)) {
2143                 *view = i915_ggtt_view_rotated;
2144                 view->params.rotated = to_intel_framebuffer(fb)->rot_info;
2145         } else {
2146                 *view = i915_ggtt_view_normal;
2147         }
2148 }
2149
2150 static void
2151 intel_fill_fb_info(struct drm_i915_private *dev_priv,
2152                    struct drm_framebuffer *fb)
2153 {
2154         struct intel_rotation_info *info = &to_intel_framebuffer(fb)->rot_info;
2155         unsigned int tile_size, tile_width, tile_height, cpp;
2156
2157         tile_size = intel_tile_size(dev_priv);
2158
2159         cpp = drm_format_plane_cpp(fb->pixel_format, 0);
2160         intel_tile_dims(dev_priv, &tile_width, &tile_height,
2161                         fb->modifier[0], cpp);
2162
2163         info->plane[0].width = DIV_ROUND_UP(fb->pitches[0], tile_width * cpp);
2164         info->plane[0].height = DIV_ROUND_UP(fb->height, tile_height);
2165
2166         if (info->pixel_format == DRM_FORMAT_NV12) {
2167                 cpp = drm_format_plane_cpp(fb->pixel_format, 1);
2168                 intel_tile_dims(dev_priv, &tile_width, &tile_height,
2169                                 fb->modifier[1], cpp);
2170
2171                 info->uv_offset = fb->offsets[1];
2172                 info->plane[1].width = DIV_ROUND_UP(fb->pitches[1], tile_width * cpp);
2173                 info->plane[1].height = DIV_ROUND_UP(fb->height / 2, tile_height);
2174         }
2175 }
2176
2177 static unsigned int intel_linear_alignment(const struct drm_i915_private *dev_priv)
2178 {
2179         if (INTEL_INFO(dev_priv)->gen >= 9)
2180                 return 256 * 1024;
2181         else if (IS_BROADWATER(dev_priv) || IS_CRESTLINE(dev_priv) ||
2182                  IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
2183                 return 128 * 1024;
2184         else if (INTEL_INFO(dev_priv)->gen >= 4)
2185                 return 4 * 1024;
2186         else
2187                 return 0;
2188 }
2189
2190 static unsigned int intel_surf_alignment(const struct drm_i915_private *dev_priv,
2191                                          uint64_t fb_modifier)
2192 {
2193         switch (fb_modifier) {
2194         case DRM_FORMAT_MOD_NONE:
2195                 return intel_linear_alignment(dev_priv);
2196         case I915_FORMAT_MOD_X_TILED:
2197                 if (INTEL_INFO(dev_priv)->gen >= 9)
2198                         return 256 * 1024;
2199                 return 0;
2200         case I915_FORMAT_MOD_Y_TILED:
2201         case I915_FORMAT_MOD_Yf_TILED:
2202                 return 1 * 1024 * 1024;
2203         default:
2204                 MISSING_CASE(fb_modifier);
2205                 return 0;
2206         }
2207 }
2208
2209 int
2210 intel_pin_and_fence_fb_obj(struct drm_framebuffer *fb,
2211                            unsigned int rotation)
2212 {
2213         struct drm_device *dev = fb->dev;
2214         struct drm_i915_private *dev_priv = to_i915(dev);
2215         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
2216         struct i915_ggtt_view view;
2217         u32 alignment;
2218         int ret;
2219
2220         WARN_ON(!mutex_is_locked(&dev->struct_mutex));
2221
2222         alignment = intel_surf_alignment(dev_priv, fb->modifier[0]);
2223
2224         intel_fill_fb_ggtt_view(&view, fb, rotation);
2225
2226         /* Note that the w/a also requires 64 PTE of padding following the
2227          * bo. We currently fill all unused PTE with the shadow page and so
2228          * we should always have valid PTE following the scanout preventing
2229          * the VT-d warning.
2230          */
2231         if (intel_scanout_needs_vtd_wa(dev_priv) && alignment < 256 * 1024)
2232                 alignment = 256 * 1024;
2233
2234         /*
2235          * Global gtt pte registers are special registers which actually forward
2236          * writes to a chunk of system memory. Which means that there is no risk
2237          * that the register values disappear as soon as we call
2238          * intel_runtime_pm_put(), so it is correct to wrap only the
2239          * pin/unpin/fence and not more.
2240          */
2241         intel_runtime_pm_get(dev_priv);
2242
2243         ret = i915_gem_object_pin_to_display_plane(obj, alignment,
2244                                                    &view);
2245         if (ret)
2246                 goto err_pm;
2247
2248         /* Install a fence for tiled scan-out. Pre-i965 always needs a
2249          * fence, whereas 965+ only requires a fence if using
2250          * framebuffer compression.  For simplicity, we always install
2251          * a fence as the cost is not that onerous.
2252          */
2253         if (view.type == I915_GGTT_VIEW_NORMAL) {
2254                 ret = i915_gem_object_get_fence(obj);
2255                 if (ret == -EDEADLK) {
2256                         /*
2257                          * -EDEADLK means there are no free fences
2258                          * no pending flips.
2259                          *
2260                          * This is propagated to atomic, but it uses
2261                          * -EDEADLK to force a locking recovery, so
2262                          * change the returned error to -EBUSY.
2263                          */
2264                         ret = -EBUSY;
2265                         goto err_unpin;
2266                 } else if (ret)
2267                         goto err_unpin;
2268
2269                 i915_gem_object_pin_fence(obj);
2270         }
2271
2272         intel_runtime_pm_put(dev_priv);
2273         return 0;
2274
2275 err_unpin:
2276         i915_gem_object_unpin_from_display_plane(obj, &view);
2277 err_pm:
2278         intel_runtime_pm_put(dev_priv);
2279         return ret;
2280 }
2281
2282 void intel_unpin_fb_obj(struct drm_framebuffer *fb, unsigned int rotation)
2283 {
2284         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
2285         struct i915_ggtt_view view;
2286
2287         WARN_ON(!mutex_is_locked(&obj->base.dev->struct_mutex));
2288
2289         intel_fill_fb_ggtt_view(&view, fb, rotation);
2290
2291         if (view.type == I915_GGTT_VIEW_NORMAL)
2292                 i915_gem_object_unpin_fence(obj);
2293
2294         i915_gem_object_unpin_from_display_plane(obj, &view);
2295 }
2296
2297 /*
2298  * Adjust the tile offset by moving the difference into
2299  * the x/y offsets.
2300  *
2301  * Input tile dimensions and pitch must already be
2302  * rotated to match x and y, and in pixel units.
2303  */
2304 static u32 intel_adjust_tile_offset(int *x, int *y,
2305                                     unsigned int tile_width,
2306                                     unsigned int tile_height,
2307                                     unsigned int tile_size,
2308                                     unsigned int pitch_tiles,
2309                                     u32 old_offset,
2310                                     u32 new_offset)
2311 {
2312         unsigned int tiles;
2313
2314         WARN_ON(old_offset & (tile_size - 1));
2315         WARN_ON(new_offset & (tile_size - 1));
2316         WARN_ON(new_offset > old_offset);
2317
2318         tiles = (old_offset - new_offset) / tile_size;
2319
2320         *y += tiles / pitch_tiles * tile_height;
2321         *x += tiles % pitch_tiles * tile_width;
2322
2323         return new_offset;
2324 }
2325
2326 /*
2327  * Computes the linear offset to the base tile and adjusts
2328  * x, y. bytes per pixel is assumed to be a power-of-two.
2329  *
2330  * In the 90/270 rotated case, x and y are assumed
2331  * to be already rotated to match the rotated GTT view, and
2332  * pitch is the tile_height aligned framebuffer height.
2333  */
2334 u32 intel_compute_tile_offset(int *x, int *y,
2335                               const struct drm_framebuffer *fb, int plane,
2336                               unsigned int pitch,
2337                               unsigned int rotation)
2338 {
2339         const struct drm_i915_private *dev_priv = to_i915(fb->dev);
2340         uint64_t fb_modifier = fb->modifier[plane];
2341         unsigned int cpp = drm_format_plane_cpp(fb->pixel_format, plane);
2342         u32 offset, offset_aligned, alignment;
2343
2344         alignment = intel_surf_alignment(dev_priv, fb_modifier);
2345         if (alignment)
2346                 alignment--;
2347
2348         if (fb_modifier != DRM_FORMAT_MOD_NONE) {
2349                 unsigned int tile_size, tile_width, tile_height;
2350                 unsigned int tile_rows, tiles, pitch_tiles;
2351
2352                 tile_size = intel_tile_size(dev_priv);
2353                 intel_tile_dims(dev_priv, &tile_width, &tile_height,
2354                                 fb_modifier, cpp);
2355
2356                 if (intel_rotation_90_or_270(rotation)) {
2357                         pitch_tiles = pitch / tile_height;
2358                         swap(tile_width, tile_height);
2359                 } else {
2360                         pitch_tiles = pitch / (tile_width * cpp);
2361                 }
2362
2363                 tile_rows = *y / tile_height;
2364                 *y %= tile_height;
2365
2366                 tiles = *x / tile_width;
2367                 *x %= tile_width;
2368
2369                 offset = (tile_rows * pitch_tiles + tiles) * tile_size;
2370                 offset_aligned = offset & ~alignment;
2371
2372                 intel_adjust_tile_offset(x, y, tile_width, tile_height,
2373                                          tile_size, pitch_tiles,
2374                                          offset, offset_aligned);
2375         } else {
2376                 offset = *y * pitch + *x * cpp;
2377                 offset_aligned = offset & ~alignment;
2378
2379                 *y = (offset & alignment) / pitch;
2380                 *x = ((offset & alignment) - *y * pitch) / cpp;
2381         }
2382
2383         return offset_aligned;
2384 }
2385
2386 static int i9xx_format_to_fourcc(int format)
2387 {
2388         switch (format) {
2389         case DISPPLANE_8BPP:
2390                 return DRM_FORMAT_C8;
2391         case DISPPLANE_BGRX555:
2392                 return DRM_FORMAT_XRGB1555;
2393         case DISPPLANE_BGRX565:
2394                 return DRM_FORMAT_RGB565;
2395         default:
2396         case DISPPLANE_BGRX888:
2397                 return DRM_FORMAT_XRGB8888;
2398         case DISPPLANE_RGBX888:
2399                 return DRM_FORMAT_XBGR8888;
2400         case DISPPLANE_BGRX101010:
2401                 return DRM_FORMAT_XRGB2101010;
2402         case DISPPLANE_RGBX101010:
2403                 return DRM_FORMAT_XBGR2101010;
2404         }
2405 }
2406
2407 static int skl_format_to_fourcc(int format, bool rgb_order, bool alpha)
2408 {
2409         switch (format) {
2410         case PLANE_CTL_FORMAT_RGB_565:
2411                 return DRM_FORMAT_RGB565;
2412         default:
2413         case PLANE_CTL_FORMAT_XRGB_8888:
2414                 if (rgb_order) {
2415                         if (alpha)
2416                                 return DRM_FORMAT_ABGR8888;
2417                         else
2418                                 return DRM_FORMAT_XBGR8888;
2419                 } else {
2420                         if (alpha)
2421                                 return DRM_FORMAT_ARGB8888;
2422                         else
2423                                 return DRM_FORMAT_XRGB8888;
2424                 }
2425         case PLANE_CTL_FORMAT_XRGB_2101010:
2426                 if (rgb_order)
2427                         return DRM_FORMAT_XBGR2101010;
2428                 else
2429                         return DRM_FORMAT_XRGB2101010;
2430         }
2431 }
2432
2433 static bool
2434 intel_alloc_initial_plane_obj(struct intel_crtc *crtc,
2435                               struct intel_initial_plane_config *plane_config)
2436 {
2437         struct drm_device *dev = crtc->base.dev;
2438         struct drm_i915_private *dev_priv = to_i915(dev);
2439         struct i915_ggtt *ggtt = &dev_priv->ggtt;
2440         struct drm_i915_gem_object *obj = NULL;
2441         struct drm_mode_fb_cmd2 mode_cmd = { 0 };
2442         struct drm_framebuffer *fb = &plane_config->fb->base;
2443         u32 base_aligned = round_down(plane_config->base, PAGE_SIZE);
2444         u32 size_aligned = round_up(plane_config->base + plane_config->size,
2445                                     PAGE_SIZE);
2446
2447         size_aligned -= base_aligned;
2448
2449         if (plane_config->size == 0)
2450                 return false;
2451
2452         /* If the FB is too big, just don't use it since fbdev is not very
2453          * important and we should probably use that space with FBC or other
2454          * features. */
2455         if (size_aligned * 2 > ggtt->stolen_usable_size)
2456                 return false;
2457
2458         mutex_lock(&dev->struct_mutex);
2459
2460         obj = i915_gem_object_create_stolen_for_preallocated(dev,
2461                                                              base_aligned,
2462                                                              base_aligned,
2463                                                              size_aligned);
2464         if (!obj) {
2465                 mutex_unlock(&dev->struct_mutex);
2466                 return false;
2467         }
2468
2469         if (plane_config->tiling == I915_TILING_X)
2470                 obj->tiling_and_stride = fb->pitches[0] | I915_TILING_X;
2471
2472         mode_cmd.pixel_format = fb->pixel_format;
2473         mode_cmd.width = fb->width;
2474         mode_cmd.height = fb->height;
2475         mode_cmd.pitches[0] = fb->pitches[0];
2476         mode_cmd.modifier[0] = fb->modifier[0];
2477         mode_cmd.flags = DRM_MODE_FB_MODIFIERS;
2478
2479         if (intel_framebuffer_init(dev, to_intel_framebuffer(fb),
2480                                    &mode_cmd, obj)) {
2481                 DRM_DEBUG_KMS("intel fb init failed\n");
2482                 goto out_unref_obj;
2483         }
2484
2485         mutex_unlock(&dev->struct_mutex);
2486
2487         DRM_DEBUG_KMS("initial plane fb obj %p\n", obj);
2488         return true;
2489
2490 out_unref_obj:
2491         i915_gem_object_put(obj);
2492         mutex_unlock(&dev->struct_mutex);
2493         return false;
2494 }
2495
2496 /* Update plane->state->fb to match plane->fb after driver-internal updates */
2497 static void
2498 update_state_fb(struct drm_plane *plane)
2499 {
2500         if (plane->fb == plane->state->fb)
2501                 return;
2502
2503         if (plane->state->fb)
2504                 drm_framebuffer_unreference(plane->state->fb);
2505         plane->state->fb = plane->fb;
2506         if (plane->state->fb)
2507                 drm_framebuffer_reference(plane->state->fb);
2508 }
2509
2510 static void
2511 intel_find_initial_plane_obj(struct intel_crtc *intel_crtc,
2512                              struct intel_initial_plane_config *plane_config)
2513 {
2514         struct drm_device *dev = intel_crtc->base.dev;
2515         struct drm_i915_private *dev_priv = to_i915(dev);
2516         struct drm_crtc *c;
2517         struct intel_crtc *i;
2518         struct drm_i915_gem_object *obj;
2519         struct drm_plane *primary = intel_crtc->base.primary;
2520         struct drm_plane_state *plane_state = primary->state;
2521         struct drm_crtc_state *crtc_state = intel_crtc->base.state;
2522         struct intel_plane *intel_plane = to_intel_plane(primary);
2523         struct intel_plane_state *intel_state =
2524                 to_intel_plane_state(plane_state);
2525         struct drm_framebuffer *fb;
2526
2527         if (!plane_config->fb)
2528                 return;
2529
2530         if (intel_alloc_initial_plane_obj(intel_crtc, plane_config)) {
2531                 fb = &plane_config->fb->base;
2532                 goto valid_fb;
2533         }
2534
2535         kfree(plane_config->fb);
2536
2537         /*
2538          * Failed to alloc the obj, check to see if we should share
2539          * an fb with another CRTC instead
2540          */
2541         for_each_crtc(dev, c) {
2542                 i = to_intel_crtc(c);
2543
2544                 if (c == &intel_crtc->base)
2545                         continue;
2546
2547                 if (!i->active)
2548                         continue;
2549
2550                 fb = c->primary->fb;
2551                 if (!fb)
2552                         continue;
2553
2554                 obj = intel_fb_obj(fb);
2555                 if (i915_gem_obj_ggtt_offset(obj) == plane_config->base) {
2556                         drm_framebuffer_reference(fb);
2557                         goto valid_fb;
2558                 }
2559         }
2560
2561         /*
2562          * We've failed to reconstruct the BIOS FB.  Current display state
2563          * indicates that the primary plane is visible, but has a NULL FB,
2564          * which will lead to problems later if we don't fix it up.  The
2565          * simplest solution is to just disable the primary plane now and
2566          * pretend the BIOS never had it enabled.
2567          */
2568         to_intel_plane_state(plane_state)->base.visible = false;
2569         crtc_state->plane_mask &= ~(1 << drm_plane_index(primary));
2570         intel_pre_disable_primary_noatomic(&intel_crtc->base);
2571         intel_plane->disable_plane(primary, &intel_crtc->base);
2572
2573         return;
2574
2575 valid_fb:
2576         plane_state->src_x = 0;
2577         plane_state->src_y = 0;
2578         plane_state->src_w = fb->width << 16;
2579         plane_state->src_h = fb->height << 16;
2580
2581         plane_state->crtc_x = 0;
2582         plane_state->crtc_y = 0;
2583         plane_state->crtc_w = fb->width;
2584         plane_state->crtc_h = fb->height;
2585
2586         intel_state->base.src.x1 = plane_state->src_x;
2587         intel_state->base.src.y1 = plane_state->src_y;
2588         intel_state->base.src.x2 = plane_state->src_x + plane_state->src_w;
2589         intel_state->base.src.y2 = plane_state->src_y + plane_state->src_h;
2590         intel_state->base.dst.x1 = plane_state->crtc_x;
2591         intel_state->base.dst.y1 = plane_state->crtc_y;
2592         intel_state->base.dst.x2 = plane_state->crtc_x + plane_state->crtc_w;
2593         intel_state->base.dst.y2 = plane_state->crtc_y + plane_state->crtc_h;
2594
2595         obj = intel_fb_obj(fb);
2596         if (i915_gem_object_is_tiled(obj))
2597                 dev_priv->preserve_bios_swizzle = true;
2598
2599         drm_framebuffer_reference(fb);
2600         primary->fb = primary->state->fb = fb;
2601         primary->crtc = primary->state->crtc = &intel_crtc->base;
2602         intel_crtc->base.state->plane_mask |= (1 << drm_plane_index(primary));
2603         atomic_or(to_intel_plane(primary)->frontbuffer_bit,
2604                   &obj->frontbuffer_bits);
2605 }
2606
2607 static void i9xx_update_primary_plane(struct drm_plane *primary,
2608                                       const struct intel_crtc_state *crtc_state,
2609                                       const struct intel_plane_state *plane_state)
2610 {
2611         struct drm_device *dev = primary->dev;
2612         struct drm_i915_private *dev_priv = to_i915(dev);
2613         struct intel_crtc *intel_crtc = to_intel_crtc(crtc_state->base.crtc);
2614         struct drm_framebuffer *fb = plane_state->base.fb;
2615         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
2616         int plane = intel_crtc->plane;
2617         u32 linear_offset;
2618         u32 dspcntr;
2619         i915_reg_t reg = DSPCNTR(plane);
2620         unsigned int rotation = plane_state->base.rotation;
2621         int cpp = drm_format_plane_cpp(fb->pixel_format, 0);
2622         int x = plane_state->base.src.x1 >> 16;
2623         int y = plane_state->base.src.y1 >> 16;
2624
2625         dspcntr = DISPPLANE_GAMMA_ENABLE;
2626
2627         dspcntr |= DISPLAY_PLANE_ENABLE;
2628
2629         if (INTEL_INFO(dev)->gen < 4) {
2630                 if (intel_crtc->pipe == PIPE_B)
2631                         dspcntr |= DISPPLANE_SEL_PIPE_B;
2632
2633                 /* pipesrc and dspsize control the size that is scaled from,
2634                  * which should always be the user's requested size.
2635                  */
2636                 I915_WRITE(DSPSIZE(plane),
2637                            ((crtc_state->pipe_src_h - 1) << 16) |
2638                            (crtc_state->pipe_src_w - 1));
2639                 I915_WRITE(DSPPOS(plane), 0);
2640         } else if (IS_CHERRYVIEW(dev) && plane == PLANE_B) {
2641                 I915_WRITE(PRIMSIZE(plane),
2642                            ((crtc_state->pipe_src_h - 1) << 16) |
2643                            (crtc_state->pipe_src_w - 1));
2644                 I915_WRITE(PRIMPOS(plane), 0);
2645                 I915_WRITE(PRIMCNSTALPHA(plane), 0);
2646         }
2647
2648         switch (fb->pixel_format) {
2649         case DRM_FORMAT_C8:
2650                 dspcntr |= DISPPLANE_8BPP;
2651                 break;
2652         case DRM_FORMAT_XRGB1555:
2653                 dspcntr |= DISPPLANE_BGRX555;
2654                 break;
2655         case DRM_FORMAT_RGB565:
2656                 dspcntr |= DISPPLANE_BGRX565;
2657                 break;
2658         case DRM_FORMAT_XRGB8888:
2659                 dspcntr |= DISPPLANE_BGRX888;
2660                 break;
2661         case DRM_FORMAT_XBGR8888:
2662                 dspcntr |= DISPPLANE_RGBX888;
2663                 break;
2664         case DRM_FORMAT_XRGB2101010:
2665                 dspcntr |= DISPPLANE_BGRX101010;
2666                 break;
2667         case DRM_FORMAT_XBGR2101010:
2668                 dspcntr |= DISPPLANE_RGBX101010;
2669                 break;
2670         default:
2671                 BUG();
2672         }
2673
2674         if (INTEL_INFO(dev)->gen >= 4 && i915_gem_object_is_tiled(obj))
2675                 dspcntr |= DISPPLANE_TILED;
2676
2677         if (IS_G4X(dev))
2678                 dspcntr |= DISPPLANE_TRICKLE_FEED_DISABLE;
2679
2680         linear_offset = y * fb->pitches[0] + x * cpp;
2681
2682         if (INTEL_INFO(dev)->gen >= 4) {
2683                 intel_crtc->dspaddr_offset =
2684                         intel_compute_tile_offset(&x, &y, fb, 0,
2685                                                   fb->pitches[0], rotation);
2686                 linear_offset -= intel_crtc->dspaddr_offset;
2687         } else {
2688                 intel_crtc->dspaddr_offset = linear_offset;
2689         }
2690
2691         if (rotation == DRM_ROTATE_180) {
2692                 dspcntr |= DISPPLANE_ROTATE_180;
2693
2694                 x += (crtc_state->pipe_src_w - 1);
2695                 y += (crtc_state->pipe_src_h - 1);
2696
2697                 /* Finding the last pixel of the last line of the display
2698                 data and adding to linear_offset*/
2699                 linear_offset +=
2700                         (crtc_state->pipe_src_h - 1) * fb->pitches[0] +
2701                         (crtc_state->pipe_src_w - 1) * cpp;
2702         }
2703
2704         intel_crtc->adjusted_x = x;
2705         intel_crtc->adjusted_y = y;
2706
2707         I915_WRITE(reg, dspcntr);
2708
2709         I915_WRITE(DSPSTRIDE(plane), fb->pitches[0]);
2710         if (INTEL_INFO(dev)->gen >= 4) {
2711                 I915_WRITE(DSPSURF(plane),
2712                            i915_gem_obj_ggtt_offset(obj) + intel_crtc->dspaddr_offset);
2713                 I915_WRITE(DSPTILEOFF(plane), (y << 16) | x);
2714                 I915_WRITE(DSPLINOFF(plane), linear_offset);
2715         } else
2716                 I915_WRITE(DSPADDR(plane), i915_gem_obj_ggtt_offset(obj) + linear_offset);
2717         POSTING_READ(reg);
2718 }
2719
2720 static void i9xx_disable_primary_plane(struct drm_plane *primary,
2721                                        struct drm_crtc *crtc)
2722 {
2723         struct drm_device *dev = crtc->dev;
2724         struct drm_i915_private *dev_priv = to_i915(dev);
2725         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
2726         int plane = intel_crtc->plane;
2727
2728         I915_WRITE(DSPCNTR(plane), 0);
2729         if (INTEL_INFO(dev_priv)->gen >= 4)
2730                 I915_WRITE(DSPSURF(plane), 0);
2731         else
2732                 I915_WRITE(DSPADDR(plane), 0);
2733         POSTING_READ(DSPCNTR(plane));
2734 }
2735
2736 static void ironlake_update_primary_plane(struct drm_plane *primary,
2737                                           const struct intel_crtc_state *crtc_state,
2738                                           const struct intel_plane_state *plane_state)
2739 {
2740         struct drm_device *dev = primary->dev;
2741         struct drm_i915_private *dev_priv = to_i915(dev);
2742         struct intel_crtc *intel_crtc = to_intel_crtc(crtc_state->base.crtc);
2743         struct drm_framebuffer *fb = plane_state->base.fb;
2744         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
2745         int plane = intel_crtc->plane;
2746         u32 linear_offset;
2747         u32 dspcntr;
2748         i915_reg_t reg = DSPCNTR(plane);
2749         unsigned int rotation = plane_state->base.rotation;
2750         int cpp = drm_format_plane_cpp(fb->pixel_format, 0);
2751         int x = plane_state->base.src.x1 >> 16;
2752         int y = plane_state->base.src.y1 >> 16;
2753
2754         dspcntr = DISPPLANE_GAMMA_ENABLE;
2755         dspcntr |= DISPLAY_PLANE_ENABLE;
2756
2757         if (IS_HASWELL(dev) || IS_BROADWELL(dev))
2758                 dspcntr |= DISPPLANE_PIPE_CSC_ENABLE;
2759
2760         switch (fb->pixel_format) {
2761         case DRM_FORMAT_C8:
2762                 dspcntr |= DISPPLANE_8BPP;
2763                 break;
2764         case DRM_FORMAT_RGB565:
2765                 dspcntr |= DISPPLANE_BGRX565;
2766                 break;
2767         case DRM_FORMAT_XRGB8888:
2768                 dspcntr |= DISPPLANE_BGRX888;
2769                 break;
2770         case DRM_FORMAT_XBGR8888:
2771                 dspcntr |= DISPPLANE_RGBX888;
2772                 break;
2773         case DRM_FORMAT_XRGB2101010:
2774                 dspcntr |= DISPPLANE_BGRX101010;
2775                 break;
2776         case DRM_FORMAT_XBGR2101010:
2777                 dspcntr |= DISPPLANE_RGBX101010;
2778                 break;
2779         default:
2780                 BUG();
2781         }
2782
2783         if (i915_gem_object_is_tiled(obj))
2784                 dspcntr |= DISPPLANE_TILED;
2785
2786         if (!IS_HASWELL(dev) && !IS_BROADWELL(dev))
2787                 dspcntr |= DISPPLANE_TRICKLE_FEED_DISABLE;
2788
2789         linear_offset = y * fb->pitches[0] + x * cpp;
2790         intel_crtc->dspaddr_offset =
2791                 intel_compute_tile_offset(&x, &y, fb, 0,
2792                                           fb->pitches[0], rotation);
2793         linear_offset -= intel_crtc->dspaddr_offset;
2794         if (rotation == DRM_ROTATE_180) {
2795                 dspcntr |= DISPPLANE_ROTATE_180;
2796
2797                 if (!IS_HASWELL(dev) && !IS_BROADWELL(dev)) {
2798                         x += (crtc_state->pipe_src_w - 1);
2799                         y += (crtc_state->pipe_src_h - 1);
2800
2801                         /* Finding the last pixel of the last line of the display
2802                         data and adding to linear_offset*/
2803                         linear_offset +=
2804                                 (crtc_state->pipe_src_h - 1) * fb->pitches[0] +
2805                                 (crtc_state->pipe_src_w - 1) * cpp;
2806                 }
2807         }
2808
2809         intel_crtc->adjusted_x = x;
2810         intel_crtc->adjusted_y = y;
2811
2812         I915_WRITE(reg, dspcntr);
2813
2814         I915_WRITE(DSPSTRIDE(plane), fb->pitches[0]);
2815         I915_WRITE(DSPSURF(plane),
2816                    i915_gem_obj_ggtt_offset(obj) + intel_crtc->dspaddr_offset);
2817         if (IS_HASWELL(dev) || IS_BROADWELL(dev)) {
2818                 I915_WRITE(DSPOFFSET(plane), (y << 16) | x);
2819         } else {
2820                 I915_WRITE(DSPTILEOFF(plane), (y << 16) | x);
2821                 I915_WRITE(DSPLINOFF(plane), linear_offset);
2822         }
2823         POSTING_READ(reg);
2824 }
2825
2826 u32 intel_fb_stride_alignment(const struct drm_i915_private *dev_priv,
2827                               uint64_t fb_modifier, uint32_t pixel_format)
2828 {
2829         if (fb_modifier == DRM_FORMAT_MOD_NONE) {
2830                 return 64;
2831         } else {
2832                 int cpp = drm_format_plane_cpp(pixel_format, 0);
2833
2834                 return intel_tile_width_bytes(dev_priv, fb_modifier, cpp);
2835         }
2836 }
2837
2838 u32 intel_plane_obj_offset(struct intel_plane *intel_plane,
2839                            struct drm_i915_gem_object *obj,
2840                            unsigned int plane)
2841 {
2842         struct i915_ggtt_view view;
2843         struct i915_vma *vma;
2844         u64 offset;
2845
2846         intel_fill_fb_ggtt_view(&view, intel_plane->base.state->fb,
2847                                 intel_plane->base.state->rotation);
2848
2849         vma = i915_gem_obj_to_ggtt_view(obj, &view);
2850         if (WARN(!vma, "ggtt vma for display object not found! (view=%u)\n",
2851                 view.type))
2852                 return -1;
2853
2854         offset = vma->node.start;
2855
2856         if (plane == 1) {
2857                 offset += vma->ggtt_view.params.rotated.uv_start_page *
2858                           PAGE_SIZE;
2859         }
2860
2861         WARN_ON(upper_32_bits(offset));
2862
2863         return lower_32_bits(offset);
2864 }
2865
2866 static void skl_detach_scaler(struct intel_crtc *intel_crtc, int id)
2867 {
2868         struct drm_device *dev = intel_crtc->base.dev;
2869         struct drm_i915_private *dev_priv = to_i915(dev);
2870
2871         I915_WRITE(SKL_PS_CTRL(intel_crtc->pipe, id), 0);
2872         I915_WRITE(SKL_PS_WIN_POS(intel_crtc->pipe, id), 0);
2873         I915_WRITE(SKL_PS_WIN_SZ(intel_crtc->pipe, id), 0);
2874 }
2875
2876 /*
2877  * This function detaches (aka. unbinds) unused scalers in hardware
2878  */
2879 static void skl_detach_scalers(struct intel_crtc *intel_crtc)
2880 {
2881         struct intel_crtc_scaler_state *scaler_state;
2882         int i;
2883
2884         scaler_state = &intel_crtc->config->scaler_state;
2885
2886         /* loop through and disable scalers that aren't in use */
2887         for (i = 0; i < intel_crtc->num_scalers; i++) {
2888                 if (!scaler_state->scalers[i].in_use)
2889                         skl_detach_scaler(intel_crtc, i);
2890         }
2891 }
2892
2893 u32 skl_plane_ctl_format(uint32_t pixel_format)
2894 {
2895         switch (pixel_format) {
2896         case DRM_FORMAT_C8:
2897                 return PLANE_CTL_FORMAT_INDEXED;
2898         case DRM_FORMAT_RGB565:
2899                 return PLANE_CTL_FORMAT_RGB_565;
2900         case DRM_FORMAT_XBGR8888:
2901                 return PLANE_CTL_FORMAT_XRGB_8888 | PLANE_CTL_ORDER_RGBX;
2902         case DRM_FORMAT_XRGB8888:
2903                 return PLANE_CTL_FORMAT_XRGB_8888;
2904         /*
2905          * XXX: For ARBG/ABGR formats we default to expecting scanout buffers
2906          * to be already pre-multiplied. We need to add a knob (or a different
2907          * DRM_FORMAT) for user-space to configure that.
2908          */
2909         case DRM_FORMAT_ABGR8888:
2910                 return PLANE_CTL_FORMAT_XRGB_8888 | PLANE_CTL_ORDER_RGBX |
2911                         PLANE_CTL_ALPHA_SW_PREMULTIPLY;
2912         case DRM_FORMAT_ARGB8888:
2913                 return PLANE_CTL_FORMAT_XRGB_8888 |
2914                         PLANE_CTL_ALPHA_SW_PREMULTIPLY;
2915         case DRM_FORMAT_XRGB2101010:
2916                 return PLANE_CTL_FORMAT_XRGB_2101010;
2917         case DRM_FORMAT_XBGR2101010:
2918                 return PLANE_CTL_ORDER_RGBX | PLANE_CTL_FORMAT_XRGB_2101010;
2919         case DRM_FORMAT_YUYV:
2920                 return PLANE_CTL_FORMAT_YUV422 | PLANE_CTL_YUV422_YUYV;
2921         case DRM_FORMAT_YVYU:
2922                 return PLANE_CTL_FORMAT_YUV422 | PLANE_CTL_YUV422_YVYU;
2923         case DRM_FORMAT_UYVY:
2924                 return PLANE_CTL_FORMAT_YUV422 | PLANE_CTL_YUV422_UYVY;
2925         case DRM_FORMAT_VYUY:
2926                 return PLANE_CTL_FORMAT_YUV422 | PLANE_CTL_YUV422_VYUY;
2927         default:
2928                 MISSING_CASE(pixel_format);
2929         }
2930
2931         return 0;
2932 }
2933
2934 u32 skl_plane_ctl_tiling(uint64_t fb_modifier)
2935 {
2936         switch (fb_modifier) {
2937         case DRM_FORMAT_MOD_NONE:
2938                 break;
2939         case I915_FORMAT_MOD_X_TILED:
2940                 return PLANE_CTL_TILED_X;
2941         case I915_FORMAT_MOD_Y_TILED:
2942                 return PLANE_CTL_TILED_Y;
2943         case I915_FORMAT_MOD_Yf_TILED:
2944                 return PLANE_CTL_TILED_YF;
2945         default:
2946                 MISSING_CASE(fb_modifier);
2947         }
2948
2949         return 0;
2950 }
2951
2952 u32 skl_plane_ctl_rotation(unsigned int rotation)
2953 {
2954         switch (rotation) {
2955         case DRM_ROTATE_0:
2956                 break;
2957         /*
2958          * DRM_ROTATE_ is counter clockwise to stay compatible with Xrandr
2959          * while i915 HW rotation is clockwise, thats why this swapping.
2960          */
2961         case DRM_ROTATE_90:
2962                 return PLANE_CTL_ROTATE_270;
2963         case DRM_ROTATE_180:
2964                 return PLANE_CTL_ROTATE_180;
2965         case DRM_ROTATE_270:
2966                 return PLANE_CTL_ROTATE_90;
2967         default:
2968                 MISSING_CASE(rotation);
2969         }
2970
2971         return 0;
2972 }
2973
2974 static void skylake_update_primary_plane(struct drm_plane *plane,
2975                                          const struct intel_crtc_state *crtc_state,
2976                                          const struct intel_plane_state *plane_state)
2977 {
2978         struct drm_device *dev = plane->dev;
2979         struct drm_i915_private *dev_priv = to_i915(dev);
2980         struct intel_crtc *intel_crtc = to_intel_crtc(crtc_state->base.crtc);
2981         struct drm_framebuffer *fb = plane_state->base.fb;
2982         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
2983         int pipe = intel_crtc->pipe;
2984         u32 plane_ctl, stride_div, stride;
2985         u32 tile_height, plane_offset, plane_size;
2986         unsigned int rotation = plane_state->base.rotation;
2987         int x_offset, y_offset;
2988         u32 surf_addr;
2989         int scaler_id = plane_state->scaler_id;
2990         int src_x = plane_state->base.src.x1 >> 16;
2991         int src_y = plane_state->base.src.y1 >> 16;
2992         int src_w = drm_rect_width(&plane_state->base.src) >> 16;
2993         int src_h = drm_rect_height(&plane_state->base.src) >> 16;
2994         int dst_x = plane_state->base.dst.x1;
2995         int dst_y = plane_state->base.dst.y1;
2996         int dst_w = drm_rect_width(&plane_state->base.dst);
2997         int dst_h = drm_rect_height(&plane_state->base.dst);
2998
2999         plane_ctl = PLANE_CTL_ENABLE |
3000                     PLANE_CTL_PIPE_GAMMA_ENABLE |
3001                     PLANE_CTL_PIPE_CSC_ENABLE;
3002
3003         plane_ctl |= skl_plane_ctl_format(fb->pixel_format);
3004         plane_ctl |= skl_plane_ctl_tiling(fb->modifier[0]);
3005         plane_ctl |= PLANE_CTL_PLANE_GAMMA_DISABLE;
3006         plane_ctl |= skl_plane_ctl_rotation(rotation);
3007
3008         stride_div = intel_fb_stride_alignment(dev_priv, fb->modifier[0],
3009                                                fb->pixel_format);
3010         surf_addr = intel_plane_obj_offset(to_intel_plane(plane), obj, 0);
3011
3012         WARN_ON(drm_rect_width(&plane_state->base.src) == 0);
3013
3014         if (intel_rotation_90_or_270(rotation)) {
3015                 int cpp = drm_format_plane_cpp(fb->pixel_format, 0);
3016
3017                 /* stride = Surface height in tiles */
3018                 tile_height = intel_tile_height(dev_priv, fb->modifier[0], cpp);
3019                 stride = DIV_ROUND_UP(fb->height, tile_height);
3020                 x_offset = stride * tile_height - src_y - src_h;
3021                 y_offset = src_x;
3022                 plane_size = (src_w - 1) << 16 | (src_h - 1);
3023         } else {
3024                 stride = fb->pitches[0] / stride_div;
3025                 x_offset = src_x;
3026                 y_offset = src_y;
3027                 plane_size = (src_h - 1) << 16 | (src_w - 1);
3028         }
3029         plane_offset = y_offset << 16 | x_offset;
3030
3031         intel_crtc->adjusted_x = x_offset;
3032         intel_crtc->adjusted_y = y_offset;
3033
3034         I915_WRITE(PLANE_CTL(pipe, 0), plane_ctl);
3035         I915_WRITE(PLANE_OFFSET(pipe, 0), plane_offset);
3036         I915_WRITE(PLANE_SIZE(pipe, 0), plane_size);
3037         I915_WRITE(PLANE_STRIDE(pipe, 0), stride);
3038
3039         if (scaler_id >= 0) {
3040                 uint32_t ps_ctrl = 0;
3041
3042                 WARN_ON(!dst_w || !dst_h);
3043                 ps_ctrl = PS_SCALER_EN | PS_PLANE_SEL(0) |
3044                         crtc_state->scaler_state.scalers[scaler_id].mode;
3045                 I915_WRITE(SKL_PS_CTRL(pipe, scaler_id), ps_ctrl);
3046                 I915_WRITE(SKL_PS_PWR_GATE(pipe, scaler_id), 0);
3047                 I915_WRITE(SKL_PS_WIN_POS(pipe, scaler_id), (dst_x << 16) | dst_y);
3048                 I915_WRITE(SKL_PS_WIN_SZ(pipe, scaler_id), (dst_w << 16) | dst_h);
3049                 I915_WRITE(PLANE_POS(pipe, 0), 0);
3050         } else {
3051                 I915_WRITE(PLANE_POS(pipe, 0), (dst_y << 16) | dst_x);
3052         }
3053
3054         I915_WRITE(PLANE_SURF(pipe, 0), surf_addr);
3055
3056         POSTING_READ(PLANE_SURF(pipe, 0));
3057 }
3058
3059 static void skylake_disable_primary_plane(struct drm_plane *primary,
3060                                           struct drm_crtc *crtc)
3061 {
3062         struct drm_device *dev = crtc->dev;
3063         struct drm_i915_private *dev_priv = to_i915(dev);
3064         int pipe = to_intel_crtc(crtc)->pipe;
3065
3066         I915_WRITE(PLANE_CTL(pipe, 0), 0);
3067         I915_WRITE(PLANE_SURF(pipe, 0), 0);
3068         POSTING_READ(PLANE_SURF(pipe, 0));
3069 }
3070
3071 /* Assume fb object is pinned & idle & fenced and just update base pointers */
3072 static int
3073 intel_pipe_set_base_atomic(struct drm_crtc *crtc, struct drm_framebuffer *fb,
3074                            int x, int y, enum mode_set_atomic state)
3075 {
3076         /* Support for kgdboc is disabled, this needs a major rework. */
3077         DRM_ERROR("legacy panic handler not supported any more.\n");
3078
3079         return -ENODEV;
3080 }
3081
3082 static void intel_complete_page_flips(struct drm_i915_private *dev_priv)
3083 {
3084         struct intel_crtc *crtc;
3085
3086         for_each_intel_crtc(&dev_priv->drm, crtc)
3087                 intel_finish_page_flip_cs(dev_priv, crtc->pipe);
3088 }
3089
3090 static void intel_update_primary_planes(struct drm_device *dev)
3091 {
3092         struct drm_crtc *crtc;
3093
3094         for_each_crtc(dev, crtc) {
3095                 struct intel_plane *plane = to_intel_plane(crtc->primary);
3096                 struct intel_plane_state *plane_state;
3097
3098                 drm_modeset_lock_crtc(crtc, &plane->base);
3099                 plane_state = to_intel_plane_state(plane->base.state);
3100
3101                 if (plane_state->base.visible)
3102                         plane->update_plane(&plane->base,
3103                                             to_intel_crtc_state(crtc->state),
3104                                             plane_state);
3105
3106                 drm_modeset_unlock_crtc(crtc);
3107         }
3108 }
3109
3110 void intel_prepare_reset(struct drm_i915_private *dev_priv)
3111 {
3112         /* no reset support for gen2 */
3113         if (IS_GEN2(dev_priv))
3114                 return;
3115
3116         /* reset doesn't touch the display */
3117         if (INTEL_GEN(dev_priv) >= 5 || IS_G4X(dev_priv))
3118                 return;
3119
3120         drm_modeset_lock_all(&dev_priv->drm);
3121         /*
3122          * Disabling the crtcs gracefully seems nicer. Also the
3123          * g33 docs say we should at least disable all the planes.
3124          */
3125         intel_display_suspend(&dev_priv->drm);
3126 }
3127
3128 void intel_finish_reset(struct drm_i915_private *dev_priv)
3129 {
3130         /*
3131          * Flips in the rings will be nuked by the reset,
3132          * so complete all pending flips so that user space
3133          * will get its events and not get stuck.
3134          */
3135         intel_complete_page_flips(dev_priv);
3136
3137         /* no reset support for gen2 */
3138         if (IS_GEN2(dev_priv))
3139                 return;
3140
3141         /* reset doesn't touch the display */
3142         if (INTEL_GEN(dev_priv) >= 5 || IS_G4X(dev_priv)) {
3143                 /*
3144                  * Flips in the rings have been nuked by the reset,
3145                  * so update the base address of all primary
3146                  * planes to the the last fb to make sure we're
3147                  * showing the correct fb after a reset.
3148                  *
3149                  * FIXME: Atomic will make this obsolete since we won't schedule
3150                  * CS-based flips (which might get lost in gpu resets) any more.
3151                  */
3152                 intel_update_primary_planes(&dev_priv->drm);
3153                 return;
3154         }
3155
3156         /*
3157          * The display has been reset as well,
3158          * so need a full re-initialization.
3159          */
3160         intel_runtime_pm_disable_interrupts(dev_priv);
3161         intel_runtime_pm_enable_interrupts(dev_priv);
3162
3163         intel_modeset_init_hw(&dev_priv->drm);
3164
3165         spin_lock_irq(&dev_priv->irq_lock);
3166         if (dev_priv->display.hpd_irq_setup)
3167                 dev_priv->display.hpd_irq_setup(dev_priv);
3168         spin_unlock_irq(&dev_priv->irq_lock);
3169
3170         intel_display_resume(&dev_priv->drm);
3171
3172         intel_hpd_init(dev_priv);
3173
3174         drm_modeset_unlock_all(&dev_priv->drm);
3175 }
3176
3177 static bool intel_crtc_has_pending_flip(struct drm_crtc *crtc)
3178 {
3179         struct drm_device *dev = crtc->dev;
3180         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3181         unsigned reset_counter;
3182         bool pending;
3183
3184         reset_counter = i915_reset_counter(&to_i915(dev)->gpu_error);
3185         if (intel_crtc->reset_counter != reset_counter)
3186                 return false;
3187
3188         spin_lock_irq(&dev->event_lock);
3189         pending = to_intel_crtc(crtc)->flip_work != NULL;
3190         spin_unlock_irq(&dev->event_lock);
3191
3192         return pending;
3193 }
3194
3195 static void intel_update_pipe_config(struct intel_crtc *crtc,
3196                                      struct intel_crtc_state *old_crtc_state)
3197 {
3198         struct drm_device *dev = crtc->base.dev;
3199         struct drm_i915_private *dev_priv = to_i915(dev);
3200         struct intel_crtc_state *pipe_config =
3201                 to_intel_crtc_state(crtc->base.state);
3202
3203         /* drm_atomic_helper_update_legacy_modeset_state might not be called. */
3204         crtc->base.mode = crtc->base.state->mode;
3205
3206         DRM_DEBUG_KMS("Updating pipe size %ix%i -> %ix%i\n",
3207                       old_crtc_state->pipe_src_w, old_crtc_state->pipe_src_h,
3208                       pipe_config->pipe_src_w, pipe_config->pipe_src_h);
3209
3210         /*
3211          * Update pipe size and adjust fitter if needed: the reason for this is
3212          * that in compute_mode_changes we check the native mode (not the pfit
3213          * mode) to see if we can flip rather than do a full mode set. In the
3214          * fastboot case, we'll flip, but if we don't update the pipesrc and
3215          * pfit state, we'll end up with a big fb scanned out into the wrong
3216          * sized surface.
3217          */
3218
3219         I915_WRITE(PIPESRC(crtc->pipe),
3220                    ((pipe_config->pipe_src_w - 1) << 16) |
3221                    (pipe_config->pipe_src_h - 1));
3222
3223         /* on skylake this is done by detaching scalers */
3224         if (INTEL_INFO(dev)->gen >= 9) {
3225                 skl_detach_scalers(crtc);
3226
3227                 if (pipe_config->pch_pfit.enabled)
3228                         skylake_pfit_enable(crtc);
3229         } else if (HAS_PCH_SPLIT(dev)) {
3230                 if (pipe_config->pch_pfit.enabled)
3231                         ironlake_pfit_enable(crtc);
3232                 else if (old_crtc_state->pch_pfit.enabled)
3233                         ironlake_pfit_disable(crtc, true);
3234         }
3235 }
3236
3237 static void intel_fdi_normal_train(struct drm_crtc *crtc)
3238 {
3239         struct drm_device *dev = crtc->dev;
3240         struct drm_i915_private *dev_priv = to_i915(dev);
3241         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3242         int pipe = intel_crtc->pipe;
3243         i915_reg_t reg;
3244         u32 temp;
3245
3246         /* enable normal train */
3247         reg = FDI_TX_CTL(pipe);
3248         temp = I915_READ(reg);
3249         if (IS_IVYBRIDGE(dev)) {
3250                 temp &= ~FDI_LINK_TRAIN_NONE_IVB;
3251                 temp |= FDI_LINK_TRAIN_NONE_IVB | FDI_TX_ENHANCE_FRAME_ENABLE;
3252         } else {
3253                 temp &= ~FDI_LINK_TRAIN_NONE;
3254                 temp |= FDI_LINK_TRAIN_NONE | FDI_TX_ENHANCE_FRAME_ENABLE;
3255         }
3256         I915_WRITE(reg, temp);
3257
3258         reg = FDI_RX_CTL(pipe);
3259         temp = I915_READ(reg);
3260         if (HAS_PCH_CPT(dev)) {
3261                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
3262                 temp |= FDI_LINK_TRAIN_NORMAL_CPT;
3263         } else {
3264                 temp &= ~FDI_LINK_TRAIN_NONE;
3265                 temp |= FDI_LINK_TRAIN_NONE;
3266         }
3267         I915_WRITE(reg, temp | FDI_RX_ENHANCE_FRAME_ENABLE);
3268
3269         /* wait one idle pattern time */
3270         POSTING_READ(reg);
3271         udelay(1000);
3272
3273         /* IVB wants error correction enabled */
3274         if (IS_IVYBRIDGE(dev))
3275                 I915_WRITE(reg, I915_READ(reg) | FDI_FS_ERRC_ENABLE |
3276                            FDI_FE_ERRC_ENABLE);
3277 }
3278
3279 /* The FDI link training functions for ILK/Ibexpeak. */
3280 static void ironlake_fdi_link_train(struct drm_crtc *crtc)
3281 {
3282         struct drm_device *dev = crtc->dev;
3283         struct drm_i915_private *dev_priv = to_i915(dev);
3284         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3285         int pipe = intel_crtc->pipe;
3286         i915_reg_t reg;
3287         u32 temp, tries;
3288
3289         /* FDI needs bits from pipe first */
3290         assert_pipe_enabled(dev_priv, pipe);
3291
3292         /* Train 1: umask FDI RX Interrupt symbol_lock and bit_lock bit
3293            for train result */
3294         reg = FDI_RX_IMR(pipe);
3295         temp = I915_READ(reg);
3296         temp &= ~FDI_RX_SYMBOL_LOCK;
3297         temp &= ~FDI_RX_BIT_LOCK;
3298         I915_WRITE(reg, temp);
3299         I915_READ(reg);
3300         udelay(150);
3301
3302         /* enable CPU FDI TX and PCH FDI RX */
3303         reg = FDI_TX_CTL(pipe);
3304         temp = I915_READ(reg);
3305         temp &= ~FDI_DP_PORT_WIDTH_MASK;
3306         temp |= FDI_DP_PORT_WIDTH(intel_crtc->config->fdi_lanes);
3307         temp &= ~FDI_LINK_TRAIN_NONE;
3308         temp |= FDI_LINK_TRAIN_PATTERN_1;
3309         I915_WRITE(reg, temp | FDI_TX_ENABLE);
3310
3311         reg = FDI_RX_CTL(pipe);
3312         temp = I915_READ(reg);
3313         temp &= ~FDI_LINK_TRAIN_NONE;
3314         temp |= FDI_LINK_TRAIN_PATTERN_1;
3315         I915_WRITE(reg, temp | FDI_RX_ENABLE);
3316
3317         POSTING_READ(reg);
3318         udelay(150);
3319
3320         /* Ironlake workaround, enable clock pointer after FDI enable*/
3321         I915_WRITE(FDI_RX_CHICKEN(pipe), FDI_RX_PHASE_SYNC_POINTER_OVR);
3322         I915_WRITE(FDI_RX_CHICKEN(pipe), FDI_RX_PHASE_SYNC_POINTER_OVR |
3323                    FDI_RX_PHASE_SYNC_POINTER_EN);
3324
3325         reg = FDI_RX_IIR(pipe);
3326         for (tries = 0; tries < 5; tries++) {
3327                 temp = I915_READ(reg);
3328                 DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
3329
3330                 if ((temp & FDI_RX_BIT_LOCK)) {
3331                         DRM_DEBUG_KMS("FDI train 1 done.\n");
3332                         I915_WRITE(reg, temp | FDI_RX_BIT_LOCK);
3333                         break;
3334                 }
3335         }
3336         if (tries == 5)
3337                 DRM_ERROR("FDI train 1 fail!\n");
3338
3339         /* Train 2 */
3340         reg = FDI_TX_CTL(pipe);
3341         temp = I915_READ(reg);
3342         temp &= ~FDI_LINK_TRAIN_NONE;
3343         temp |= FDI_LINK_TRAIN_PATTERN_2;
3344         I915_WRITE(reg, temp);
3345
3346         reg = FDI_RX_CTL(pipe);
3347         temp = I915_READ(reg);
3348         temp &= ~FDI_LINK_TRAIN_NONE;
3349         temp |= FDI_LINK_TRAIN_PATTERN_2;
3350         I915_WRITE(reg, temp);
3351
3352         POSTING_READ(reg);
3353         udelay(150);
3354
3355         reg = FDI_RX_IIR(pipe);
3356         for (tries = 0; tries < 5; tries++) {
3357                 temp = I915_READ(reg);
3358                 DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
3359
3360                 if (temp & FDI_RX_SYMBOL_LOCK) {
3361                         I915_WRITE(reg, temp | FDI_RX_SYMBOL_LOCK);
3362                         DRM_DEBUG_KMS("FDI train 2 done.\n");
3363                         break;
3364                 }
3365         }
3366         if (tries == 5)
3367                 DRM_ERROR("FDI train 2 fail!\n");
3368
3369         DRM_DEBUG_KMS("FDI train done\n");
3370
3371 }
3372
3373 static const int snb_b_fdi_train_param[] = {
3374         FDI_LINK_TRAIN_400MV_0DB_SNB_B,
3375         FDI_LINK_TRAIN_400MV_6DB_SNB_B,
3376         FDI_LINK_TRAIN_600MV_3_5DB_SNB_B,
3377         FDI_LINK_TRAIN_800MV_0DB_SNB_B,
3378 };
3379
3380 /* The FDI link training functions for SNB/Cougarpoint. */
3381 static void gen6_fdi_link_train(struct drm_crtc *crtc)
3382 {
3383         struct drm_device *dev = crtc->dev;
3384         struct drm_i915_private *dev_priv = to_i915(dev);
3385         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3386         int pipe = intel_crtc->pipe;
3387         i915_reg_t reg;
3388         u32 temp, i, retry;
3389
3390         /* Train 1: umask FDI RX Interrupt symbol_lock and bit_lock bit
3391            for train result */
3392         reg = FDI_RX_IMR(pipe);
3393         temp = I915_READ(reg);
3394         temp &= ~FDI_RX_SYMBOL_LOCK;
3395         temp &= ~FDI_RX_BIT_LOCK;
3396         I915_WRITE(reg, temp);
3397
3398         POSTING_READ(reg);
3399         udelay(150);
3400
3401         /* enable CPU FDI TX and PCH FDI RX */
3402         reg = FDI_TX_CTL(pipe);
3403         temp = I915_READ(reg);
3404         temp &= ~FDI_DP_PORT_WIDTH_MASK;
3405         temp |= FDI_DP_PORT_WIDTH(intel_crtc->config->fdi_lanes);
3406         temp &= ~FDI_LINK_TRAIN_NONE;
3407         temp |= FDI_LINK_TRAIN_PATTERN_1;
3408         temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
3409         /* SNB-B */
3410         temp |= FDI_LINK_TRAIN_400MV_0DB_SNB_B;
3411         I915_WRITE(reg, temp | FDI_TX_ENABLE);
3412
3413         I915_WRITE(FDI_RX_MISC(pipe),
3414                    FDI_RX_TP1_TO_TP2_48 | FDI_RX_FDI_DELAY_90);
3415
3416         reg = FDI_RX_CTL(pipe);
3417         temp = I915_READ(reg);
3418         if (HAS_PCH_CPT(dev)) {
3419                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
3420                 temp |= FDI_LINK_TRAIN_PATTERN_1_CPT;
3421         } else {
3422                 temp &= ~FDI_LINK_TRAIN_NONE;
3423                 temp |= FDI_LINK_TRAIN_PATTERN_1;
3424         }
3425         I915_WRITE(reg, temp | FDI_RX_ENABLE);
3426
3427         POSTING_READ(reg);
3428         udelay(150);
3429
3430         for (i = 0; i < 4; i++) {
3431                 reg = FDI_TX_CTL(pipe);
3432                 temp = I915_READ(reg);
3433                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
3434                 temp |= snb_b_fdi_train_param[i];
3435                 I915_WRITE(reg, temp);
3436
3437                 POSTING_READ(reg);
3438                 udelay(500);
3439
3440                 for (retry = 0; retry < 5; retry++) {
3441                         reg = FDI_RX_IIR(pipe);
3442                         temp = I915_READ(reg);
3443                         DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
3444                         if (temp & FDI_RX_BIT_LOCK) {
3445                                 I915_WRITE(reg, temp | FDI_RX_BIT_LOCK);
3446                                 DRM_DEBUG_KMS("FDI train 1 done.\n");
3447                                 break;
3448                         }
3449                         udelay(50);
3450                 }
3451                 if (retry < 5)
3452                         break;
3453         }
3454         if (i == 4)
3455                 DRM_ERROR("FDI train 1 fail!\n");
3456
3457         /* Train 2 */
3458         reg = FDI_TX_CTL(pipe);
3459         temp = I915_READ(reg);
3460         temp &= ~FDI_LINK_TRAIN_NONE;
3461         temp |= FDI_LINK_TRAIN_PATTERN_2;
3462         if (IS_GEN6(dev)) {
3463                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
3464                 /* SNB-B */
3465                 temp |= FDI_LINK_TRAIN_400MV_0DB_SNB_B;
3466         }
3467         I915_WRITE(reg, temp);
3468
3469         reg = FDI_RX_CTL(pipe);
3470         temp = I915_READ(reg);
3471         if (HAS_PCH_CPT(dev)) {
3472                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
3473                 temp |= FDI_LINK_TRAIN_PATTERN_2_CPT;
3474         } else {
3475                 temp &= ~FDI_LINK_TRAIN_NONE;
3476                 temp |= FDI_LINK_TRAIN_PATTERN_2;
3477         }
3478         I915_WRITE(reg, temp);
3479
3480         POSTING_READ(reg);
3481         udelay(150);
3482
3483         for (i = 0; i < 4; i++) {
3484                 reg = FDI_TX_CTL(pipe);
3485                 temp = I915_READ(reg);
3486                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
3487                 temp |= snb_b_fdi_train_param[i];
3488                 I915_WRITE(reg, temp);
3489
3490                 POSTING_READ(reg);
3491                 udelay(500);
3492
3493                 for (retry = 0; retry < 5; retry++) {
3494                         reg = FDI_RX_IIR(pipe);
3495                         temp = I915_READ(reg);
3496                         DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
3497                         if (temp & FDI_RX_SYMBOL_LOCK) {
3498                                 I915_WRITE(reg, temp | FDI_RX_SYMBOL_LOCK);
3499                                 DRM_DEBUG_KMS("FDI train 2 done.\n");
3500                                 break;
3501                         }
3502                         udelay(50);
3503                 }
3504                 if (retry < 5)
3505                         break;
3506         }
3507         if (i == 4)
3508                 DRM_ERROR("FDI train 2 fail!\n");
3509
3510         DRM_DEBUG_KMS("FDI train done.\n");
3511 }
3512
3513 /* Manual link training for Ivy Bridge A0 parts */
3514 static void ivb_manual_fdi_link_train(struct drm_crtc *crtc)
3515 {
3516         struct drm_device *dev = crtc->dev;
3517         struct drm_i915_private *dev_priv = to_i915(dev);
3518         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3519         int pipe = intel_crtc->pipe;
3520         i915_reg_t reg;
3521         u32 temp, i, j;
3522
3523         /* Train 1: umask FDI RX Interrupt symbol_lock and bit_lock bit
3524            for train result */
3525         reg = FDI_RX_IMR(pipe);
3526         temp = I915_READ(reg);
3527         temp &= ~FDI_RX_SYMBOL_LOCK;
3528         temp &= ~FDI_RX_BIT_LOCK;
3529         I915_WRITE(reg, temp);
3530
3531         POSTING_READ(reg);
3532         udelay(150);
3533
3534         DRM_DEBUG_KMS("FDI_RX_IIR before link train 0x%x\n",
3535                       I915_READ(FDI_RX_IIR(pipe)));
3536
3537         /* Try each vswing and preemphasis setting twice before moving on */
3538         for (j = 0; j < ARRAY_SIZE(snb_b_fdi_train_param) * 2; j++) {
3539                 /* disable first in case we need to retry */
3540                 reg = FDI_TX_CTL(pipe);
3541                 temp = I915_READ(reg);
3542                 temp &= ~(FDI_LINK_TRAIN_AUTO | FDI_LINK_TRAIN_NONE_IVB);
3543                 temp &= ~FDI_TX_ENABLE;
3544                 I915_WRITE(reg, temp);
3545
3546                 reg = FDI_RX_CTL(pipe);
3547                 temp = I915_READ(reg);
3548                 temp &= ~FDI_LINK_TRAIN_AUTO;
3549                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
3550                 temp &= ~FDI_RX_ENABLE;
3551                 I915_WRITE(reg, temp);
3552
3553                 /* enable CPU FDI TX and PCH FDI RX */
3554                 reg = FDI_TX_CTL(pipe);
3555                 temp = I915_READ(reg);
3556                 temp &= ~FDI_DP_PORT_WIDTH_MASK;
3557                 temp |= FDI_DP_PORT_WIDTH(intel_crtc->config->fdi_lanes);
3558                 temp |= FDI_LINK_TRAIN_PATTERN_1_IVB;
3559                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
3560                 temp |= snb_b_fdi_train_param[j/2];
3561                 temp |= FDI_COMPOSITE_SYNC;
3562                 I915_WRITE(reg, temp | FDI_TX_ENABLE);
3563
3564                 I915_WRITE(FDI_RX_MISC(pipe),
3565                            FDI_RX_TP1_TO_TP2_48 | FDI_RX_FDI_DELAY_90);
3566
3567                 reg = FDI_RX_CTL(pipe);
3568                 temp = I915_READ(reg);
3569                 temp |= FDI_LINK_TRAIN_PATTERN_1_CPT;
3570                 temp |= FDI_COMPOSITE_SYNC;
3571                 I915_WRITE(reg, temp | FDI_RX_ENABLE);
3572
3573                 POSTING_READ(reg);
3574                 udelay(1); /* should be 0.5us */
3575
3576                 for (i = 0; i < 4; i++) {
3577                         reg = FDI_RX_IIR(pipe);
3578                         temp = I915_READ(reg);
3579                         DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
3580
3581                         if (temp & FDI_RX_BIT_LOCK ||
3582                             (I915_READ(reg) & FDI_RX_BIT_LOCK)) {
3583                                 I915_WRITE(reg, temp | FDI_RX_BIT_LOCK);
3584                                 DRM_DEBUG_KMS("FDI train 1 done, level %i.\n",
3585                                               i);
3586                                 break;
3587                         }
3588                         udelay(1); /* should be 0.5us */
3589                 }
3590                 if (i == 4) {
3591                         DRM_DEBUG_KMS("FDI train 1 fail on vswing %d\n", j / 2);
3592                         continue;
3593                 }
3594
3595                 /* Train 2 */
3596                 reg = FDI_TX_CTL(pipe);
3597                 temp = I915_READ(reg);
3598                 temp &= ~FDI_LINK_TRAIN_NONE_IVB;
3599                 temp |= FDI_LINK_TRAIN_PATTERN_2_IVB;
3600                 I915_WRITE(reg, temp);
3601
3602                 reg = FDI_RX_CTL(pipe);
3603                 temp = I915_READ(reg);
3604                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
3605                 temp |= FDI_LINK_TRAIN_PATTERN_2_CPT;
3606                 I915_WRITE(reg, temp);
3607
3608                 POSTING_READ(reg);
3609                 udelay(2); /* should be 1.5us */
3610
3611                 for (i = 0; i < 4; i++) {
3612                         reg = FDI_RX_IIR(pipe);
3613                         temp = I915_READ(reg);
3614                         DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
3615
3616                         if (temp & FDI_RX_SYMBOL_LOCK ||
3617                             (I915_READ(reg) & FDI_RX_SYMBOL_LOCK)) {
3618                                 I915_WRITE(reg, temp | FDI_RX_SYMBOL_LOCK);
3619                                 DRM_DEBUG_KMS("FDI train 2 done, level %i.\n",
3620                                               i);
3621                                 goto train_done;
3622                         }
3623                         udelay(2); /* should be 1.5us */
3624                 }
3625                 if (i == 4)
3626                         DRM_DEBUG_KMS("FDI train 2 fail on vswing %d\n", j / 2);
3627         }
3628
3629 train_done:
3630         DRM_DEBUG_KMS("FDI train done.\n");
3631 }
3632
3633 static void ironlake_fdi_pll_enable(struct intel_crtc *intel_crtc)
3634 {
3635         struct drm_device *dev = intel_crtc->base.dev;
3636         struct drm_i915_private *dev_priv = to_i915(dev);
3637         int pipe = intel_crtc->pipe;
3638         i915_reg_t reg;
3639         u32 temp;
3640
3641         /* enable PCH FDI RX PLL, wait warmup plus DMI latency */
3642         reg = FDI_RX_CTL(pipe);
3643         temp = I915_READ(reg);
3644         temp &= ~(FDI_DP_PORT_WIDTH_MASK | (0x7 << 16));
3645         temp |= FDI_DP_PORT_WIDTH(intel_crtc->config->fdi_lanes);
3646         temp |= (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) << 11;
3647         I915_WRITE(reg, temp | FDI_RX_PLL_ENABLE);
3648
3649         POSTING_READ(reg);
3650         udelay(200);
3651
3652         /* Switch from Rawclk to PCDclk */
3653         temp = I915_READ(reg);
3654         I915_WRITE(reg, temp | FDI_PCDCLK);
3655
3656         POSTING_READ(reg);
3657         udelay(200);
3658
3659         /* Enable CPU FDI TX PLL, always on for Ironlake */
3660         reg = FDI_TX_CTL(pipe);
3661         temp = I915_READ(reg);
3662         if ((temp & FDI_TX_PLL_ENABLE) == 0) {
3663                 I915_WRITE(reg, temp | FDI_TX_PLL_ENABLE);
3664
3665                 POSTING_READ(reg);
3666                 udelay(100);
3667         }
3668 }
3669
3670 static void ironlake_fdi_pll_disable(struct intel_crtc *intel_crtc)
3671 {
3672         struct drm_device *dev = intel_crtc->base.dev;
3673         struct drm_i915_private *dev_priv = to_i915(dev);
3674         int pipe = intel_crtc->pipe;
3675         i915_reg_t reg;
3676         u32 temp;
3677
3678         /* Switch from PCDclk to Rawclk */
3679         reg = FDI_RX_CTL(pipe);
3680         temp = I915_READ(reg);
3681         I915_WRITE(reg, temp & ~FDI_PCDCLK);
3682
3683         /* Disable CPU FDI TX PLL */
3684         reg = FDI_TX_CTL(pipe);
3685         temp = I915_READ(reg);
3686         I915_WRITE(reg, temp & ~FDI_TX_PLL_ENABLE);
3687
3688         POSTING_READ(reg);
3689         udelay(100);
3690
3691         reg = FDI_RX_CTL(pipe);
3692         temp = I915_READ(reg);
3693         I915_WRITE(reg, temp & ~FDI_RX_PLL_ENABLE);
3694
3695         /* Wait for the clocks to turn off. */
3696         POSTING_READ(reg);
3697         udelay(100);
3698 }
3699
3700 static void ironlake_fdi_disable(struct drm_crtc *crtc)
3701 {
3702         struct drm_device *dev = crtc->dev;
3703         struct drm_i915_private *dev_priv = to_i915(dev);
3704         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3705         int pipe = intel_crtc->pipe;
3706         i915_reg_t reg;
3707         u32 temp;
3708
3709         /* disable CPU FDI tx and PCH FDI rx */
3710         reg = FDI_TX_CTL(pipe);
3711         temp = I915_READ(reg);
3712         I915_WRITE(reg, temp & ~FDI_TX_ENABLE);
3713         POSTING_READ(reg);
3714
3715         reg = FDI_RX_CTL(pipe);
3716         temp = I915_READ(reg);
3717         temp &= ~(0x7 << 16);
3718         temp |= (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) << 11;
3719         I915_WRITE(reg, temp & ~FDI_RX_ENABLE);
3720
3721         POSTING_READ(reg);
3722         udelay(100);
3723
3724         /* Ironlake workaround, disable clock pointer after downing FDI */
3725         if (HAS_PCH_IBX(dev))
3726                 I915_WRITE(FDI_RX_CHICKEN(pipe), FDI_RX_PHASE_SYNC_POINTER_OVR);
3727
3728         /* still set train pattern 1 */
3729         reg = FDI_TX_CTL(pipe);
3730         temp = I915_READ(reg);
3731         temp &= ~FDI_LINK_TRAIN_NONE;
3732         temp |= FDI_LINK_TRAIN_PATTERN_1;
3733         I915_WRITE(reg, temp);
3734
3735         reg = FDI_RX_CTL(pipe);
3736         temp = I915_READ(reg);
3737         if (HAS_PCH_CPT(dev)) {
3738                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
3739                 temp |= FDI_LINK_TRAIN_PATTERN_1_CPT;
3740         } else {
3741                 temp &= ~FDI_LINK_TRAIN_NONE;
3742                 temp |= FDI_LINK_TRAIN_PATTERN_1;
3743         }
3744         /* BPC in FDI rx is consistent with that in PIPECONF */
3745         temp &= ~(0x07 << 16);
3746         temp |= (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) << 11;
3747         I915_WRITE(reg, temp);
3748
3749         POSTING_READ(reg);
3750         udelay(100);
3751 }
3752
3753 bool intel_has_pending_fb_unpin(struct drm_device *dev)
3754 {
3755         struct intel_crtc *crtc;
3756
3757         /* Note that we don't need to be called with mode_config.lock here
3758          * as our list of CRTC objects is static for the lifetime of the
3759          * device and so cannot disappear as we iterate. Similarly, we can
3760          * happily treat the predicates as racy, atomic checks as userspace
3761          * cannot claim and pin a new fb without at least acquring the
3762          * struct_mutex and so serialising with us.
3763          */
3764         for_each_intel_crtc(dev, crtc) {
3765                 if (atomic_read(&crtc->unpin_work_count) == 0)
3766                         continue;
3767
3768                 if (crtc->flip_work)
3769                         intel_wait_for_vblank(dev, crtc->pipe);
3770
3771                 return true;
3772         }
3773
3774         return false;
3775 }
3776
3777 static void page_flip_completed(struct intel_crtc *intel_crtc)
3778 {
3779         struct drm_i915_private *dev_priv = to_i915(intel_crtc->base.dev);
3780         struct intel_flip_work *work = intel_crtc->flip_work;
3781
3782         intel_crtc->flip_work = NULL;
3783
3784         if (work->event)
3785                 drm_crtc_send_vblank_event(&intel_crtc->base, work->event);
3786
3787         drm_crtc_vblank_put(&intel_crtc->base);
3788
3789         wake_up_all(&dev_priv->pending_flip_queue);
3790         queue_work(dev_priv->wq, &work->unpin_work);
3791
3792         trace_i915_flip_complete(intel_crtc->plane,
3793                                  work->pending_flip_obj);
3794 }
3795
3796 static int intel_crtc_wait_for_pending_flips(struct drm_crtc *crtc)
3797 {
3798         struct drm_device *dev = crtc->dev;
3799         struct drm_i915_private *dev_priv = to_i915(dev);
3800         long ret;
3801
3802         WARN_ON(waitqueue_active(&dev_priv->pending_flip_queue));
3803
3804         ret = wait_event_interruptible_timeout(
3805                                         dev_priv->pending_flip_queue,
3806                                         !intel_crtc_has_pending_flip(crtc),
3807                                         60*HZ);
3808
3809         if (ret < 0)
3810                 return ret;
3811
3812         if (ret == 0) {
3813                 struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3814                 struct intel_flip_work *work;
3815
3816                 spin_lock_irq(&dev->event_lock);
3817                 work = intel_crtc->flip_work;
3818                 if (work && !is_mmio_work(work)) {
3819                         WARN_ONCE(1, "Removing stuck page flip\n");
3820                         page_flip_completed(intel_crtc);
3821                 }
3822                 spin_unlock_irq(&dev->event_lock);
3823         }
3824
3825         return 0;
3826 }
3827
3828 static void lpt_disable_iclkip(struct drm_i915_private *dev_priv)
3829 {
3830         u32 temp;
3831
3832         I915_WRITE(PIXCLK_GATE, PIXCLK_GATE_GATE);
3833
3834         mutex_lock(&dev_priv->sb_lock);
3835
3836         temp = intel_sbi_read(dev_priv, SBI_SSCCTL6, SBI_ICLK);
3837         temp |= SBI_SSCCTL_DISABLE;
3838         intel_sbi_write(dev_priv, SBI_SSCCTL6, temp, SBI_ICLK);
3839
3840         mutex_unlock(&dev_priv->sb_lock);
3841 }
3842
3843 /* Program iCLKIP clock to the desired frequency */
3844 static void lpt_program_iclkip(struct drm_crtc *crtc)
3845 {
3846         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
3847         int clock = to_intel_crtc(crtc)->config->base.adjusted_mode.crtc_clock;
3848         u32 divsel, phaseinc, auxdiv, phasedir = 0;
3849         u32 temp;
3850
3851         lpt_disable_iclkip(dev_priv);
3852
3853         /* The iCLK virtual clock root frequency is in MHz,
3854          * but the adjusted_mode->crtc_clock in in KHz. To get the
3855          * divisors, it is necessary to divide one by another, so we
3856          * convert the virtual clock precision to KHz here for higher
3857          * precision.
3858          */
3859         for (auxdiv = 0; auxdiv < 2; auxdiv++) {
3860                 u32 iclk_virtual_root_freq = 172800 * 1000;
3861                 u32 iclk_pi_range = 64;
3862                 u32 desired_divisor;
3863
3864                 desired_divisor = DIV_ROUND_CLOSEST(iclk_virtual_root_freq,
3865                                                     clock << auxdiv);
3866                 divsel = (desired_divisor / iclk_pi_range) - 2;
3867                 phaseinc = desired_divisor % iclk_pi_range;
3868
3869                 /*
3870                  * Near 20MHz is a corner case which is
3871                  * out of range for the 7-bit divisor
3872                  */
3873                 if (divsel <= 0x7f)
3874                         break;
3875         }
3876
3877         /* This should not happen with any sane values */
3878         WARN_ON(SBI_SSCDIVINTPHASE_DIVSEL(divsel) &
3879                 ~SBI_SSCDIVINTPHASE_DIVSEL_MASK);
3880         WARN_ON(SBI_SSCDIVINTPHASE_DIR(phasedir) &
3881                 ~SBI_SSCDIVINTPHASE_INCVAL_MASK);
3882
3883         DRM_DEBUG_KMS("iCLKIP clock: found settings for %dKHz refresh rate: auxdiv=%x, divsel=%x, phasedir=%x, phaseinc=%x\n",
3884                         clock,
3885                         auxdiv,
3886                         divsel,
3887                         phasedir,
3888                         phaseinc);
3889
3890         mutex_lock(&dev_priv->sb_lock);
3891
3892         /* Program SSCDIVINTPHASE6 */
3893         temp = intel_sbi_read(dev_priv, SBI_SSCDIVINTPHASE6, SBI_ICLK);
3894         temp &= ~SBI_SSCDIVINTPHASE_DIVSEL_MASK;
3895         temp |= SBI_SSCDIVINTPHASE_DIVSEL(divsel);
3896         temp &= ~SBI_SSCDIVINTPHASE_INCVAL_MASK;
3897         temp |= SBI_SSCDIVINTPHASE_INCVAL(phaseinc);
3898         temp |= SBI_SSCDIVINTPHASE_DIR(phasedir);
3899         temp |= SBI_SSCDIVINTPHASE_PROPAGATE;
3900         intel_sbi_write(dev_priv, SBI_SSCDIVINTPHASE6, temp, SBI_ICLK);
3901
3902         /* Program SSCAUXDIV */
3903         temp = intel_sbi_read(dev_priv, SBI_SSCAUXDIV6, SBI_ICLK);
3904         temp &= ~SBI_SSCAUXDIV_FINALDIV2SEL(1);
3905         temp |= SBI_SSCAUXDIV_FINALDIV2SEL(auxdiv);
3906         intel_sbi_write(dev_priv, SBI_SSCAUXDIV6, temp, SBI_ICLK);
3907
3908         /* Enable modulator and associated divider */
3909         temp = intel_sbi_read(dev_priv, SBI_SSCCTL6, SBI_ICLK);
3910         temp &= ~SBI_SSCCTL_DISABLE;
3911         intel_sbi_write(dev_priv, SBI_SSCCTL6, temp, SBI_ICLK);
3912
3913         mutex_unlock(&dev_priv->sb_lock);
3914
3915         /* Wait for initialization time */
3916         udelay(24);
3917
3918         I915_WRITE(PIXCLK_GATE, PIXCLK_GATE_UNGATE);
3919 }
3920
3921 int lpt_get_iclkip(struct drm_i915_private *dev_priv)
3922 {
3923         u32 divsel, phaseinc, auxdiv;
3924         u32 iclk_virtual_root_freq = 172800 * 1000;
3925         u32 iclk_pi_range = 64;
3926         u32 desired_divisor;
3927         u32 temp;
3928
3929         if ((I915_READ(PIXCLK_GATE) & PIXCLK_GATE_UNGATE) == 0)
3930                 return 0;
3931
3932         mutex_lock(&dev_priv->sb_lock);
3933
3934         temp = intel_sbi_read(dev_priv, SBI_SSCCTL6, SBI_ICLK);
3935         if (temp & SBI_SSCCTL_DISABLE) {
3936                 mutex_unlock(&dev_priv->sb_lock);
3937                 return 0;
3938         }
3939
3940         temp = intel_sbi_read(dev_priv, SBI_SSCDIVINTPHASE6, SBI_ICLK);
3941         divsel = (temp & SBI_SSCDIVINTPHASE_DIVSEL_MASK) >>
3942                 SBI_SSCDIVINTPHASE_DIVSEL_SHIFT;
3943         phaseinc = (temp & SBI_SSCDIVINTPHASE_INCVAL_MASK) >>
3944                 SBI_SSCDIVINTPHASE_INCVAL_SHIFT;
3945
3946         temp = intel_sbi_read(dev_priv, SBI_SSCAUXDIV6, SBI_ICLK);
3947         auxdiv = (temp & SBI_SSCAUXDIV_FINALDIV2SEL_MASK) >>
3948                 SBI_SSCAUXDIV_FINALDIV2SEL_SHIFT;
3949
3950         mutex_unlock(&dev_priv->sb_lock);
3951
3952         desired_divisor = (divsel + 2) * iclk_pi_range + phaseinc;
3953
3954         return DIV_ROUND_CLOSEST(iclk_virtual_root_freq,
3955                                  desired_divisor << auxdiv);
3956 }
3957
3958 static void ironlake_pch_transcoder_set_timings(struct intel_crtc *crtc,
3959                                                 enum pipe pch_transcoder)
3960 {
3961         struct drm_device *dev = crtc->base.dev;
3962         struct drm_i915_private *dev_priv = to_i915(dev);
3963         enum transcoder cpu_transcoder = crtc->config->cpu_transcoder;
3964
3965         I915_WRITE(PCH_TRANS_HTOTAL(pch_transcoder),
3966                    I915_READ(HTOTAL(cpu_transcoder)));
3967         I915_WRITE(PCH_TRANS_HBLANK(pch_transcoder),
3968                    I915_READ(HBLANK(cpu_transcoder)));
3969         I915_WRITE(PCH_TRANS_HSYNC(pch_transcoder),
3970                    I915_READ(HSYNC(cpu_transcoder)));
3971
3972         I915_WRITE(PCH_TRANS_VTOTAL(pch_transcoder),
3973                    I915_READ(VTOTAL(cpu_transcoder)));
3974         I915_WRITE(PCH_TRANS_VBLANK(pch_transcoder),
3975                    I915_READ(VBLANK(cpu_transcoder)));
3976         I915_WRITE(PCH_TRANS_VSYNC(pch_transcoder),
3977                    I915_READ(VSYNC(cpu_transcoder)));
3978         I915_WRITE(PCH_TRANS_VSYNCSHIFT(pch_transcoder),
3979                    I915_READ(VSYNCSHIFT(cpu_transcoder)));
3980 }
3981
3982 static void cpt_set_fdi_bc_bifurcation(struct drm_device *dev, bool enable)
3983 {
3984         struct drm_i915_private *dev_priv = to_i915(dev);
3985         uint32_t temp;
3986
3987         temp = I915_READ(SOUTH_CHICKEN1);
3988         if (!!(temp & FDI_BC_BIFURCATION_SELECT) == enable)
3989                 return;
3990
3991         WARN_ON(I915_READ(FDI_RX_CTL(PIPE_B)) & FDI_RX_ENABLE);
3992         WARN_ON(I915_READ(FDI_RX_CTL(PIPE_C)) & FDI_RX_ENABLE);
3993
3994         temp &= ~FDI_BC_BIFURCATION_SELECT;
3995         if (enable)
3996                 temp |= FDI_BC_BIFURCATION_SELECT;
3997
3998         DRM_DEBUG_KMS("%sabling fdi C rx\n", enable ? "en" : "dis");
3999         I915_WRITE(SOUTH_CHICKEN1, temp);
4000         POSTING_READ(SOUTH_CHICKEN1);
4001 }
4002
4003 static void ivybridge_update_fdi_bc_bifurcation(struct intel_crtc *intel_crtc)
4004 {
4005         struct drm_device *dev = intel_crtc->base.dev;
4006
4007         switch (intel_crtc->pipe) {
4008         case PIPE_A:
4009                 break;
4010         case PIPE_B:
4011                 if (intel_crtc->config->fdi_lanes > 2)
4012                         cpt_set_fdi_bc_bifurcation(dev, false);
4013                 else
4014                         cpt_set_fdi_bc_bifurcation(dev, true);
4015
4016                 break;
4017         case PIPE_C:
4018                 cpt_set_fdi_bc_bifurcation(dev, true);
4019
4020                 break;
4021         default:
4022                 BUG();
4023         }
4024 }
4025
4026 /* Return which DP Port should be selected for Transcoder DP control */
4027 static enum port
4028 intel_trans_dp_port_sel(struct drm_crtc *crtc)
4029 {
4030         struct drm_device *dev = crtc->dev;
4031         struct intel_encoder *encoder;
4032
4033         for_each_encoder_on_crtc(dev, crtc, encoder) {
4034                 if (encoder->type == INTEL_OUTPUT_DP ||
4035                     encoder->type == INTEL_OUTPUT_EDP)
4036                         return enc_to_dig_port(&encoder->base)->port;
4037         }
4038
4039         return -1;
4040 }
4041
4042 /*
4043  * Enable PCH resources required for PCH ports:
4044  *   - PCH PLLs
4045  *   - FDI training & RX/TX
4046  *   - update transcoder timings
4047  *   - DP transcoding bits
4048  *   - transcoder
4049  */
4050 static void ironlake_pch_enable(struct drm_crtc *crtc)
4051 {
4052         struct drm_device *dev = crtc->dev;
4053         struct drm_i915_private *dev_priv = to_i915(dev);
4054         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4055         int pipe = intel_crtc->pipe;
4056         u32 temp;
4057
4058         assert_pch_transcoder_disabled(dev_priv, pipe);
4059
4060         if (IS_IVYBRIDGE(dev))
4061                 ivybridge_update_fdi_bc_bifurcation(intel_crtc);
4062
4063         /* Write the TU size bits before fdi link training, so that error
4064          * detection works. */
4065         I915_WRITE(FDI_RX_TUSIZE1(pipe),
4066                    I915_READ(PIPE_DATA_M1(pipe)) & TU_SIZE_MASK);
4067
4068         /* For PCH output, training FDI link */
4069         dev_priv->display.fdi_link_train(crtc);
4070
4071         /* We need to program the right clock selection before writing the pixel
4072          * mutliplier into the DPLL. */
4073         if (HAS_PCH_CPT(dev)) {
4074                 u32 sel;
4075
4076                 temp = I915_READ(PCH_DPLL_SEL);
4077                 temp |= TRANS_DPLL_ENABLE(pipe);
4078                 sel = TRANS_DPLLB_SEL(pipe);
4079                 if (intel_crtc->config->shared_dpll ==
4080                     intel_get_shared_dpll_by_id(dev_priv, DPLL_ID_PCH_PLL_B))
4081                         temp |= sel;
4082                 else
4083                         temp &= ~sel;
4084                 I915_WRITE(PCH_DPLL_SEL, temp);
4085         }
4086
4087         /* XXX: pch pll's can be enabled any time before we enable the PCH
4088          * transcoder, and we actually should do this to not upset any PCH
4089          * transcoder that already use the clock when we share it.
4090          *
4091          * Note that enable_shared_dpll tries to do the right thing, but
4092          * get_shared_dpll unconditionally resets the pll - we need that to have
4093          * the right LVDS enable sequence. */
4094         intel_enable_shared_dpll(intel_crtc);
4095
4096         /* set transcoder timing, panel must allow it */
4097         assert_panel_unlocked(dev_priv, pipe);
4098         ironlake_pch_transcoder_set_timings(intel_crtc, pipe);
4099
4100         intel_fdi_normal_train(crtc);
4101
4102         /* For PCH DP, enable TRANS_DP_CTL */
4103         if (HAS_PCH_CPT(dev) && intel_crtc_has_dp_encoder(intel_crtc->config)) {
4104                 const struct drm_display_mode *adjusted_mode =
4105                         &intel_crtc->config->base.adjusted_mode;
4106                 u32 bpc = (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) >> 5;
4107                 i915_reg_t reg = TRANS_DP_CTL(pipe);
4108                 temp = I915_READ(reg);
4109                 temp &= ~(TRANS_DP_PORT_SEL_MASK |
4110                           TRANS_DP_SYNC_MASK |
4111                           TRANS_DP_BPC_MASK);
4112                 temp |= TRANS_DP_OUTPUT_ENABLE;
4113                 temp |= bpc << 9; /* same format but at 11:9 */
4114
4115                 if (adjusted_mode->flags & DRM_MODE_FLAG_PHSYNC)
4116                         temp |= TRANS_DP_HSYNC_ACTIVE_HIGH;
4117                 if (adjusted_mode->flags & DRM_MODE_FLAG_PVSYNC)
4118                         temp |= TRANS_DP_VSYNC_ACTIVE_HIGH;
4119
4120                 switch (intel_trans_dp_port_sel(crtc)) {
4121                 case PORT_B:
4122                         temp |= TRANS_DP_PORT_SEL_B;
4123                         break;
4124                 case PORT_C:
4125                         temp |= TRANS_DP_PORT_SEL_C;
4126                         break;
4127                 case PORT_D:
4128                         temp |= TRANS_DP_PORT_SEL_D;
4129                         break;
4130                 default:
4131                         BUG();
4132                 }
4133
4134                 I915_WRITE(reg, temp);
4135         }
4136
4137         ironlake_enable_pch_transcoder(dev_priv, pipe);
4138 }
4139
4140 static void lpt_pch_enable(struct drm_crtc *crtc)
4141 {
4142         struct drm_device *dev = crtc->dev;
4143         struct drm_i915_private *dev_priv = to_i915(dev);
4144         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4145         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
4146
4147         assert_pch_transcoder_disabled(dev_priv, TRANSCODER_A);
4148
4149         lpt_program_iclkip(crtc);
4150
4151         /* Set transcoder timing. */
4152         ironlake_pch_transcoder_set_timings(intel_crtc, PIPE_A);
4153
4154         lpt_enable_pch_transcoder(dev_priv, cpu_transcoder);
4155 }
4156
4157 static void cpt_verify_modeset(struct drm_device *dev, int pipe)
4158 {
4159         struct drm_i915_private *dev_priv = to_i915(dev);
4160         i915_reg_t dslreg = PIPEDSL(pipe);
4161         u32 temp;
4162
4163         temp = I915_READ(dslreg);
4164         udelay(500);
4165         if (wait_for(I915_READ(dslreg) != temp, 5)) {
4166                 if (wait_for(I915_READ(dslreg) != temp, 5))
4167                         DRM_ERROR("mode set failed: pipe %c stuck\n", pipe_name(pipe));
4168         }
4169 }
4170
4171 static int
4172 skl_update_scaler(struct intel_crtc_state *crtc_state, bool force_detach,
4173                   unsigned scaler_user, int *scaler_id, unsigned int rotation,
4174                   int src_w, int src_h, int dst_w, int dst_h)
4175 {
4176         struct intel_crtc_scaler_state *scaler_state =
4177                 &crtc_state->scaler_state;
4178         struct intel_crtc *intel_crtc =
4179                 to_intel_crtc(crtc_state->base.crtc);
4180         int need_scaling;
4181
4182         need_scaling = intel_rotation_90_or_270(rotation) ?
4183                 (src_h != dst_w || src_w != dst_h):
4184                 (src_w != dst_w || src_h != dst_h);
4185
4186         /*
4187          * if plane is being disabled or scaler is no more required or force detach
4188          *  - free scaler binded to this plane/crtc
4189          *  - in order to do this, update crtc->scaler_usage
4190          *
4191          * Here scaler state in crtc_state is set free so that
4192          * scaler can be assigned to other user. Actual register
4193          * update to free the scaler is done in plane/panel-fit programming.
4194          * For this purpose crtc/plane_state->scaler_id isn't reset here.
4195          */
4196         if (force_detach || !need_scaling) {
4197                 if (*scaler_id >= 0) {
4198                         scaler_state->scaler_users &= ~(1 << scaler_user);
4199                         scaler_state->scalers[*scaler_id].in_use = 0;
4200
4201                         DRM_DEBUG_KMS("scaler_user index %u.%u: "
4202                                 "Staged freeing scaler id %d scaler_users = 0x%x\n",
4203                                 intel_crtc->pipe, scaler_user, *scaler_id,
4204                                 scaler_state->scaler_users);
4205                         *scaler_id = -1;
4206                 }
4207                 return 0;
4208         }
4209
4210         /* range checks */
4211         if (src_w < SKL_MIN_SRC_W || src_h < SKL_MIN_SRC_H ||
4212                 dst_w < SKL_MIN_DST_W || dst_h < SKL_MIN_DST_H ||
4213
4214                 src_w > SKL_MAX_SRC_W || src_h > SKL_MAX_SRC_H ||
4215                 dst_w > SKL_MAX_DST_W || dst_h > SKL_MAX_DST_H) {
4216                 DRM_DEBUG_KMS("scaler_user index %u.%u: src %ux%u dst %ux%u "
4217                         "size is out of scaler range\n",
4218                         intel_crtc->pipe, scaler_user, src_w, src_h, dst_w, dst_h);
4219                 return -EINVAL;
4220         }
4221
4222         /* mark this plane as a scaler user in crtc_state */
4223         scaler_state->scaler_users |= (1 << scaler_user);
4224         DRM_DEBUG_KMS("scaler_user index %u.%u: "
4225                 "staged scaling request for %ux%u->%ux%u scaler_users = 0x%x\n",
4226                 intel_crtc->pipe, scaler_user, src_w, src_h, dst_w, dst_h,
4227                 scaler_state->scaler_users);
4228
4229         return 0;
4230 }
4231
4232 /**
4233  * skl_update_scaler_crtc - Stages update to scaler state for a given crtc.
4234  *
4235  * @state: crtc's scaler state
4236  *
4237  * Return
4238  *     0 - scaler_usage updated successfully
4239  *    error - requested scaling cannot be supported or other error condition
4240  */
4241 int skl_update_scaler_crtc(struct intel_crtc_state *state)
4242 {
4243         struct intel_crtc *intel_crtc = to_intel_crtc(state->base.crtc);
4244         const struct drm_display_mode *adjusted_mode = &state->base.adjusted_mode;
4245
4246         DRM_DEBUG_KMS("Updating scaler for [CRTC:%d:%s] scaler_user index %u.%u\n",
4247                       intel_crtc->base.base.id, intel_crtc->base.name,
4248                       intel_crtc->pipe, SKL_CRTC_INDEX);
4249
4250         return skl_update_scaler(state, !state->base.active, SKL_CRTC_INDEX,
4251                 &state->scaler_state.scaler_id, DRM_ROTATE_0,
4252                 state->pipe_src_w, state->pipe_src_h,
4253                 adjusted_mode->crtc_hdisplay, adjusted_mode->crtc_vdisplay);
4254 }
4255
4256 /**
4257  * skl_update_scaler_plane - Stages update to scaler state for a given plane.
4258  *
4259  * @state: crtc's scaler state
4260  * @plane_state: atomic plane state to update
4261  *
4262  * Return
4263  *     0 - scaler_usage updated successfully
4264  *    error - requested scaling cannot be supported or other error condition
4265  */
4266 static int skl_update_scaler_plane(struct intel_crtc_state *crtc_state,
4267                                    struct intel_plane_state *plane_state)
4268 {
4269
4270         struct intel_crtc *intel_crtc = to_intel_crtc(crtc_state->base.crtc);
4271         struct intel_plane *intel_plane =
4272                 to_intel_plane(plane_state->base.plane);
4273         struct drm_framebuffer *fb = plane_state->base.fb;
4274         int ret;
4275
4276         bool force_detach = !fb || !plane_state->base.visible;
4277
4278         DRM_DEBUG_KMS("Updating scaler for [PLANE:%d:%s] scaler_user index %u.%u\n",
4279                       intel_plane->base.base.id, intel_plane->base.name,
4280                       intel_crtc->pipe, drm_plane_index(&intel_plane->base));
4281
4282         ret = skl_update_scaler(crtc_state, force_detach,
4283                                 drm_plane_index(&intel_plane->base),
4284                                 &plane_state->scaler_id,
4285                                 plane_state->base.rotation,
4286                                 drm_rect_width(&plane_state->base.src) >> 16,
4287                                 drm_rect_height(&plane_state->base.src) >> 16,
4288                                 drm_rect_width(&plane_state->base.dst),
4289                                 drm_rect_height(&plane_state->base.dst));
4290
4291         if (ret || plane_state->scaler_id < 0)
4292                 return ret;
4293
4294         /* check colorkey */
4295         if (plane_state->ckey.flags != I915_SET_COLORKEY_NONE) {
4296                 DRM_DEBUG_KMS("[PLANE:%d:%s] scaling with color key not allowed",
4297                               intel_plane->base.base.id,
4298                               intel_plane->base.name);
4299                 return -EINVAL;
4300         }
4301
4302         /* Check src format */
4303         switch (fb->pixel_format) {
4304         case DRM_FORMAT_RGB565:
4305         case DRM_FORMAT_XBGR8888:
4306         case DRM_FORMAT_XRGB8888:
4307         case DRM_FORMAT_ABGR8888:
4308         case DRM_FORMAT_ARGB8888:
4309         case DRM_FORMAT_XRGB2101010:
4310         case DRM_FORMAT_XBGR2101010:
4311         case DRM_FORMAT_YUYV:
4312         case DRM_FORMAT_YVYU:
4313         case DRM_FORMAT_UYVY:
4314         case DRM_FORMAT_VYUY:
4315                 break;
4316         default:
4317                 DRM_DEBUG_KMS("[PLANE:%d:%s] FB:%d unsupported scaling format 0x%x\n",
4318                               intel_plane->base.base.id, intel_plane->base.name,
4319                               fb->base.id, fb->pixel_format);
4320                 return -EINVAL;
4321         }
4322
4323         return 0;
4324 }
4325
4326 static void skylake_scaler_disable(struct intel_crtc *crtc)
4327 {
4328         int i;
4329
4330         for (i = 0; i < crtc->num_scalers; i++)
4331                 skl_detach_scaler(crtc, i);
4332 }
4333
4334 static void skylake_pfit_enable(struct intel_crtc *crtc)
4335 {
4336         struct drm_device *dev = crtc->base.dev;
4337         struct drm_i915_private *dev_priv = to_i915(dev);
4338         int pipe = crtc->pipe;
4339         struct intel_crtc_scaler_state *scaler_state =
4340                 &crtc->config->scaler_state;
4341
4342         DRM_DEBUG_KMS("for crtc_state = %p\n", crtc->config);
4343
4344         if (crtc->config->pch_pfit.enabled) {
4345                 int id;
4346
4347                 if (WARN_ON(crtc->config->scaler_state.scaler_id < 0)) {
4348                         DRM_ERROR("Requesting pfit without getting a scaler first\n");
4349                         return;
4350                 }
4351
4352                 id = scaler_state->scaler_id;
4353                 I915_WRITE(SKL_PS_CTRL(pipe, id), PS_SCALER_EN |
4354                         PS_FILTER_MEDIUM | scaler_state->scalers[id].mode);
4355                 I915_WRITE(SKL_PS_WIN_POS(pipe, id), crtc->config->pch_pfit.pos);
4356                 I915_WRITE(SKL_PS_WIN_SZ(pipe, id), crtc->config->pch_pfit.size);
4357
4358                 DRM_DEBUG_KMS("for crtc_state = %p scaler_id = %d\n", crtc->config, id);
4359         }
4360 }
4361
4362 static void ironlake_pfit_enable(struct intel_crtc *crtc)
4363 {
4364         struct drm_device *dev = crtc->base.dev;
4365         struct drm_i915_private *dev_priv = to_i915(dev);
4366         int pipe = crtc->pipe;
4367
4368         if (crtc->config->pch_pfit.enabled) {
4369                 /* Force use of hard-coded filter coefficients
4370                  * as some pre-programmed values are broken,
4371                  * e.g. x201.
4372                  */
4373                 if (IS_IVYBRIDGE(dev) || IS_HASWELL(dev))
4374                         I915_WRITE(PF_CTL(pipe), PF_ENABLE | PF_FILTER_MED_3x3 |
4375                                                  PF_PIPE_SEL_IVB(pipe));
4376                 else
4377                         I915_WRITE(PF_CTL(pipe), PF_ENABLE | PF_FILTER_MED_3x3);
4378                 I915_WRITE(PF_WIN_POS(pipe), crtc->config->pch_pfit.pos);
4379                 I915_WRITE(PF_WIN_SZ(pipe), crtc->config->pch_pfit.size);
4380         }
4381 }
4382
4383 void hsw_enable_ips(struct intel_crtc *crtc)
4384 {
4385         struct drm_device *dev = crtc->base.dev;
4386         struct drm_i915_private *dev_priv = to_i915(dev);
4387
4388         if (!crtc->config->ips_enabled)
4389                 return;
4390
4391         /*
4392          * We can only enable IPS after we enable a plane and wait for a vblank
4393          * This function is called from post_plane_update, which is run after
4394          * a vblank wait.
4395          */
4396
4397         assert_plane_enabled(dev_priv, crtc->plane);
4398         if (IS_BROADWELL(dev)) {
4399                 mutex_lock(&dev_priv->rps.hw_lock);
4400                 WARN_ON(sandybridge_pcode_write(dev_priv, DISPLAY_IPS_CONTROL, 0xc0000000));
4401                 mutex_unlock(&dev_priv->rps.hw_lock);
4402                 /* Quoting Art Runyan: "its not safe to expect any particular
4403                  * value in IPS_CTL bit 31 after enabling IPS through the
4404                  * mailbox." Moreover, the mailbox may return a bogus state,
4405                  * so we need to just enable it and continue on.
4406                  */
4407         } else {
4408                 I915_WRITE(IPS_CTL, IPS_ENABLE);
4409                 /* The bit only becomes 1 in the next vblank, so this wait here
4410                  * is essentially intel_wait_for_vblank. If we don't have this
4411                  * and don't wait for vblanks until the end of crtc_enable, then
4412                  * the HW state readout code will complain that the expected
4413                  * IPS_CTL value is not the one we read. */
4414                 if (intel_wait_for_register(dev_priv,
4415                                             IPS_CTL, IPS_ENABLE, IPS_ENABLE,
4416                                             50))
4417                         DRM_ERROR("Timed out waiting for IPS enable\n");
4418         }
4419 }
4420
4421 void hsw_disable_ips(struct intel_crtc *crtc)
4422 {
4423         struct drm_device *dev = crtc->base.dev;
4424         struct drm_i915_private *dev_priv = to_i915(dev);
4425
4426         if (!crtc->config->ips_enabled)
4427                 return;
4428
4429         assert_plane_enabled(dev_priv, crtc->plane);
4430         if (IS_BROADWELL(dev)) {
4431                 mutex_lock(&dev_priv->rps.hw_lock);
4432                 WARN_ON(sandybridge_pcode_write(dev_priv, DISPLAY_IPS_CONTROL, 0));
4433                 mutex_unlock(&dev_priv->rps.hw_lock);
4434                 /* wait for pcode to finish disabling IPS, which may take up to 42ms */
4435                 if (intel_wait_for_register(dev_priv,
4436                                             IPS_CTL, IPS_ENABLE, 0,
4437                                             42))
4438                         DRM_ERROR("Timed out waiting for IPS disable\n");
4439         } else {
4440                 I915_WRITE(IPS_CTL, 0);
4441                 POSTING_READ(IPS_CTL);
4442         }
4443
4444         /* We need to wait for a vblank before we can disable the plane. */
4445         intel_wait_for_vblank(dev, crtc->pipe);
4446 }
4447
4448 static void intel_crtc_dpms_overlay_disable(struct intel_crtc *intel_crtc)
4449 {
4450         if (intel_crtc->overlay) {
4451                 struct drm_device *dev = intel_crtc->base.dev;
4452                 struct drm_i915_private *dev_priv = to_i915(dev);
4453
4454                 mutex_lock(&dev->struct_mutex);
4455                 dev_priv->mm.interruptible = false;
4456                 (void) intel_overlay_switch_off(intel_crtc->overlay);
4457                 dev_priv->mm.interruptible = true;
4458                 mutex_unlock(&dev->struct_mutex);
4459         }
4460
4461         /* Let userspace switch the overlay on again. In most cases userspace
4462          * has to recompute where to put it anyway.
4463          */
4464 }
4465
4466 /**
4467  * intel_post_enable_primary - Perform operations after enabling primary plane
4468  * @crtc: the CRTC whose primary plane was just enabled
4469  *
4470  * Performs potentially sleeping operations that must be done after the primary
4471  * plane is enabled, such as updating FBC and IPS.  Note that this may be
4472  * called due to an explicit primary plane update, or due to an implicit
4473  * re-enable that is caused when a sprite plane is updated to no longer
4474  * completely hide the primary plane.
4475  */
4476 static void
4477 intel_post_enable_primary(struct drm_crtc *crtc)
4478 {
4479         struct drm_device *dev = crtc->dev;
4480         struct drm_i915_private *dev_priv = to_i915(dev);
4481         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4482         int pipe = intel_crtc->pipe;
4483
4484         /*
4485          * FIXME IPS should be fine as long as one plane is
4486          * enabled, but in practice it seems to have problems
4487          * when going from primary only to sprite only and vice
4488          * versa.
4489          */
4490         hsw_enable_ips(intel_crtc);
4491
4492         /*
4493          * Gen2 reports pipe underruns whenever all planes are disabled.
4494          * So don't enable underrun reporting before at least some planes
4495          * are enabled.
4496          * FIXME: Need to fix the logic to work when we turn off all planes
4497          * but leave the pipe running.
4498          */
4499         if (IS_GEN2(dev))
4500                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
4501
4502         /* Underruns don't always raise interrupts, so check manually. */
4503         intel_check_cpu_fifo_underruns(dev_priv);
4504         intel_check_pch_fifo_underruns(dev_priv);
4505 }
4506
4507 /* FIXME move all this to pre_plane_update() with proper state tracking */
4508 static void
4509 intel_pre_disable_primary(struct drm_crtc *crtc)
4510 {
4511         struct drm_device *dev = crtc->dev;
4512         struct drm_i915_private *dev_priv = to_i915(dev);
4513         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4514         int pipe = intel_crtc->pipe;
4515
4516         /*
4517          * Gen2 reports pipe underruns whenever all planes are disabled.
4518          * So diasble underrun reporting before all the planes get disabled.
4519          * FIXME: Need to fix the logic to work when we turn off all planes
4520          * but leave the pipe running.
4521          */
4522         if (IS_GEN2(dev))
4523                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
4524
4525         /*
4526          * FIXME IPS should be fine as long as one plane is
4527          * enabled, but in practice it seems to have problems
4528          * when going from primary only to sprite only and vice
4529          * versa.
4530          */
4531         hsw_disable_ips(intel_crtc);
4532 }
4533
4534 /* FIXME get rid of this and use pre_plane_update */
4535 static void
4536 intel_pre_disable_primary_noatomic(struct drm_crtc *crtc)
4537 {
4538         struct drm_device *dev = crtc->dev;
4539         struct drm_i915_private *dev_priv = to_i915(dev);
4540         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4541         int pipe = intel_crtc->pipe;
4542
4543         intel_pre_disable_primary(crtc);
4544
4545         /*
4546          * Vblank time updates from the shadow to live plane control register
4547          * are blocked if the memory self-refresh mode is active at that
4548          * moment. So to make sure the plane gets truly disabled, disable
4549          * first the self-refresh mode. The self-refresh enable bit in turn
4550          * will be checked/applied by the HW only at the next frame start
4551          * event which is after the vblank start event, so we need to have a
4552          * wait-for-vblank between disabling the plane and the pipe.
4553          */
4554         if (HAS_GMCH_DISPLAY(dev)) {
4555                 intel_set_memory_cxsr(dev_priv, false);
4556                 dev_priv->wm.vlv.cxsr = false;
4557                 intel_wait_for_vblank(dev, pipe);
4558         }
4559 }
4560
4561 static void intel_post_plane_update(struct intel_crtc_state *old_crtc_state)
4562 {
4563         struct intel_crtc *crtc = to_intel_crtc(old_crtc_state->base.crtc);
4564         struct drm_atomic_state *old_state = old_crtc_state->base.state;
4565         struct intel_crtc_state *pipe_config =
4566                 to_intel_crtc_state(crtc->base.state);
4567         struct drm_plane *primary = crtc->base.primary;
4568         struct drm_plane_state *old_pri_state =
4569                 drm_atomic_get_existing_plane_state(old_state, primary);
4570
4571         intel_frontbuffer_flip(to_i915(crtc->base.dev), pipe_config->fb_bits);
4572
4573         crtc->wm.cxsr_allowed = true;
4574
4575         if (pipe_config->update_wm_post && pipe_config->base.active)
4576                 intel_update_watermarks(&crtc->base);
4577
4578         if (old_pri_state) {
4579                 struct intel_plane_state *primary_state =
4580                         to_intel_plane_state(primary->state);
4581                 struct intel_plane_state *old_primary_state =
4582                         to_intel_plane_state(old_pri_state);
4583
4584                 intel_fbc_post_update(crtc);
4585
4586                 if (primary_state->base.visible &&
4587                     (needs_modeset(&pipe_config->base) ||
4588                      !old_primary_state->base.visible))
4589                         intel_post_enable_primary(&crtc->base);
4590         }
4591 }
4592
4593 static void intel_pre_plane_update(struct intel_crtc_state *old_crtc_state)
4594 {
4595         struct intel_crtc *crtc = to_intel_crtc(old_crtc_state->base.crtc);
4596         struct drm_device *dev = crtc->base.dev;
4597         struct drm_i915_private *dev_priv = to_i915(dev);
4598         struct intel_crtc_state *pipe_config =
4599                 to_intel_crtc_state(crtc->base.state);
4600         struct drm_atomic_state *old_state = old_crtc_state->base.state;
4601         struct drm_plane *primary = crtc->base.primary;
4602         struct drm_plane_state *old_pri_state =
4603                 drm_atomic_get_existing_plane_state(old_state, primary);
4604         bool modeset = needs_modeset(&pipe_config->base);
4605
4606         if (old_pri_state) {
4607                 struct intel_plane_state *primary_state =
4608                         to_intel_plane_state(primary->state);
4609                 struct intel_plane_state *old_primary_state =
4610                         to_intel_plane_state(old_pri_state);
4611
4612                 intel_fbc_pre_update(crtc, pipe_config, primary_state);
4613
4614                 if (old_primary_state->base.visible &&
4615                     (modeset || !primary_state->base.visible))
4616                         intel_pre_disable_primary(&crtc->base);
4617         }
4618
4619         if (pipe_config->disable_cxsr && HAS_GMCH_DISPLAY(dev)) {
4620                 crtc->wm.cxsr_allowed = false;
4621
4622                 /*
4623                  * Vblank time updates from the shadow to live plane control register
4624                  * are blocked if the memory self-refresh mode is active at that
4625                  * moment. So to make sure the plane gets truly disabled, disable
4626                  * first the self-refresh mode. The self-refresh enable bit in turn
4627                  * will be checked/applied by the HW only at the next frame start
4628                  * event which is after the vblank start event, so we need to have a
4629                  * wait-for-vblank between disabling the plane and the pipe.
4630                  */
4631                 if (old_crtc_state->base.active) {
4632                         intel_set_memory_cxsr(dev_priv, false);
4633                         dev_priv->wm.vlv.cxsr = false;
4634                         intel_wait_for_vblank(dev, crtc->pipe);
4635                 }
4636         }
4637
4638         /*
4639          * IVB workaround: must disable low power watermarks for at least
4640          * one frame before enabling scaling.  LP watermarks can be re-enabled
4641          * when scaling is disabled.
4642          *
4643          * WaCxSRDisabledForSpriteScaling:ivb
4644          */
4645         if (pipe_config->disable_lp_wm) {
4646                 ilk_disable_lp_wm(dev);
4647                 intel_wait_for_vblank(dev, crtc->pipe);
4648         }
4649
4650         /*
4651          * If we're doing a modeset, we're done.  No need to do any pre-vblank
4652          * watermark programming here.
4653          */
4654         if (needs_modeset(&pipe_config->base))
4655                 return;
4656
4657         /*
4658          * For platforms that support atomic watermarks, program the
4659          * 'intermediate' watermarks immediately.  On pre-gen9 platforms, these
4660          * will be the intermediate values that are safe for both pre- and
4661          * post- vblank; when vblank happens, the 'active' values will be set
4662          * to the final 'target' values and we'll do this again to get the
4663          * optimal watermarks.  For gen9+ platforms, the values we program here
4664          * will be the final target values which will get automatically latched
4665          * at vblank time; no further programming will be necessary.
4666          *
4667          * If a platform hasn't been transitioned to atomic watermarks yet,
4668          * we'll continue to update watermarks the old way, if flags tell
4669          * us to.
4670          */
4671         if (dev_priv->display.initial_watermarks != NULL)
4672                 dev_priv->display.initial_watermarks(pipe_config);
4673         else if (pipe_config->update_wm_pre)
4674                 intel_update_watermarks(&crtc->base);
4675 }
4676
4677 static void intel_crtc_disable_planes(struct drm_crtc *crtc, unsigned plane_mask)
4678 {
4679         struct drm_device *dev = crtc->dev;
4680         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4681         struct drm_plane *p;
4682         int pipe = intel_crtc->pipe;
4683
4684         intel_crtc_dpms_overlay_disable(intel_crtc);
4685
4686         drm_for_each_plane_mask(p, dev, plane_mask)
4687                 to_intel_plane(p)->disable_plane(p, crtc);
4688
4689         /*
4690          * FIXME: Once we grow proper nuclear flip support out of this we need
4691          * to compute the mask of flip planes precisely. For the time being
4692          * consider this a flip to a NULL plane.
4693          */
4694         intel_frontbuffer_flip(to_i915(dev), INTEL_FRONTBUFFER_ALL_MASK(pipe));
4695 }
4696
4697 static void ironlake_crtc_enable(struct drm_crtc *crtc)
4698 {
4699         struct drm_device *dev = crtc->dev;
4700         struct drm_i915_private *dev_priv = to_i915(dev);
4701         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4702         struct intel_encoder *encoder;
4703         int pipe = intel_crtc->pipe;
4704         struct intel_crtc_state *pipe_config =
4705                 to_intel_crtc_state(crtc->state);
4706
4707         if (WARN_ON(intel_crtc->active))
4708                 return;
4709
4710         /*
4711          * Sometimes spurious CPU pipe underruns happen during FDI
4712          * training, at least with VGA+HDMI cloning. Suppress them.
4713          *
4714          * On ILK we get an occasional spurious CPU pipe underruns
4715          * between eDP port A enable and vdd enable. Also PCH port
4716          * enable seems to result in the occasional CPU pipe underrun.
4717          *
4718          * Spurious PCH underruns also occur during PCH enabling.
4719          */
4720         if (intel_crtc->config->has_pch_encoder || IS_GEN5(dev_priv))
4721                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
4722         if (intel_crtc->config->has_pch_encoder)
4723                 intel_set_pch_fifo_underrun_reporting(dev_priv, pipe, false);
4724
4725         if (intel_crtc->config->has_pch_encoder)
4726                 intel_prepare_shared_dpll(intel_crtc);
4727
4728         if (intel_crtc_has_dp_encoder(intel_crtc->config))
4729                 intel_dp_set_m_n(intel_crtc, M1_N1);
4730
4731         intel_set_pipe_timings(intel_crtc);
4732         intel_set_pipe_src_size(intel_crtc);
4733
4734         if (intel_crtc->config->has_pch_encoder) {
4735                 intel_cpu_transcoder_set_m_n(intel_crtc,
4736                                      &intel_crtc->config->fdi_m_n, NULL);
4737         }
4738
4739         ironlake_set_pipeconf(crtc);
4740
4741         intel_crtc->active = true;
4742
4743         for_each_encoder_on_crtc(dev, crtc, encoder)
4744                 if (encoder->pre_enable)
4745                         encoder->pre_enable(encoder);
4746
4747         if (intel_crtc->config->has_pch_encoder) {
4748                 /* Note: FDI PLL enabling _must_ be done before we enable the
4749                  * cpu pipes, hence this is separate from all the other fdi/pch
4750                  * enabling. */
4751                 ironlake_fdi_pll_enable(intel_crtc);
4752         } else {
4753                 assert_fdi_tx_disabled(dev_priv, pipe);
4754                 assert_fdi_rx_disabled(dev_priv, pipe);
4755         }
4756
4757         ironlake_pfit_enable(intel_crtc);
4758
4759         /*
4760          * On ILK+ LUT must be loaded before the pipe is running but with
4761          * clocks enabled
4762          */
4763         intel_color_load_luts(&pipe_config->base);
4764
4765         if (dev_priv->display.initial_watermarks != NULL)
4766                 dev_priv->display.initial_watermarks(intel_crtc->config);
4767         intel_enable_pipe(intel_crtc);
4768
4769         if (intel_crtc->config->has_pch_encoder)
4770                 ironlake_pch_enable(crtc);
4771
4772         assert_vblank_disabled(crtc);
4773         drm_crtc_vblank_on(crtc);
4774
4775         for_each_encoder_on_crtc(dev, crtc, encoder)
4776                 encoder->enable(encoder);
4777
4778         if (HAS_PCH_CPT(dev))
4779                 cpt_verify_modeset(dev, intel_crtc->pipe);
4780
4781         /* Must wait for vblank to avoid spurious PCH FIFO underruns */
4782         if (intel_crtc->config->has_pch_encoder)
4783                 intel_wait_for_vblank(dev, pipe);
4784         intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
4785         intel_set_pch_fifo_underrun_reporting(dev_priv, pipe, true);
4786 }
4787
4788 /* IPS only exists on ULT machines and is tied to pipe A. */
4789 static bool hsw_crtc_supports_ips(struct intel_crtc *crtc)
4790 {
4791         return HAS_IPS(crtc->base.dev) && crtc->pipe == PIPE_A;
4792 }
4793
4794 static void haswell_crtc_enable(struct drm_crtc *crtc)
4795 {
4796         struct drm_device *dev = crtc->dev;
4797         struct drm_i915_private *dev_priv = to_i915(dev);
4798         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4799         struct intel_encoder *encoder;
4800         int pipe = intel_crtc->pipe, hsw_workaround_pipe;
4801         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
4802         struct intel_crtc_state *pipe_config =
4803                 to_intel_crtc_state(crtc->state);
4804
4805         if (WARN_ON(intel_crtc->active))
4806                 return;
4807
4808         if (intel_crtc->config->has_pch_encoder)
4809                 intel_set_pch_fifo_underrun_reporting(dev_priv, TRANSCODER_A,
4810                                                       false);
4811
4812         for_each_encoder_on_crtc(dev, crtc, encoder)
4813                 if (encoder->pre_pll_enable)
4814                         encoder->pre_pll_enable(encoder);
4815
4816         if (intel_crtc->config->shared_dpll)
4817                 intel_enable_shared_dpll(intel_crtc);
4818
4819         if (intel_crtc_has_dp_encoder(intel_crtc->config))
4820                 intel_dp_set_m_n(intel_crtc, M1_N1);
4821
4822         if (!transcoder_is_dsi(cpu_transcoder))
4823                 intel_set_pipe_timings(intel_crtc);
4824
4825         intel_set_pipe_src_size(intel_crtc);
4826
4827         if (cpu_transcoder != TRANSCODER_EDP &&
4828             !transcoder_is_dsi(cpu_transcoder)) {
4829                 I915_WRITE(PIPE_MULT(cpu_transcoder),
4830                            intel_crtc->config->pixel_multiplier - 1);
4831         }
4832
4833         if (intel_crtc->config->has_pch_encoder) {
4834                 intel_cpu_transcoder_set_m_n(intel_crtc,
4835                                      &intel_crtc->config->fdi_m_n, NULL);
4836         }
4837
4838         if (!transcoder_is_dsi(cpu_transcoder))
4839                 haswell_set_pipeconf(crtc);
4840
4841         haswell_set_pipemisc(crtc);
4842
4843         intel_color_set_csc(&pipe_config->base);
4844
4845         intel_crtc->active = true;
4846
4847         if (intel_crtc->config->has_pch_encoder)
4848                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
4849         else
4850                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
4851
4852         for_each_encoder_on_crtc(dev, crtc, encoder) {
4853                 if (encoder->pre_enable)
4854                         encoder->pre_enable(encoder);
4855         }
4856
4857         if (intel_crtc->config->has_pch_encoder)
4858                 dev_priv->display.fdi_link_train(crtc);
4859
4860         if (!transcoder_is_dsi(cpu_transcoder))
4861                 intel_ddi_enable_pipe_clock(intel_crtc);
4862
4863         if (INTEL_INFO(dev)->gen >= 9)
4864                 skylake_pfit_enable(intel_crtc);
4865         else
4866                 ironlake_pfit_enable(intel_crtc);
4867
4868         /*
4869          * On ILK+ LUT must be loaded before the pipe is running but with
4870          * clocks enabled
4871          */
4872         intel_color_load_luts(&pipe_config->base);
4873
4874         intel_ddi_set_pipe_settings(crtc);
4875         if (!transcoder_is_dsi(cpu_transcoder))
4876                 intel_ddi_enable_transcoder_func(crtc);
4877
4878         if (dev_priv->display.initial_watermarks != NULL)
4879                 dev_priv->display.initial_watermarks(pipe_config);
4880         else
4881                 intel_update_watermarks(crtc);
4882
4883         /* XXX: Do the pipe assertions at the right place for BXT DSI. */
4884         if (!transcoder_is_dsi(cpu_transcoder))
4885                 intel_enable_pipe(intel_crtc);
4886
4887         if (intel_crtc->config->has_pch_encoder)
4888                 lpt_pch_enable(crtc);
4889
4890         if (intel_crtc->config->dp_encoder_is_mst)
4891                 intel_ddi_set_vc_payload_alloc(crtc, true);
4892
4893         assert_vblank_disabled(crtc);
4894         drm_crtc_vblank_on(crtc);
4895
4896         for_each_encoder_on_crtc(dev, crtc, encoder) {
4897                 encoder->enable(encoder);
4898                 intel_opregion_notify_encoder(encoder, true);
4899         }
4900
4901         if (intel_crtc->config->has_pch_encoder) {
4902                 intel_wait_for_vblank(dev, pipe);
4903                 intel_wait_for_vblank(dev, pipe);
4904                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
4905                 intel_set_pch_fifo_underrun_reporting(dev_priv, TRANSCODER_A,
4906                                                       true);
4907         }
4908
4909         /* If we change the relative order between pipe/planes enabling, we need
4910          * to change the workaround. */
4911         hsw_workaround_pipe = pipe_config->hsw_workaround_pipe;
4912         if (IS_HASWELL(dev) && hsw_workaround_pipe != INVALID_PIPE) {
4913                 intel_wait_for_vblank(dev, hsw_workaround_pipe);
4914                 intel_wait_for_vblank(dev, hsw_workaround_pipe);
4915         }
4916 }
4917
4918 static void ironlake_pfit_disable(struct intel_crtc *crtc, bool force)
4919 {
4920         struct drm_device *dev = crtc->base.dev;
4921         struct drm_i915_private *dev_priv = to_i915(dev);
4922         int pipe = crtc->pipe;
4923
4924         /* To avoid upsetting the power well on haswell only disable the pfit if
4925          * it's in use. The hw state code will make sure we get this right. */
4926         if (force || crtc->config->pch_pfit.enabled) {
4927                 I915_WRITE(PF_CTL(pipe), 0);
4928                 I915_WRITE(PF_WIN_POS(pipe), 0);
4929                 I915_WRITE(PF_WIN_SZ(pipe), 0);
4930         }
4931 }
4932
4933 static void ironlake_crtc_disable(struct drm_crtc *crtc)
4934 {
4935         struct drm_device *dev = crtc->dev;
4936         struct drm_i915_private *dev_priv = to_i915(dev);
4937         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4938         struct intel_encoder *encoder;
4939         int pipe = intel_crtc->pipe;
4940
4941         /*
4942          * Sometimes spurious CPU pipe underruns happen when the
4943          * pipe is already disabled, but FDI RX/TX is still enabled.
4944          * Happens at least with VGA+HDMI cloning. Suppress them.
4945          */
4946         if (intel_crtc->config->has_pch_encoder) {
4947                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
4948                 intel_set_pch_fifo_underrun_reporting(dev_priv, pipe, false);
4949         }
4950
4951         for_each_encoder_on_crtc(dev, crtc, encoder)
4952                 encoder->disable(encoder);
4953
4954         drm_crtc_vblank_off(crtc);
4955         assert_vblank_disabled(crtc);
4956
4957         intel_disable_pipe(intel_crtc);
4958
4959         ironlake_pfit_disable(intel_crtc, false);
4960
4961         if (intel_crtc->config->has_pch_encoder)
4962                 ironlake_fdi_disable(crtc);
4963
4964         for_each_encoder_on_crtc(dev, crtc, encoder)
4965                 if (encoder->post_disable)
4966                         encoder->post_disable(encoder);
4967
4968         if (intel_crtc->config->has_pch_encoder) {
4969                 ironlake_disable_pch_transcoder(dev_priv, pipe);
4970
4971                 if (HAS_PCH_CPT(dev)) {
4972                         i915_reg_t reg;
4973                         u32 temp;
4974
4975                         /* disable TRANS_DP_CTL */
4976                         reg = TRANS_DP_CTL(pipe);
4977                         temp = I915_READ(reg);
4978                         temp &= ~(TRANS_DP_OUTPUT_ENABLE |
4979                                   TRANS_DP_PORT_SEL_MASK);
4980                         temp |= TRANS_DP_PORT_SEL_NONE;
4981                         I915_WRITE(reg, temp);
4982
4983                         /* disable DPLL_SEL */
4984                         temp = I915_READ(PCH_DPLL_SEL);
4985                         temp &= ~(TRANS_DPLL_ENABLE(pipe) | TRANS_DPLLB_SEL(pipe));
4986                         I915_WRITE(PCH_DPLL_SEL, temp);
4987                 }
4988
4989                 ironlake_fdi_pll_disable(intel_crtc);
4990         }
4991
4992         intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
4993         intel_set_pch_fifo_underrun_reporting(dev_priv, pipe, true);
4994 }
4995
4996 static void haswell_crtc_disable(struct drm_crtc *crtc)
4997 {
4998         struct drm_device *dev = crtc->dev;
4999         struct drm_i915_private *dev_priv = to_i915(dev);
5000         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5001         struct intel_encoder *encoder;
5002         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
5003
5004         if (intel_crtc->config->has_pch_encoder)
5005                 intel_set_pch_fifo_underrun_reporting(dev_priv, TRANSCODER_A,
5006                                                       false);
5007
5008         for_each_encoder_on_crtc(dev, crtc, encoder) {
5009                 intel_opregion_notify_encoder(encoder, false);
5010                 encoder->disable(encoder);
5011         }
5012
5013         drm_crtc_vblank_off(crtc);
5014         assert_vblank_disabled(crtc);
5015
5016         /* XXX: Do the pipe assertions at the right place for BXT DSI. */
5017         if (!transcoder_is_dsi(cpu_transcoder))
5018                 intel_disable_pipe(intel_crtc);
5019
5020         if (intel_crtc->config->dp_encoder_is_mst)
5021                 intel_ddi_set_vc_payload_alloc(crtc, false);
5022
5023         if (!transcoder_is_dsi(cpu_transcoder))
5024                 intel_ddi_disable_transcoder_func(dev_priv, cpu_transcoder);
5025
5026         if (INTEL_INFO(dev)->gen >= 9)
5027                 skylake_scaler_disable(intel_crtc);
5028         else
5029                 ironlake_pfit_disable(intel_crtc, false);
5030
5031         if (!transcoder_is_dsi(cpu_transcoder))
5032                 intel_ddi_disable_pipe_clock(intel_crtc);
5033
5034         for_each_encoder_on_crtc(dev, crtc, encoder)
5035                 if (encoder->post_disable)
5036                         encoder->post_disable(encoder);
5037
5038         if (intel_crtc->config->has_pch_encoder) {
5039                 lpt_disable_pch_transcoder(dev_priv);
5040                 lpt_disable_iclkip(dev_priv);
5041                 intel_ddi_fdi_disable(crtc);
5042
5043                 intel_set_pch_fifo_underrun_reporting(dev_priv, TRANSCODER_A,
5044                                                       true);
5045         }
5046 }
5047
5048 static void i9xx_pfit_enable(struct intel_crtc *crtc)
5049 {
5050         struct drm_device *dev = crtc->base.dev;
5051         struct drm_i915_private *dev_priv = to_i915(dev);
5052         struct intel_crtc_state *pipe_config = crtc->config;
5053
5054         if (!pipe_config->gmch_pfit.control)
5055                 return;
5056
5057         /*
5058          * The panel fitter should only be adjusted whilst the pipe is disabled,
5059          * according to register description and PRM.
5060          */
5061         WARN_ON(I915_READ(PFIT_CONTROL) & PFIT_ENABLE);
5062         assert_pipe_disabled(dev_priv, crtc->pipe);
5063
5064         I915_WRITE(PFIT_PGM_RATIOS, pipe_config->gmch_pfit.pgm_ratios);
5065         I915_WRITE(PFIT_CONTROL, pipe_config->gmch_pfit.control);
5066
5067         /* Border color in case we don't scale up to the full screen. Black by
5068          * default, change to something else for debugging. */
5069         I915_WRITE(BCLRPAT(crtc->pipe), 0);
5070 }
5071
5072 static enum intel_display_power_domain port_to_power_domain(enum port port)
5073 {
5074         switch (port) {
5075         case PORT_A:
5076                 return POWER_DOMAIN_PORT_DDI_A_LANES;
5077         case PORT_B:
5078                 return POWER_DOMAIN_PORT_DDI_B_LANES;
5079         case PORT_C:
5080                 return POWER_DOMAIN_PORT_DDI_C_LANES;
5081         case PORT_D:
5082                 return POWER_DOMAIN_PORT_DDI_D_LANES;
5083         case PORT_E:
5084                 return POWER_DOMAIN_PORT_DDI_E_LANES;
5085         default:
5086                 MISSING_CASE(port);
5087                 return POWER_DOMAIN_PORT_OTHER;
5088         }
5089 }
5090
5091 static enum intel_display_power_domain port_to_aux_power_domain(enum port port)
5092 {
5093         switch (port) {
5094         case PORT_A:
5095                 return POWER_DOMAIN_AUX_A;
5096         case PORT_B:
5097                 return POWER_DOMAIN_AUX_B;
5098         case PORT_C:
5099                 return POWER_DOMAIN_AUX_C;
5100         case PORT_D:
5101                 return POWER_DOMAIN_AUX_D;
5102         case PORT_E:
5103                 /* FIXME: Check VBT for actual wiring of PORT E */
5104                 return POWER_DOMAIN_AUX_D;
5105         default:
5106                 MISSING_CASE(port);
5107                 return POWER_DOMAIN_AUX_A;
5108         }
5109 }
5110
5111 enum intel_display_power_domain
5112 intel_display_port_power_domain(struct intel_encoder *intel_encoder)
5113 {
5114         struct drm_device *dev = intel_encoder->base.dev;
5115         struct intel_digital_port *intel_dig_port;
5116
5117         switch (intel_encoder->type) {
5118         case INTEL_OUTPUT_UNKNOWN:
5119                 /* Only DDI platforms should ever use this output type */
5120                 WARN_ON_ONCE(!HAS_DDI(dev));
5121         case INTEL_OUTPUT_DP:
5122         case INTEL_OUTPUT_HDMI:
5123         case INTEL_OUTPUT_EDP:
5124                 intel_dig_port = enc_to_dig_port(&intel_encoder->base);
5125                 return port_to_power_domain(intel_dig_port->port);
5126         case INTEL_OUTPUT_DP_MST:
5127                 intel_dig_port = enc_to_mst(&intel_encoder->base)->primary;
5128                 return port_to_power_domain(intel_dig_port->port);
5129         case INTEL_OUTPUT_ANALOG:
5130                 return POWER_DOMAIN_PORT_CRT;
5131         case INTEL_OUTPUT_DSI:
5132                 return POWER_DOMAIN_PORT_DSI;
5133         default:
5134                 return POWER_DOMAIN_PORT_OTHER;
5135         }
5136 }
5137
5138 enum intel_display_power_domain
5139 intel_display_port_aux_power_domain(struct intel_encoder *intel_encoder)
5140 {
5141         struct drm_device *dev = intel_encoder->base.dev;
5142         struct intel_digital_port *intel_dig_port;
5143
5144         switch (intel_encoder->type) {
5145         case INTEL_OUTPUT_UNKNOWN:
5146         case INTEL_OUTPUT_HDMI:
5147                 /*
5148                  * Only DDI platforms should ever use these output types.
5149                  * We can get here after the HDMI detect code has already set
5150                  * the type of the shared encoder. Since we can't be sure
5151                  * what's the status of the given connectors, play safe and
5152                  * run the DP detection too.
5153                  */
5154                 WARN_ON_ONCE(!HAS_DDI(dev));
5155         case INTEL_OUTPUT_DP:
5156         case INTEL_OUTPUT_EDP:
5157                 intel_dig_port = enc_to_dig_port(&intel_encoder->base);
5158                 return port_to_aux_power_domain(intel_dig_port->port);
5159         case INTEL_OUTPUT_DP_MST:
5160                 intel_dig_port = enc_to_mst(&intel_encoder->base)->primary;
5161                 return port_to_aux_power_domain(intel_dig_port->port);
5162         default:
5163                 MISSING_CASE(intel_encoder->type);
5164                 return POWER_DOMAIN_AUX_A;
5165         }
5166 }
5167
5168 static unsigned long get_crtc_power_domains(struct drm_crtc *crtc,
5169                                             struct intel_crtc_state *crtc_state)
5170 {
5171         struct drm_device *dev = crtc->dev;
5172         struct drm_encoder *encoder;
5173         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5174         enum pipe pipe = intel_crtc->pipe;
5175         unsigned long mask;
5176         enum transcoder transcoder = crtc_state->cpu_transcoder;
5177
5178         if (!crtc_state->base.active)
5179                 return 0;
5180
5181         mask = BIT(POWER_DOMAIN_PIPE(pipe));
5182         mask |= BIT(POWER_DOMAIN_TRANSCODER(transcoder));
5183         if (crtc_state->pch_pfit.enabled ||
5184             crtc_state->pch_pfit.force_thru)
5185                 mask |= BIT(POWER_DOMAIN_PIPE_PANEL_FITTER(pipe));
5186
5187         drm_for_each_encoder_mask(encoder, dev, crtc_state->base.encoder_mask) {
5188                 struct intel_encoder *intel_encoder = to_intel_encoder(encoder);
5189
5190                 mask |= BIT(intel_display_port_power_domain(intel_encoder));
5191         }
5192
5193         if (crtc_state->shared_dpll)
5194                 mask |= BIT(POWER_DOMAIN_PLLS);
5195
5196         return mask;
5197 }
5198
5199 static unsigned long
5200 modeset_get_crtc_power_domains(struct drm_crtc *crtc,
5201                                struct intel_crtc_state *crtc_state)
5202 {
5203         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
5204         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5205         enum intel_display_power_domain domain;
5206         unsigned long domains, new_domains, old_domains;
5207
5208         old_domains = intel_crtc->enabled_power_domains;
5209         intel_crtc->enabled_power_domains = new_domains =
5210                 get_crtc_power_domains(crtc, crtc_state);
5211
5212         domains = new_domains & ~old_domains;
5213
5214         for_each_power_domain(domain, domains)
5215                 intel_display_power_get(dev_priv, domain);
5216
5217         return old_domains & ~new_domains;
5218 }
5219
5220 static void modeset_put_power_domains(struct drm_i915_private *dev_priv,
5221                                       unsigned long domains)
5222 {
5223         enum intel_display_power_domain domain;
5224
5225         for_each_power_domain(domain, domains)
5226                 intel_display_power_put(dev_priv, domain);
5227 }
5228
5229 static int intel_compute_max_dotclk(struct drm_i915_private *dev_priv)
5230 {
5231         int max_cdclk_freq = dev_priv->max_cdclk_freq;
5232
5233         if (INTEL_INFO(dev_priv)->gen >= 9 ||
5234             IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv))
5235                 return max_cdclk_freq;
5236         else if (IS_CHERRYVIEW(dev_priv))
5237                 return max_cdclk_freq*95/100;
5238         else if (INTEL_INFO(dev_priv)->gen < 4)
5239                 return 2*max_cdclk_freq*90/100;
5240         else
5241                 return max_cdclk_freq*90/100;
5242 }
5243
5244 static int skl_calc_cdclk(int max_pixclk, int vco);
5245
5246 static void intel_update_max_cdclk(struct drm_device *dev)
5247 {
5248         struct drm_i915_private *dev_priv = to_i915(dev);
5249
5250         if (IS_SKYLAKE(dev) || IS_KABYLAKE(dev)) {
5251                 u32 limit = I915_READ(SKL_DFSM) & SKL_DFSM_CDCLK_LIMIT_MASK;
5252                 int max_cdclk, vco;
5253
5254                 vco = dev_priv->skl_preferred_vco_freq;
5255                 WARN_ON(vco != 8100000 && vco != 8640000);
5256
5257                 /*
5258                  * Use the lower (vco 8640) cdclk values as a
5259                  * first guess. skl_calc_cdclk() will correct it
5260                  * if the preferred vco is 8100 instead.
5261                  */
5262                 if (limit == SKL_DFSM_CDCLK_LIMIT_675)
5263                         max_cdclk = 617143;
5264                 else if (limit == SKL_DFSM_CDCLK_LIMIT_540)
5265                         max_cdclk = 540000;
5266                 else if (limit == SKL_DFSM_CDCLK_LIMIT_450)
5267                         max_cdclk = 432000;
5268                 else
5269                         max_cdclk = 308571;
5270
5271                 dev_priv->max_cdclk_freq = skl_calc_cdclk(max_cdclk, vco);
5272         } else if (IS_BROXTON(dev)) {
5273                 dev_priv->max_cdclk_freq = 624000;
5274         } else if (IS_BROADWELL(dev))  {
5275                 /*
5276                  * FIXME with extra cooling we can allow
5277                  * 540 MHz for ULX and 675 Mhz for ULT.
5278                  * How can we know if extra cooling is
5279                  * available? PCI ID, VTB, something else?
5280                  */
5281                 if (I915_READ(FUSE_STRAP) & HSW_CDCLK_LIMIT)
5282                         dev_priv->max_cdclk_freq = 450000;
5283                 else if (IS_BDW_ULX(dev))
5284                         dev_priv->max_cdclk_freq = 450000;
5285                 else if (IS_BDW_ULT(dev))
5286                         dev_priv->max_cdclk_freq = 540000;
5287                 else
5288                         dev_priv->max_cdclk_freq = 675000;
5289         } else if (IS_CHERRYVIEW(dev)) {
5290                 dev_priv->max_cdclk_freq = 320000;
5291         } else if (IS_VALLEYVIEW(dev)) {
5292                 dev_priv->max_cdclk_freq = 400000;
5293         } else {
5294                 /* otherwise assume cdclk is fixed */
5295                 dev_priv->max_cdclk_freq = dev_priv->cdclk_freq;
5296         }
5297
5298         dev_priv->max_dotclk_freq = intel_compute_max_dotclk(dev_priv);
5299
5300         DRM_DEBUG_DRIVER("Max CD clock rate: %d kHz\n",
5301                          dev_priv->max_cdclk_freq);
5302
5303         DRM_DEBUG_DRIVER("Max dotclock rate: %d kHz\n",
5304                          dev_priv->max_dotclk_freq);
5305 }
5306
5307 static void intel_update_cdclk(struct drm_device *dev)
5308 {
5309         struct drm_i915_private *dev_priv = to_i915(dev);
5310
5311         dev_priv->cdclk_freq = dev_priv->display.get_display_clock_speed(dev);
5312
5313         if (INTEL_GEN(dev_priv) >= 9)
5314                 DRM_DEBUG_DRIVER("Current CD clock rate: %d kHz, VCO: %d kHz, ref: %d kHz\n",
5315                                  dev_priv->cdclk_freq, dev_priv->cdclk_pll.vco,
5316                                  dev_priv->cdclk_pll.ref);
5317         else
5318                 DRM_DEBUG_DRIVER("Current CD clock rate: %d kHz\n",
5319                                  dev_priv->cdclk_freq);
5320
5321         /*
5322          * 9:0 CMBUS [sic] CDCLK frequency (cdfreq):
5323          * Programmng [sic] note: bit[9:2] should be programmed to the number
5324          * of cdclk that generates 4MHz reference clock freq which is used to
5325          * generate GMBus clock. This will vary with the cdclk freq.
5326          */
5327         if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
5328                 I915_WRITE(GMBUSFREQ_VLV, DIV_ROUND_UP(dev_priv->cdclk_freq, 1000));
5329 }
5330
5331 /* convert from kHz to .1 fixpoint MHz with -1MHz offset */
5332 static int skl_cdclk_decimal(int cdclk)
5333 {
5334         return DIV_ROUND_CLOSEST(cdclk - 1000, 500);
5335 }
5336
5337 static int bxt_de_pll_vco(struct drm_i915_private *dev_priv, int cdclk)
5338 {
5339         int ratio;
5340
5341         if (cdclk == dev_priv->cdclk_pll.ref)
5342                 return 0;
5343
5344         switch (cdclk) {
5345         default:
5346                 MISSING_CASE(cdclk);
5347         case 144000:
5348         case 288000:
5349         case 384000:
5350         case 576000:
5351                 ratio = 60;
5352                 break;
5353         case 624000:
5354                 ratio = 65;
5355                 break;
5356         }
5357
5358         return dev_priv->cdclk_pll.ref * ratio;
5359 }
5360
5361 static void bxt_de_pll_disable(struct drm_i915_private *dev_priv)
5362 {
5363         I915_WRITE(BXT_DE_PLL_ENABLE, 0);
5364
5365         /* Timeout 200us */
5366         if (intel_wait_for_register(dev_priv,
5367                                     BXT_DE_PLL_ENABLE, BXT_DE_PLL_LOCK, 0,
5368                                     1))
5369                 DRM_ERROR("timeout waiting for DE PLL unlock\n");
5370
5371         dev_priv->cdclk_pll.vco = 0;
5372 }
5373
5374 static void bxt_de_pll_enable(struct drm_i915_private *dev_priv, int vco)
5375 {
5376         int ratio = DIV_ROUND_CLOSEST(vco, dev_priv->cdclk_pll.ref);
5377         u32 val;
5378
5379         val = I915_READ(BXT_DE_PLL_CTL);
5380         val &= ~BXT_DE_PLL_RATIO_MASK;
5381         val |= BXT_DE_PLL_RATIO(ratio);
5382         I915_WRITE(BXT_DE_PLL_CTL, val);
5383
5384         I915_WRITE(BXT_DE_PLL_ENABLE, BXT_DE_PLL_PLL_ENABLE);
5385
5386         /* Timeout 200us */
5387         if (intel_wait_for_register(dev_priv,
5388                                     BXT_DE_PLL_ENABLE,
5389                                     BXT_DE_PLL_LOCK,
5390                                     BXT_DE_PLL_LOCK,
5391                                     1))
5392                 DRM_ERROR("timeout waiting for DE PLL lock\n");
5393
5394         dev_priv->cdclk_pll.vco = vco;
5395 }
5396
5397 static void bxt_set_cdclk(struct drm_i915_private *dev_priv, int cdclk)
5398 {
5399         u32 val, divider;
5400         int vco, ret;
5401
5402         vco = bxt_de_pll_vco(dev_priv, cdclk);
5403
5404         DRM_DEBUG_DRIVER("Changing CDCLK to %d kHz (VCO %d kHz)\n", cdclk, vco);
5405
5406         /* cdclk = vco / 2 / div{1,1.5,2,4} */
5407         switch (DIV_ROUND_CLOSEST(vco, cdclk)) {
5408         case 8:
5409                 divider = BXT_CDCLK_CD2X_DIV_SEL_4;
5410                 break;
5411         case 4:
5412                 divider = BXT_CDCLK_CD2X_DIV_SEL_2;
5413                 break;
5414         case 3:
5415                 divider = BXT_CDCLK_CD2X_DIV_SEL_1_5;
5416                 break;
5417         case 2:
5418                 divider = BXT_CDCLK_CD2X_DIV_SEL_1;
5419                 break;
5420         default:
5421                 WARN_ON(cdclk != dev_priv->cdclk_pll.ref);
5422                 WARN_ON(vco != 0);
5423
5424                 divider = BXT_CDCLK_CD2X_DIV_SEL_1;
5425                 break;
5426         }
5427
5428         /* Inform power controller of upcoming frequency change */
5429         mutex_lock(&dev_priv->rps.hw_lock);
5430         ret = sandybridge_pcode_write(dev_priv, HSW_PCODE_DE_WRITE_FREQ_REQ,
5431                                       0x80000000);
5432         mutex_unlock(&dev_priv->rps.hw_lock);
5433
5434         if (ret) {
5435                 DRM_ERROR("PCode CDCLK freq change notify failed (err %d, freq %d)\n",
5436                           ret, cdclk);
5437                 return;
5438         }
5439
5440         if (dev_priv->cdclk_pll.vco != 0 &&
5441             dev_priv->cdclk_pll.vco != vco)
5442                 bxt_de_pll_disable(dev_priv);
5443
5444         if (dev_priv->cdclk_pll.vco != vco)
5445                 bxt_de_pll_enable(dev_priv, vco);
5446
5447         val = divider | skl_cdclk_decimal(cdclk);
5448         /*
5449          * FIXME if only the cd2x divider needs changing, it could be done
5450          * without shutting off the pipe (if only one pipe is active).
5451          */
5452         val |= BXT_CDCLK_CD2X_PIPE_NONE;
5453         /*
5454          * Disable SSA Precharge when CD clock frequency < 500 MHz,
5455          * enable otherwise.
5456          */
5457         if (cdclk >= 500000)
5458                 val |= BXT_CDCLK_SSA_PRECHARGE_ENABLE;
5459         I915_WRITE(CDCLK_CTL, val);
5460
5461         mutex_lock(&dev_priv->rps.hw_lock);
5462         ret = sandybridge_pcode_write(dev_priv, HSW_PCODE_DE_WRITE_FREQ_REQ,
5463                                       DIV_ROUND_UP(cdclk, 25000));
5464         mutex_unlock(&dev_priv->rps.hw_lock);
5465
5466         if (ret) {
5467                 DRM_ERROR("PCode CDCLK freq set failed, (err %d, freq %d)\n",
5468                           ret, cdclk);
5469                 return;
5470         }
5471
5472         intel_update_cdclk(&dev_priv->drm);
5473 }
5474
5475 static void bxt_sanitize_cdclk(struct drm_i915_private *dev_priv)
5476 {
5477         u32 cdctl, expected;
5478
5479         intel_update_cdclk(&dev_priv->drm);
5480
5481         if (dev_priv->cdclk_pll.vco == 0 ||
5482             dev_priv->cdclk_freq == dev_priv->cdclk_pll.ref)
5483                 goto sanitize;
5484
5485         /* DPLL okay; verify the cdclock
5486          *
5487          * Some BIOS versions leave an incorrect decimal frequency value and
5488          * set reserved MBZ bits in CDCLK_CTL at least during exiting from S4,
5489          * so sanitize this register.
5490          */
5491         cdctl = I915_READ(CDCLK_CTL);
5492         /*
5493          * Let's ignore the pipe field, since BIOS could have configured the
5494          * dividers both synching to an active pipe, or asynchronously
5495          * (PIPE_NONE).
5496          */
5497         cdctl &= ~BXT_CDCLK_CD2X_PIPE_NONE;
5498
5499         expected = (cdctl & BXT_CDCLK_CD2X_DIV_SEL_MASK) |
5500                    skl_cdclk_decimal(dev_priv->cdclk_freq);
5501         /*
5502          * Disable SSA Precharge when CD clock frequency < 500 MHz,
5503          * enable otherwise.
5504          */
5505         if (dev_priv->cdclk_freq >= 500000)
5506                 expected |= BXT_CDCLK_SSA_PRECHARGE_ENABLE;
5507
5508         if (cdctl == expected)
5509                 /* All well; nothing to sanitize */
5510                 return;
5511
5512 sanitize:
5513         DRM_DEBUG_KMS("Sanitizing cdclk programmed by pre-os\n");
5514
5515         /* force cdclk programming */
5516         dev_priv->cdclk_freq = 0;
5517
5518         /* force full PLL disable + enable */
5519         dev_priv->cdclk_pll.vco = -1;
5520 }
5521
5522 void bxt_init_cdclk(struct drm_i915_private *dev_priv)
5523 {
5524         bxt_sanitize_cdclk(dev_priv);
5525
5526         if (dev_priv->cdclk_freq != 0 && dev_priv->cdclk_pll.vco != 0)
5527                 return;
5528
5529         /*
5530          * FIXME:
5531          * - The initial CDCLK needs to be read from VBT.
5532          *   Need to make this change after VBT has changes for BXT.
5533          */
5534         bxt_set_cdclk(dev_priv, bxt_calc_cdclk(0));
5535 }
5536
5537 void bxt_uninit_cdclk(struct drm_i915_private *dev_priv)
5538 {
5539         bxt_set_cdclk(dev_priv, dev_priv->cdclk_pll.ref);
5540 }
5541
5542 static int skl_calc_cdclk(int max_pixclk, int vco)
5543 {
5544         if (vco == 8640000) {
5545                 if (max_pixclk > 540000)
5546                         return 617143;
5547                 else if (max_pixclk > 432000)
5548                         return 540000;
5549                 else if (max_pixclk > 308571)
5550                         return 432000;
5551                 else
5552                         return 308571;
5553         } else {
5554                 if (max_pixclk > 540000)
5555                         return 675000;
5556                 else if (max_pixclk > 450000)
5557                         return 540000;
5558                 else if (max_pixclk > 337500)
5559                         return 450000;
5560                 else
5561                         return 337500;
5562         }
5563 }
5564
5565 static void
5566 skl_dpll0_update(struct drm_i915_private *dev_priv)
5567 {
5568         u32 val;
5569
5570         dev_priv->cdclk_pll.ref = 24000;
5571         dev_priv->cdclk_pll.vco = 0;
5572
5573         val = I915_READ(LCPLL1_CTL);
5574         if ((val & LCPLL_PLL_ENABLE) == 0)
5575                 return;
5576
5577         if (WARN_ON((val & LCPLL_PLL_LOCK) == 0))
5578                 return;
5579
5580         val = I915_READ(DPLL_CTRL1);
5581
5582         if (WARN_ON((val & (DPLL_CTRL1_HDMI_MODE(SKL_DPLL0) |
5583                             DPLL_CTRL1_SSC(SKL_DPLL0) |
5584                             DPLL_CTRL1_OVERRIDE(SKL_DPLL0))) !=
5585                     DPLL_CTRL1_OVERRIDE(SKL_DPLL0)))
5586                 return;
5587
5588         switch (val & DPLL_CTRL1_LINK_RATE_MASK(SKL_DPLL0)) {
5589         case DPLL_CTRL1_LINK_RATE(DPLL_CTRL1_LINK_RATE_810, SKL_DPLL0):
5590         case DPLL_CTRL1_LINK_RATE(DPLL_CTRL1_LINK_RATE_1350, SKL_DPLL0):
5591         case DPLL_CTRL1_LINK_RATE(DPLL_CTRL1_LINK_RATE_1620, SKL_DPLL0):
5592         case DPLL_CTRL1_LINK_RATE(DPLL_CTRL1_LINK_RATE_2700, SKL_DPLL0):
5593                 dev_priv->cdclk_pll.vco = 8100000;
5594                 break;
5595         case DPLL_CTRL1_LINK_RATE(DPLL_CTRL1_LINK_RATE_1080, SKL_DPLL0):
5596         case DPLL_CTRL1_LINK_RATE(DPLL_CTRL1_LINK_RATE_2160, SKL_DPLL0):
5597                 dev_priv->cdclk_pll.vco = 8640000;
5598                 break;
5599         default:
5600                 MISSING_CASE(val & DPLL_CTRL1_LINK_RATE_MASK(SKL_DPLL0));
5601                 break;
5602         }
5603 }
5604
5605 void skl_set_preferred_cdclk_vco(struct drm_i915_private *dev_priv, int vco)
5606 {
5607         bool changed = dev_priv->skl_preferred_vco_freq != vco;
5608
5609         dev_priv->skl_preferred_vco_freq = vco;
5610
5611         if (changed)
5612                 intel_update_max_cdclk(&dev_priv->drm);
5613 }
5614
5615 static void
5616 skl_dpll0_enable(struct drm_i915_private *dev_priv, int vco)
5617 {
5618         int min_cdclk = skl_calc_cdclk(0, vco);
5619         u32 val;
5620
5621         WARN_ON(vco != 8100000 && vco != 8640000);
5622
5623         /* select the minimum CDCLK before enabling DPLL 0 */
5624         val = CDCLK_FREQ_337_308 | skl_cdclk_decimal(min_cdclk);
5625         I915_WRITE(CDCLK_CTL, val);
5626         POSTING_READ(CDCLK_CTL);
5627
5628         /*
5629          * We always enable DPLL0 with the lowest link rate possible, but still
5630          * taking into account the VCO required to operate the eDP panel at the
5631          * desired frequency. The usual DP link rates operate with a VCO of
5632          * 8100 while the eDP 1.4 alternate link rates need a VCO of 8640.
5633          * The modeset code is responsible for the selection of the exact link
5634          * rate later on, with the constraint of choosing a frequency that
5635          * works with vco.
5636          */
5637         val = I915_READ(DPLL_CTRL1);
5638
5639         val &= ~(DPLL_CTRL1_HDMI_MODE(SKL_DPLL0) | DPLL_CTRL1_SSC(SKL_DPLL0) |
5640                  DPLL_CTRL1_LINK_RATE_MASK(SKL_DPLL0));
5641         val |= DPLL_CTRL1_OVERRIDE(SKL_DPLL0);
5642         if (vco == 8640000)
5643                 val |= DPLL_CTRL1_LINK_RATE(DPLL_CTRL1_LINK_RATE_1080,
5644                                             SKL_DPLL0);
5645         else
5646                 val |= DPLL_CTRL1_LINK_RATE(DPLL_CTRL1_LINK_RATE_810,
5647                                             SKL_DPLL0);
5648
5649         I915_WRITE(DPLL_CTRL1, val);
5650         POSTING_READ(DPLL_CTRL1);
5651
5652         I915_WRITE(LCPLL1_CTL, I915_READ(LCPLL1_CTL) | LCPLL_PLL_ENABLE);
5653
5654         if (intel_wait_for_register(dev_priv,
5655                                     LCPLL1_CTL, LCPLL_PLL_LOCK, LCPLL_PLL_LOCK,
5656                                     5))
5657                 DRM_ERROR("DPLL0 not locked\n");
5658
5659         dev_priv->cdclk_pll.vco = vco;
5660
5661         /* We'll want to keep using the current vco from now on. */
5662         skl_set_preferred_cdclk_vco(dev_priv, vco);
5663 }
5664
5665 static void
5666 skl_dpll0_disable(struct drm_i915_private *dev_priv)
5667 {
5668         I915_WRITE(LCPLL1_CTL, I915_READ(LCPLL1_CTL) & ~LCPLL_PLL_ENABLE);
5669         if (intel_wait_for_register(dev_priv,
5670                                    LCPLL1_CTL, LCPLL_PLL_LOCK, 0,
5671                                    1))
5672                 DRM_ERROR("Couldn't disable DPLL0\n");
5673
5674         dev_priv->cdclk_pll.vco = 0;
5675 }
5676
5677 static bool skl_cdclk_pcu_ready(struct drm_i915_private *dev_priv)
5678 {
5679         int ret;
5680         u32 val;
5681
5682         /* inform PCU we want to change CDCLK */
5683         val = SKL_CDCLK_PREPARE_FOR_CHANGE;
5684         mutex_lock(&dev_priv->rps.hw_lock);
5685         ret = sandybridge_pcode_read(dev_priv, SKL_PCODE_CDCLK_CONTROL, &val);
5686         mutex_unlock(&dev_priv->rps.hw_lock);
5687
5688         return ret == 0 && (val & SKL_CDCLK_READY_FOR_CHANGE);
5689 }
5690
5691 static bool skl_cdclk_wait_for_pcu_ready(struct drm_i915_private *dev_priv)
5692 {
5693         return _wait_for(skl_cdclk_pcu_ready(dev_priv), 3000, 10) == 0;
5694 }
5695
5696 static void skl_set_cdclk(struct drm_i915_private *dev_priv, int cdclk, int vco)
5697 {
5698         struct drm_device *dev = &dev_priv->drm;
5699         u32 freq_select, pcu_ack;
5700
5701         WARN_ON((cdclk == 24000) != (vco == 0));
5702
5703         DRM_DEBUG_DRIVER("Changing CDCLK to %d kHz (VCO %d kHz)\n", cdclk, vco);
5704
5705         if (!skl_cdclk_wait_for_pcu_ready(dev_priv)) {
5706                 DRM_ERROR("failed to inform PCU about cdclk change\n");
5707                 return;
5708         }
5709
5710         /* set CDCLK_CTL */
5711         switch (cdclk) {
5712         case 450000:
5713         case 432000:
5714                 freq_select = CDCLK_FREQ_450_432;
5715                 pcu_ack = 1;
5716                 break;
5717         case 540000:
5718                 freq_select = CDCLK_FREQ_540;
5719                 pcu_ack = 2;
5720                 break;
5721         case 308571:
5722         case 337500:
5723         default:
5724                 freq_select = CDCLK_FREQ_337_308;
5725                 pcu_ack = 0;
5726                 break;
5727         case 617143:
5728         case 675000:
5729                 freq_select = CDCLK_FREQ_675_617;
5730                 pcu_ack = 3;
5731                 break;
5732         }
5733
5734         if (dev_priv->cdclk_pll.vco != 0 &&
5735             dev_priv->cdclk_pll.vco != vco)
5736                 skl_dpll0_disable(dev_priv);
5737
5738         if (dev_priv->cdclk_pll.vco != vco)
5739                 skl_dpll0_enable(dev_priv, vco);
5740
5741         I915_WRITE(CDCLK_CTL, freq_select | skl_cdclk_decimal(cdclk));
5742         POSTING_READ(CDCLK_CTL);
5743
5744         /* inform PCU of the change */
5745         mutex_lock(&dev_priv->rps.hw_lock);
5746         sandybridge_pcode_write(dev_priv, SKL_PCODE_CDCLK_CONTROL, pcu_ack);
5747         mutex_unlock(&dev_priv->rps.hw_lock);
5748
5749         intel_update_cdclk(dev);
5750 }
5751
5752 static void skl_sanitize_cdclk(struct drm_i915_private *dev_priv);
5753
5754 void skl_uninit_cdclk(struct drm_i915_private *dev_priv)
5755 {
5756         skl_set_cdclk(dev_priv, dev_priv->cdclk_pll.ref, 0);
5757 }
5758
5759 void skl_init_cdclk(struct drm_i915_private *dev_priv)
5760 {
5761         int cdclk, vco;
5762
5763         skl_sanitize_cdclk(dev_priv);
5764
5765         if (dev_priv->cdclk_freq != 0 && dev_priv->cdclk_pll.vco != 0) {
5766                 /*
5767                  * Use the current vco as our initial
5768                  * guess as to what the preferred vco is.
5769                  */
5770                 if (dev_priv->skl_preferred_vco_freq == 0)
5771                         skl_set_preferred_cdclk_vco(dev_priv,
5772                                                     dev_priv->cdclk_pll.vco);
5773                 return;
5774         }
5775
5776         vco = dev_priv->skl_preferred_vco_freq;
5777         if (vco == 0)
5778                 vco = 8100000;
5779         cdclk = skl_calc_cdclk(0, vco);
5780
5781         skl_set_cdclk(dev_priv, cdclk, vco);
5782 }
5783
5784 static void skl_sanitize_cdclk(struct drm_i915_private *dev_priv)
5785 {
5786         uint32_t cdctl, expected;
5787
5788         /*
5789          * check if the pre-os intialized the display
5790          * There is SWF18 scratchpad register defined which is set by the
5791          * pre-os which can be used by the OS drivers to check the status
5792          */
5793         if ((I915_READ(SWF_ILK(0x18)) & 0x00FFFFFF) == 0)
5794                 goto sanitize;
5795
5796         intel_update_cdclk(&dev_priv->drm);
5797         /* Is PLL enabled and locked ? */
5798         if (dev_priv->cdclk_pll.vco == 0 ||
5799             dev_priv->cdclk_freq == dev_priv->cdclk_pll.ref)
5800                 goto sanitize;
5801
5802         /* DPLL okay; verify the cdclock
5803          *
5804          * Noticed in some instances that the freq selection is correct but
5805          * decimal part is programmed wrong from BIOS where pre-os does not
5806          * enable display. Verify the same as well.
5807          */
5808         cdctl = I915_READ(CDCLK_CTL);
5809         expected = (cdctl & CDCLK_FREQ_SEL_MASK) |
5810                 skl_cdclk_decimal(dev_priv->cdclk_freq);
5811         if (cdctl == expected)
5812                 /* All well; nothing to sanitize */
5813                 return;
5814
5815 sanitize:
5816         DRM_DEBUG_KMS("Sanitizing cdclk programmed by pre-os\n");
5817
5818         /* force cdclk programming */
5819         dev_priv->cdclk_freq = 0;
5820         /* force full PLL disable + enable */
5821         dev_priv->cdclk_pll.vco = -1;
5822 }
5823
5824 /* Adjust CDclk dividers to allow high res or save power if possible */
5825 static void valleyview_set_cdclk(struct drm_device *dev, int cdclk)
5826 {
5827         struct drm_i915_private *dev_priv = to_i915(dev);
5828         u32 val, cmd;
5829
5830         WARN_ON(dev_priv->display.get_display_clock_speed(dev)
5831                                         != dev_priv->cdclk_freq);
5832
5833         if (cdclk >= 320000) /* jump to highest voltage for 400MHz too */
5834                 cmd = 2;
5835         else if (cdclk == 266667)
5836                 cmd = 1;
5837         else
5838                 cmd = 0;
5839
5840         mutex_lock(&dev_priv->rps.hw_lock);
5841         val = vlv_punit_read(dev_priv, PUNIT_REG_DSPFREQ);
5842         val &= ~DSPFREQGUAR_MASK;
5843         val |= (cmd << DSPFREQGUAR_SHIFT);
5844         vlv_punit_write(dev_priv, PUNIT_REG_DSPFREQ, val);
5845         if (wait_for((vlv_punit_read(dev_priv, PUNIT_REG_DSPFREQ) &
5846                       DSPFREQSTAT_MASK) == (cmd << DSPFREQSTAT_SHIFT),
5847                      50)) {
5848                 DRM_ERROR("timed out waiting for CDclk change\n");
5849         }
5850         mutex_unlock(&dev_priv->rps.hw_lock);
5851
5852         mutex_lock(&dev_priv->sb_lock);
5853
5854         if (cdclk == 400000) {
5855                 u32 divider;
5856
5857                 divider = DIV_ROUND_CLOSEST(dev_priv->hpll_freq << 1, cdclk) - 1;
5858
5859                 /* adjust cdclk divider */
5860                 val = vlv_cck_read(dev_priv, CCK_DISPLAY_CLOCK_CONTROL);
5861                 val &= ~CCK_FREQUENCY_VALUES;
5862                 val |= divider;
5863                 vlv_cck_write(dev_priv, CCK_DISPLAY_CLOCK_CONTROL, val);
5864
5865                 if (wait_for((vlv_cck_read(dev_priv, CCK_DISPLAY_CLOCK_CONTROL) &
5866                               CCK_FREQUENCY_STATUS) == (divider << CCK_FREQUENCY_STATUS_SHIFT),
5867                              50))
5868                         DRM_ERROR("timed out waiting for CDclk change\n");
5869         }
5870
5871         /* adjust self-refresh exit latency value */
5872         val = vlv_bunit_read(dev_priv, BUNIT_REG_BISOC);
5873         val &= ~0x7f;
5874
5875         /*
5876          * For high bandwidth configs, we set a higher latency in the bunit
5877          * so that the core display fetch happens in time to avoid underruns.
5878          */
5879         if (cdclk == 400000)
5880                 val |= 4500 / 250; /* 4.5 usec */
5881         else
5882                 val |= 3000 / 250; /* 3.0 usec */
5883         vlv_bunit_write(dev_priv, BUNIT_REG_BISOC, val);
5884
5885         mutex_unlock(&dev_priv->sb_lock);
5886
5887         intel_update_cdclk(dev);
5888 }
5889
5890 static void cherryview_set_cdclk(struct drm_device *dev, int cdclk)
5891 {
5892         struct drm_i915_private *dev_priv = to_i915(dev);
5893         u32 val, cmd;
5894
5895         WARN_ON(dev_priv->display.get_display_clock_speed(dev)
5896                                                 != dev_priv->cdclk_freq);
5897
5898         switch (cdclk) {
5899         case 333333:
5900         case 320000:
5901         case 266667:
5902         case 200000:
5903                 break;
5904         default:
5905                 MISSING_CASE(cdclk);
5906                 return;
5907         }
5908
5909         /*
5910          * Specs are full of misinformation, but testing on actual
5911          * hardware has shown that we just need to write the desired
5912          * CCK divider into the Punit register.
5913          */
5914         cmd = DIV_ROUND_CLOSEST(dev_priv->hpll_freq << 1, cdclk) - 1;
5915
5916         mutex_lock(&dev_priv->rps.hw_lock);
5917         val = vlv_punit_read(dev_priv, PUNIT_REG_DSPFREQ);
5918         val &= ~DSPFREQGUAR_MASK_CHV;
5919         val |= (cmd << DSPFREQGUAR_SHIFT_CHV);
5920         vlv_punit_write(dev_priv, PUNIT_REG_DSPFREQ, val);
5921         if (wait_for((vlv_punit_read(dev_priv, PUNIT_REG_DSPFREQ) &
5922                       DSPFREQSTAT_MASK_CHV) == (cmd << DSPFREQSTAT_SHIFT_CHV),
5923                      50)) {
5924                 DRM_ERROR("timed out waiting for CDclk change\n");
5925         }
5926         mutex_unlock(&dev_priv->rps.hw_lock);
5927
5928         intel_update_cdclk(dev);
5929 }
5930
5931 static int valleyview_calc_cdclk(struct drm_i915_private *dev_priv,
5932                                  int max_pixclk)
5933 {
5934         int freq_320 = (dev_priv->hpll_freq <<  1) % 320000 != 0 ? 333333 : 320000;
5935         int limit = IS_CHERRYVIEW(dev_priv) ? 95 : 90;
5936
5937         /*
5938          * Really only a few cases to deal with, as only 4 CDclks are supported:
5939          *   200MHz
5940          *   267MHz
5941          *   320/333MHz (depends on HPLL freq)
5942          *   400MHz (VLV only)
5943          * So we check to see whether we're above 90% (VLV) or 95% (CHV)
5944          * of the lower bin and adjust if needed.
5945          *
5946          * We seem to get an unstable or solid color picture at 200MHz.
5947          * Not sure what's wrong. For now use 200MHz only when all pipes
5948          * are off.
5949          */
5950         if (!IS_CHERRYVIEW(dev_priv) &&
5951             max_pixclk > freq_320*limit/100)
5952                 return 400000;
5953         else if (max_pixclk > 266667*limit/100)
5954                 return freq_320;
5955         else if (max_pixclk > 0)
5956                 return 266667;
5957         else
5958                 return 200000;
5959 }
5960
5961 static int bxt_calc_cdclk(int max_pixclk)
5962 {
5963         if (max_pixclk > 576000)
5964                 return 624000;
5965         else if (max_pixclk > 384000)
5966                 return 576000;
5967         else if (max_pixclk > 288000)
5968                 return 384000;
5969         else if (max_pixclk > 144000)
5970                 return 288000;
5971         else
5972                 return 144000;
5973 }
5974
5975 /* Compute the max pixel clock for new configuration. */
5976 static int intel_mode_max_pixclk(struct drm_device *dev,
5977                                  struct drm_atomic_state *state)
5978 {
5979         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
5980         struct drm_i915_private *dev_priv = to_i915(dev);
5981         struct drm_crtc *crtc;
5982         struct drm_crtc_state *crtc_state;
5983         unsigned max_pixclk = 0, i;
5984         enum pipe pipe;
5985
5986         memcpy(intel_state->min_pixclk, dev_priv->min_pixclk,
5987                sizeof(intel_state->min_pixclk));
5988
5989         for_each_crtc_in_state(state, crtc, crtc_state, i) {
5990                 int pixclk = 0;
5991
5992                 if (crtc_state->enable)
5993                         pixclk = crtc_state->adjusted_mode.crtc_clock;
5994
5995                 intel_state->min_pixclk[i] = pixclk;
5996         }
5997
5998         for_each_pipe(dev_priv, pipe)
5999                 max_pixclk = max(intel_state->min_pixclk[pipe], max_pixclk);
6000
6001         return max_pixclk;
6002 }
6003
6004 static int valleyview_modeset_calc_cdclk(struct drm_atomic_state *state)
6005 {
6006         struct drm_device *dev = state->dev;
6007         struct drm_i915_private *dev_priv = to_i915(dev);
6008         int max_pixclk = intel_mode_max_pixclk(dev, state);
6009         struct intel_atomic_state *intel_state =
6010                 to_intel_atomic_state(state);
6011
6012         intel_state->cdclk = intel_state->dev_cdclk =
6013                 valleyview_calc_cdclk(dev_priv, max_pixclk);
6014
6015         if (!intel_state->active_crtcs)
6016                 intel_state->dev_cdclk = valleyview_calc_cdclk(dev_priv, 0);
6017
6018         return 0;
6019 }
6020
6021 static int bxt_modeset_calc_cdclk(struct drm_atomic_state *state)
6022 {
6023         int max_pixclk = ilk_max_pixel_rate(state);
6024         struct intel_atomic_state *intel_state =
6025                 to_intel_atomic_state(state);
6026
6027         intel_state->cdclk = intel_state->dev_cdclk =
6028                 bxt_calc_cdclk(max_pixclk);
6029
6030         if (!intel_state->active_crtcs)
6031                 intel_state->dev_cdclk = bxt_calc_cdclk(0);
6032
6033         return 0;
6034 }
6035
6036 static void vlv_program_pfi_credits(struct drm_i915_private *dev_priv)
6037 {
6038         unsigned int credits, default_credits;
6039
6040         if (IS_CHERRYVIEW(dev_priv))
6041                 default_credits = PFI_CREDIT(12);
6042         else
6043                 default_credits = PFI_CREDIT(8);
6044
6045         if (dev_priv->cdclk_freq >= dev_priv->czclk_freq) {
6046                 /* CHV suggested value is 31 or 63 */
6047                 if (IS_CHERRYVIEW(dev_priv))
6048                         credits = PFI_CREDIT_63;
6049                 else
6050                         credits = PFI_CREDIT(15);
6051         } else {
6052                 credits = default_credits;
6053         }
6054
6055         /*
6056          * WA - write default credits before re-programming
6057          * FIXME: should we also set the resend bit here?
6058          */
6059         I915_WRITE(GCI_CONTROL, VGA_FAST_MODE_DISABLE |
6060                    default_credits);
6061
6062         I915_WRITE(GCI_CONTROL, VGA_FAST_MODE_DISABLE |
6063                    credits | PFI_CREDIT_RESEND);
6064
6065         /*
6066          * FIXME is this guaranteed to clear
6067          * immediately or should we poll for it?
6068          */
6069         WARN_ON(I915_READ(GCI_CONTROL) & PFI_CREDIT_RESEND);
6070 }
6071
6072 static void valleyview_modeset_commit_cdclk(struct drm_atomic_state *old_state)
6073 {
6074         struct drm_device *dev = old_state->dev;
6075         struct drm_i915_private *dev_priv = to_i915(dev);
6076         struct intel_atomic_state *old_intel_state =
6077                 to_intel_atomic_state(old_state);
6078         unsigned req_cdclk = old_intel_state->dev_cdclk;
6079
6080         /*
6081          * FIXME: We can end up here with all power domains off, yet
6082          * with a CDCLK frequency other than the minimum. To account
6083          * for this take the PIPE-A power domain, which covers the HW
6084          * blocks needed for the following programming. This can be
6085          * removed once it's guaranteed that we get here either with
6086          * the minimum CDCLK set, or the required power domains
6087          * enabled.
6088          */
6089         intel_display_power_get(dev_priv, POWER_DOMAIN_PIPE_A);
6090
6091         if (IS_CHERRYVIEW(dev))
6092                 cherryview_set_cdclk(dev, req_cdclk);
6093         else
6094                 valleyview_set_cdclk(dev, req_cdclk);
6095
6096         vlv_program_pfi_credits(dev_priv);
6097
6098         intel_display_power_put(dev_priv, POWER_DOMAIN_PIPE_A);
6099 }
6100
6101 static void valleyview_crtc_enable(struct drm_crtc *crtc)
6102 {
6103         struct drm_device *dev = crtc->dev;
6104         struct drm_i915_private *dev_priv = to_i915(dev);
6105         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
6106         struct intel_encoder *encoder;
6107         struct intel_crtc_state *pipe_config =
6108                 to_intel_crtc_state(crtc->state);
6109         int pipe = intel_crtc->pipe;
6110
6111         if (WARN_ON(intel_crtc->active))
6112                 return;
6113
6114         if (intel_crtc_has_dp_encoder(intel_crtc->config))
6115                 intel_dp_set_m_n(intel_crtc, M1_N1);
6116
6117         intel_set_pipe_timings(intel_crtc);
6118         intel_set_pipe_src_size(intel_crtc);
6119
6120         if (IS_CHERRYVIEW(dev) && pipe == PIPE_B) {
6121                 struct drm_i915_private *dev_priv = to_i915(dev);
6122
6123                 I915_WRITE(CHV_BLEND(pipe), CHV_BLEND_LEGACY);
6124                 I915_WRITE(CHV_CANVAS(pipe), 0);
6125         }
6126
6127         i9xx_set_pipeconf(intel_crtc);
6128
6129         intel_crtc->active = true;
6130
6131         intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
6132
6133         for_each_encoder_on_crtc(dev, crtc, encoder)
6134                 if (encoder->pre_pll_enable)
6135                         encoder->pre_pll_enable(encoder);
6136
6137         if (IS_CHERRYVIEW(dev)) {
6138                 chv_prepare_pll(intel_crtc, intel_crtc->config);
6139                 chv_enable_pll(intel_crtc, intel_crtc->config);
6140         } else {
6141                 vlv_prepare_pll(intel_crtc, intel_crtc->config);
6142                 vlv_enable_pll(intel_crtc, intel_crtc->config);
6143         }
6144
6145         for_each_encoder_on_crtc(dev, crtc, encoder)
6146                 if (encoder->pre_enable)
6147                         encoder->pre_enable(encoder);
6148
6149         i9xx_pfit_enable(intel_crtc);
6150
6151         intel_color_load_luts(&pipe_config->base);
6152
6153         intel_update_watermarks(crtc);
6154         intel_enable_pipe(intel_crtc);
6155
6156         assert_vblank_disabled(crtc);
6157         drm_crtc_vblank_on(crtc);
6158
6159         for_each_encoder_on_crtc(dev, crtc, encoder)
6160                 encoder->enable(encoder);
6161 }
6162
6163 static void i9xx_set_pll_dividers(struct intel_crtc *crtc)
6164 {
6165         struct drm_device *dev = crtc->base.dev;
6166         struct drm_i915_private *dev_priv = to_i915(dev);
6167
6168         I915_WRITE(FP0(crtc->pipe), crtc->config->dpll_hw_state.fp0);
6169         I915_WRITE(FP1(crtc->pipe), crtc->config->dpll_hw_state.fp1);
6170 }
6171
6172 static void i9xx_crtc_enable(struct drm_crtc *crtc)
6173 {
6174         struct drm_device *dev = crtc->dev;
6175         struct drm_i915_private *dev_priv = to_i915(dev);
6176         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
6177         struct intel_encoder *encoder;
6178         struct intel_crtc_state *pipe_config =
6179                 to_intel_crtc_state(crtc->state);
6180         enum pipe pipe = intel_crtc->pipe;
6181
6182         if (WARN_ON(intel_crtc->active))
6183                 return;
6184
6185         i9xx_set_pll_dividers(intel_crtc);
6186
6187         if (intel_crtc_has_dp_encoder(intel_crtc->config))
6188                 intel_dp_set_m_n(intel_crtc, M1_N1);
6189
6190         intel_set_pipe_timings(intel_crtc);
6191         intel_set_pipe_src_size(intel_crtc);
6192
6193         i9xx_set_pipeconf(intel_crtc);
6194
6195         intel_crtc->active = true;
6196
6197         if (!IS_GEN2(dev))
6198                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
6199
6200         for_each_encoder_on_crtc(dev, crtc, encoder)
6201                 if (encoder->pre_enable)
6202                         encoder->pre_enable(encoder);
6203
6204         i9xx_enable_pll(intel_crtc);
6205
6206         i9xx_pfit_enable(intel_crtc);
6207
6208         intel_color_load_luts(&pipe_config->base);
6209
6210         intel_update_watermarks(crtc);
6211         intel_enable_pipe(intel_crtc);
6212
6213         assert_vblank_disabled(crtc);
6214         drm_crtc_vblank_on(crtc);
6215
6216         for_each_encoder_on_crtc(dev, crtc, encoder)
6217                 encoder->enable(encoder);
6218 }
6219
6220 static void i9xx_pfit_disable(struct intel_crtc *crtc)
6221 {
6222         struct drm_device *dev = crtc->base.dev;
6223         struct drm_i915_private *dev_priv = to_i915(dev);
6224
6225         if (!crtc->config->gmch_pfit.control)
6226                 return;
6227
6228         assert_pipe_disabled(dev_priv, crtc->pipe);
6229
6230         DRM_DEBUG_DRIVER("disabling pfit, current: 0x%08x\n",
6231                          I915_READ(PFIT_CONTROL));
6232         I915_WRITE(PFIT_CONTROL, 0);
6233 }
6234
6235 static void i9xx_crtc_disable(struct drm_crtc *crtc)
6236 {
6237         struct drm_device *dev = crtc->dev;
6238         struct drm_i915_private *dev_priv = to_i915(dev);
6239         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
6240         struct intel_encoder *encoder;
6241         int pipe = intel_crtc->pipe;
6242
6243         /*
6244          * On gen2 planes are double buffered but the pipe isn't, so we must
6245          * wait for planes to fully turn off before disabling the pipe.
6246          */
6247         if (IS_GEN2(dev))
6248                 intel_wait_for_vblank(dev, pipe);
6249
6250         for_each_encoder_on_crtc(dev, crtc, encoder)
6251                 encoder->disable(encoder);
6252
6253         drm_crtc_vblank_off(crtc);
6254         assert_vblank_disabled(crtc);
6255
6256         intel_disable_pipe(intel_crtc);
6257
6258         i9xx_pfit_disable(intel_crtc);
6259
6260         for_each_encoder_on_crtc(dev, crtc, encoder)
6261                 if (encoder->post_disable)
6262                         encoder->post_disable(encoder);
6263
6264         if (!intel_crtc_has_type(intel_crtc->config, INTEL_OUTPUT_DSI)) {
6265                 if (IS_CHERRYVIEW(dev))
6266                         chv_disable_pll(dev_priv, pipe);
6267                 else if (IS_VALLEYVIEW(dev))
6268                         vlv_disable_pll(dev_priv, pipe);
6269                 else
6270                         i9xx_disable_pll(intel_crtc);
6271         }
6272
6273         for_each_encoder_on_crtc(dev, crtc, encoder)
6274                 if (encoder->post_pll_disable)
6275                         encoder->post_pll_disable(encoder);
6276
6277         if (!IS_GEN2(dev))
6278                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
6279 }
6280
6281 static void intel_crtc_disable_noatomic(struct drm_crtc *crtc)
6282 {
6283         struct intel_encoder *encoder;
6284         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
6285         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
6286         enum intel_display_power_domain domain;
6287         unsigned long domains;
6288
6289         if (!intel_crtc->active)
6290                 return;
6291
6292         if (to_intel_plane_state(crtc->primary->state)->base.visible) {
6293                 WARN_ON(intel_crtc->flip_work);
6294
6295                 intel_pre_disable_primary_noatomic(crtc);
6296
6297                 intel_crtc_disable_planes(crtc, 1 << drm_plane_index(crtc->primary));
6298                 to_intel_plane_state(crtc->primary->state)->base.visible = false;
6299         }
6300
6301         dev_priv->display.crtc_disable(crtc);
6302
6303         DRM_DEBUG_KMS("[CRTC:%d:%s] hw state adjusted, was enabled, now disabled\n",
6304                       crtc->base.id, crtc->name);
6305
6306         WARN_ON(drm_atomic_set_mode_for_crtc(crtc->state, NULL) < 0);
6307         crtc->state->active = false;
6308         intel_crtc->active = false;
6309         crtc->enabled = false;
6310         crtc->state->connector_mask = 0;
6311         crtc->state->encoder_mask = 0;
6312
6313         for_each_encoder_on_crtc(crtc->dev, crtc, encoder)
6314                 encoder->base.crtc = NULL;
6315
6316         intel_fbc_disable(intel_crtc);
6317         intel_update_watermarks(crtc);
6318         intel_disable_shared_dpll(intel_crtc);
6319
6320         domains = intel_crtc->enabled_power_domains;
6321         for_each_power_domain(domain, domains)
6322                 intel_display_power_put(dev_priv, domain);
6323         intel_crtc->enabled_power_domains = 0;
6324
6325         dev_priv->active_crtcs &= ~(1 << intel_crtc->pipe);
6326         dev_priv->min_pixclk[intel_crtc->pipe] = 0;
6327 }
6328
6329 /*
6330  * turn all crtc's off, but do not adjust state
6331  * This has to be paired with a call to intel_modeset_setup_hw_state.
6332  */
6333 int intel_display_suspend(struct drm_device *dev)
6334 {
6335         struct drm_i915_private *dev_priv = to_i915(dev);
6336         struct drm_atomic_state *state;
6337         int ret;
6338
6339         state = drm_atomic_helper_suspend(dev);
6340         ret = PTR_ERR_OR_ZERO(state);
6341         if (ret)
6342                 DRM_ERROR("Suspending crtc's failed with %i\n", ret);
6343         else
6344                 dev_priv->modeset_restore_state = state;
6345         return ret;
6346 }
6347
6348 void intel_encoder_destroy(struct drm_encoder *encoder)
6349 {
6350         struct intel_encoder *intel_encoder = to_intel_encoder(encoder);
6351
6352         drm_encoder_cleanup(encoder);
6353         kfree(intel_encoder);
6354 }
6355
6356 /* Cross check the actual hw state with our own modeset state tracking (and it's
6357  * internal consistency). */
6358 static void intel_connector_verify_state(struct intel_connector *connector)
6359 {
6360         struct drm_crtc *crtc = connector->base.state->crtc;
6361
6362         DRM_DEBUG_KMS("[CONNECTOR:%d:%s]\n",
6363                       connector->base.base.id,
6364                       connector->base.name);
6365
6366         if (connector->get_hw_state(connector)) {
6367                 struct intel_encoder *encoder = connector->encoder;
6368                 struct drm_connector_state *conn_state = connector->base.state;
6369
6370                 I915_STATE_WARN(!crtc,
6371                          "connector enabled without attached crtc\n");
6372
6373                 if (!crtc)
6374                         return;
6375
6376                 I915_STATE_WARN(!crtc->state->active,
6377                       "connector is active, but attached crtc isn't\n");
6378
6379                 if (!encoder || encoder->type == INTEL_OUTPUT_DP_MST)
6380                         return;
6381
6382                 I915_STATE_WARN(conn_state->best_encoder != &encoder->base,
6383                         "atomic encoder doesn't match attached encoder\n");
6384
6385                 I915_STATE_WARN(conn_state->crtc != encoder->base.crtc,
6386                         "attached encoder crtc differs from connector crtc\n");
6387         } else {
6388                 I915_STATE_WARN(crtc && crtc->state->active,
6389                         "attached crtc is active, but connector isn't\n");
6390                 I915_STATE_WARN(!crtc && connector->base.state->best_encoder,
6391                         "best encoder set without crtc!\n");
6392         }
6393 }
6394
6395 int intel_connector_init(struct intel_connector *connector)
6396 {
6397         drm_atomic_helper_connector_reset(&connector->base);
6398
6399         if (!connector->base.state)
6400                 return -ENOMEM;
6401
6402         return 0;
6403 }
6404
6405 struct intel_connector *intel_connector_alloc(void)
6406 {
6407         struct intel_connector *connector;
6408
6409         connector = kzalloc(sizeof *connector, GFP_KERNEL);
6410         if (!connector)
6411                 return NULL;
6412
6413         if (intel_connector_init(connector) < 0) {
6414                 kfree(connector);
6415                 return NULL;
6416         }
6417
6418         return connector;
6419 }
6420
6421 /* Simple connector->get_hw_state implementation for encoders that support only
6422  * one connector and no cloning and hence the encoder state determines the state
6423  * of the connector. */
6424 bool intel_connector_get_hw_state(struct intel_connector *connector)
6425 {
6426         enum pipe pipe = 0;
6427         struct intel_encoder *encoder = connector->encoder;
6428
6429         return encoder->get_hw_state(encoder, &pipe);
6430 }
6431
6432 static int pipe_required_fdi_lanes(struct intel_crtc_state *crtc_state)
6433 {
6434         if (crtc_state->base.enable && crtc_state->has_pch_encoder)
6435                 return crtc_state->fdi_lanes;
6436
6437         return 0;
6438 }
6439
6440 static int ironlake_check_fdi_lanes(struct drm_device *dev, enum pipe pipe,
6441                                      struct intel_crtc_state *pipe_config)
6442 {
6443         struct drm_atomic_state *state = pipe_config->base.state;
6444         struct intel_crtc *other_crtc;
6445         struct intel_crtc_state *other_crtc_state;
6446
6447         DRM_DEBUG_KMS("checking fdi config on pipe %c, lanes %i\n",
6448                       pipe_name(pipe), pipe_config->fdi_lanes);
6449         if (pipe_config->fdi_lanes > 4) {
6450                 DRM_DEBUG_KMS("invalid fdi lane config on pipe %c: %i lanes\n",
6451                               pipe_name(pipe), pipe_config->fdi_lanes);
6452                 return -EINVAL;
6453         }
6454
6455         if (IS_HASWELL(dev) || IS_BROADWELL(dev)) {
6456                 if (pipe_config->fdi_lanes > 2) {
6457                         DRM_DEBUG_KMS("only 2 lanes on haswell, required: %i lanes\n",
6458                                       pipe_config->fdi_lanes);
6459                         return -EINVAL;
6460                 } else {
6461                         return 0;
6462                 }
6463         }
6464
6465         if (INTEL_INFO(dev)->num_pipes == 2)
6466                 return 0;
6467
6468         /* Ivybridge 3 pipe is really complicated */
6469         switch (pipe) {
6470         case PIPE_A:
6471                 return 0;
6472         case PIPE_B:
6473                 if (pipe_config->fdi_lanes <= 2)
6474                         return 0;
6475
6476                 other_crtc = to_intel_crtc(intel_get_crtc_for_pipe(dev, PIPE_C));
6477                 other_crtc_state =
6478                         intel_atomic_get_crtc_state(state, other_crtc);
6479                 if (IS_ERR(other_crtc_state))
6480                         return PTR_ERR(other_crtc_state);
6481
6482                 if (pipe_required_fdi_lanes(other_crtc_state) > 0) {
6483                         DRM_DEBUG_KMS("invalid shared fdi lane config on pipe %c: %i lanes\n",
6484                                       pipe_name(pipe), pipe_config->fdi_lanes);
6485                         return -EINVAL;
6486                 }
6487                 return 0;
6488         case PIPE_C:
6489                 if (pipe_config->fdi_lanes > 2) {
6490                         DRM_DEBUG_KMS("only 2 lanes on pipe %c: required %i lanes\n",
6491                                       pipe_name(pipe), pipe_config->fdi_lanes);
6492                         return -EINVAL;
6493                 }
6494
6495                 other_crtc = to_intel_crtc(intel_get_crtc_for_pipe(dev, PIPE_B));
6496                 other_crtc_state =
6497                         intel_atomic_get_crtc_state(state, other_crtc);
6498                 if (IS_ERR(other_crtc_state))
6499                         return PTR_ERR(other_crtc_state);
6500
6501                 if (pipe_required_fdi_lanes(other_crtc_state) > 2) {
6502                         DRM_DEBUG_KMS("fdi link B uses too many lanes to enable link C\n");
6503                         return -EINVAL;
6504                 }
6505                 return 0;
6506         default:
6507                 BUG();
6508         }
6509 }
6510
6511 #define RETRY 1
6512 static int ironlake_fdi_compute_config(struct intel_crtc *intel_crtc,
6513                                        struct intel_crtc_state *pipe_config)
6514 {
6515         struct drm_device *dev = intel_crtc->base.dev;
6516         const struct drm_display_mode *adjusted_mode = &pipe_config->base.adjusted_mode;
6517         int lane, link_bw, fdi_dotclock, ret;
6518         bool needs_recompute = false;
6519
6520 retry:
6521         /* FDI is a binary signal running at ~2.7GHz, encoding
6522          * each output octet as 10 bits. The actual frequency
6523          * is stored as a divider into a 100MHz clock, and the
6524          * mode pixel clock is stored in units of 1KHz.
6525          * Hence the bw of each lane in terms of the mode signal
6526          * is:
6527          */
6528         link_bw = intel_fdi_link_freq(to_i915(dev), pipe_config);
6529
6530         fdi_dotclock = adjusted_mode->crtc_clock;
6531
6532         lane = ironlake_get_lanes_required(fdi_dotclock, link_bw,
6533                                            pipe_config->pipe_bpp);
6534
6535         pipe_config->fdi_lanes = lane;
6536
6537         intel_link_compute_m_n(pipe_config->pipe_bpp, lane, fdi_dotclock,
6538                                link_bw, &pipe_config->fdi_m_n);
6539
6540         ret = ironlake_check_fdi_lanes(dev, intel_crtc->pipe, pipe_config);
6541         if (ret == -EINVAL && pipe_config->pipe_bpp > 6*3) {
6542                 pipe_config->pipe_bpp -= 2*3;
6543                 DRM_DEBUG_KMS("fdi link bw constraint, reducing pipe bpp to %i\n",
6544                               pipe_config->pipe_bpp);
6545                 needs_recompute = true;
6546                 pipe_config->bw_constrained = true;
6547
6548                 goto retry;
6549         }
6550
6551         if (needs_recompute)
6552                 return RETRY;
6553
6554         return ret;
6555 }
6556
6557 static bool pipe_config_supports_ips(struct drm_i915_private *dev_priv,
6558                                      struct intel_crtc_state *pipe_config)
6559 {
6560         if (pipe_config->pipe_bpp > 24)
6561                 return false;
6562
6563         /* HSW can handle pixel rate up to cdclk? */
6564         if (IS_HASWELL(dev_priv))
6565                 return true;
6566
6567         /*
6568          * We compare against max which means we must take
6569          * the increased cdclk requirement into account when
6570          * calculating the new cdclk.
6571          *
6572          * Should measure whether using a lower cdclk w/o IPS
6573          */
6574         return ilk_pipe_pixel_rate(pipe_config) <=
6575                 dev_priv->max_cdclk_freq * 95 / 100;
6576 }
6577
6578 static void hsw_compute_ips_config(struct intel_crtc *crtc,
6579                                    struct intel_crtc_state *pipe_config)
6580 {
6581         struct drm_device *dev = crtc->base.dev;
6582         struct drm_i915_private *dev_priv = to_i915(dev);
6583
6584         pipe_config->ips_enabled = i915.enable_ips &&
6585                 hsw_crtc_supports_ips(crtc) &&
6586                 pipe_config_supports_ips(dev_priv, pipe_config);
6587 }
6588
6589 static bool intel_crtc_supports_double_wide(const struct intel_crtc *crtc)
6590 {
6591         const struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
6592
6593         /* GDG double wide on either pipe, otherwise pipe A only */
6594         return INTEL_INFO(dev_priv)->gen < 4 &&
6595                 (crtc->pipe == PIPE_A || IS_I915G(dev_priv));
6596 }
6597
6598 static int intel_crtc_compute_config(struct intel_crtc *crtc,
6599                                      struct intel_crtc_state *pipe_config)
6600 {
6601         struct drm_device *dev = crtc->base.dev;
6602         struct drm_i915_private *dev_priv = to_i915(dev);
6603         const struct drm_display_mode *adjusted_mode = &pipe_config->base.adjusted_mode;
6604         int clock_limit = dev_priv->max_dotclk_freq;
6605
6606         if (INTEL_INFO(dev)->gen < 4) {
6607                 clock_limit = dev_priv->max_cdclk_freq * 9 / 10;
6608
6609                 /*
6610                  * Enable double wide mode when the dot clock
6611                  * is > 90% of the (display) core speed.
6612                  */
6613                 if (intel_crtc_supports_double_wide(crtc) &&
6614                     adjusted_mode->crtc_clock > clock_limit) {
6615                         clock_limit = dev_priv->max_dotclk_freq;
6616                         pipe_config->double_wide = true;
6617                 }
6618         }
6619
6620         if (adjusted_mode->crtc_clock > clock_limit) {
6621                 DRM_DEBUG_KMS("requested pixel clock (%d kHz) too high (max: %d kHz, double wide: %s)\n",
6622                               adjusted_mode->crtc_clock, clock_limit,
6623                               yesno(pipe_config->double_wide));
6624                 return -EINVAL;
6625         }
6626
6627         /*
6628          * Pipe horizontal size must be even in:
6629          * - DVO ganged mode
6630          * - LVDS dual channel mode
6631          * - Double wide pipe
6632          */
6633         if ((intel_crtc_has_type(pipe_config, INTEL_OUTPUT_LVDS) &&
6634              intel_is_dual_link_lvds(dev)) || pipe_config->double_wide)
6635                 pipe_config->pipe_src_w &= ~1;
6636
6637         /* Cantiga+ cannot handle modes with a hsync front porch of 0.
6638          * WaPruneModeWithIncorrectHsyncOffset:ctg,elk,ilk,snb,ivb,vlv,hsw.
6639          */
6640         if ((INTEL_INFO(dev)->gen > 4 || IS_G4X(dev)) &&
6641                 adjusted_mode->crtc_hsync_start == adjusted_mode->crtc_hdisplay)
6642                 return -EINVAL;
6643
6644         if (HAS_IPS(dev))
6645                 hsw_compute_ips_config(crtc, pipe_config);
6646
6647         if (pipe_config->has_pch_encoder)
6648                 return ironlake_fdi_compute_config(crtc, pipe_config);
6649
6650         return 0;
6651 }
6652
6653 static int skylake_get_display_clock_speed(struct drm_device *dev)
6654 {
6655         struct drm_i915_private *dev_priv = to_i915(dev);
6656         uint32_t cdctl;
6657
6658         skl_dpll0_update(dev_priv);
6659
6660         if (dev_priv->cdclk_pll.vco == 0)
6661                 return dev_priv->cdclk_pll.ref;
6662
6663         cdctl = I915_READ(CDCLK_CTL);
6664
6665         if (dev_priv->cdclk_pll.vco == 8640000) {
6666                 switch (cdctl & CDCLK_FREQ_SEL_MASK) {
6667                 case CDCLK_FREQ_450_432:
6668                         return 432000;
6669                 case CDCLK_FREQ_337_308:
6670                         return 308571;
6671                 case CDCLK_FREQ_540:
6672                         return 540000;
6673                 case CDCLK_FREQ_675_617:
6674                         return 617143;
6675                 default:
6676                         MISSING_CASE(cdctl & CDCLK_FREQ_SEL_MASK);
6677                 }
6678         } else {
6679                 switch (cdctl & CDCLK_FREQ_SEL_MASK) {
6680                 case CDCLK_FREQ_450_432:
6681                         return 450000;
6682                 case CDCLK_FREQ_337_308:
6683                         return 337500;
6684                 case CDCLK_FREQ_540:
6685                         return 540000;
6686                 case CDCLK_FREQ_675_617:
6687                         return 675000;
6688                 default:
6689                         MISSING_CASE(cdctl & CDCLK_FREQ_SEL_MASK);
6690                 }
6691         }
6692
6693         return dev_priv->cdclk_pll.ref;
6694 }
6695
6696 static void bxt_de_pll_update(struct drm_i915_private *dev_priv)
6697 {
6698         u32 val;
6699
6700         dev_priv->cdclk_pll.ref = 19200;
6701         dev_priv->cdclk_pll.vco = 0;
6702
6703         val = I915_READ(BXT_DE_PLL_ENABLE);
6704         if ((val & BXT_DE_PLL_PLL_ENABLE) == 0)
6705                 return;
6706
6707         if (WARN_ON((val & BXT_DE_PLL_LOCK) == 0))
6708                 return;
6709
6710         val = I915_READ(BXT_DE_PLL_CTL);
6711         dev_priv->cdclk_pll.vco = (val & BXT_DE_PLL_RATIO_MASK) *
6712                 dev_priv->cdclk_pll.ref;
6713 }
6714
6715 static int broxton_get_display_clock_speed(struct drm_device *dev)
6716 {
6717         struct drm_i915_private *dev_priv = to_i915(dev);
6718         u32 divider;
6719         int div, vco;
6720
6721         bxt_de_pll_update(dev_priv);
6722
6723         vco = dev_priv->cdclk_pll.vco;
6724         if (vco == 0)
6725                 return dev_priv->cdclk_pll.ref;
6726
6727         divider = I915_READ(CDCLK_CTL) & BXT_CDCLK_CD2X_DIV_SEL_MASK;
6728
6729         switch (divider) {
6730         case BXT_CDCLK_CD2X_DIV_SEL_1:
6731                 div = 2;
6732                 break;
6733         case BXT_CDCLK_CD2X_DIV_SEL_1_5:
6734                 div = 3;
6735                 break;
6736         case BXT_CDCLK_CD2X_DIV_SEL_2:
6737                 div = 4;
6738                 break;
6739         case BXT_CDCLK_CD2X_DIV_SEL_4:
6740                 div = 8;
6741                 break;
6742         default:
6743                 MISSING_CASE(divider);
6744                 return dev_priv->cdclk_pll.ref;
6745         }
6746
6747         return DIV_ROUND_CLOSEST(vco, div);
6748 }
6749
6750 static int broadwell_get_display_clock_speed(struct drm_device *dev)
6751 {
6752         struct drm_i915_private *dev_priv = to_i915(dev);
6753         uint32_t lcpll = I915_READ(LCPLL_CTL);
6754         uint32_t freq = lcpll & LCPLL_CLK_FREQ_MASK;
6755
6756         if (lcpll & LCPLL_CD_SOURCE_FCLK)
6757                 return 800000;
6758         else if (I915_READ(FUSE_STRAP) & HSW_CDCLK_LIMIT)
6759                 return 450000;
6760         else if (freq == LCPLL_CLK_FREQ_450)
6761                 return 450000;
6762         else if (freq == LCPLL_CLK_FREQ_54O_BDW)
6763                 return 540000;
6764         else if (freq == LCPLL_CLK_FREQ_337_5_BDW)
6765                 return 337500;
6766         else
6767                 return 675000;
6768 }
6769
6770 static int haswell_get_display_clock_speed(struct drm_device *dev)
6771 {
6772         struct drm_i915_private *dev_priv = to_i915(dev);
6773         uint32_t lcpll = I915_READ(LCPLL_CTL);
6774         uint32_t freq = lcpll & LCPLL_CLK_FREQ_MASK;
6775
6776         if (lcpll & LCPLL_CD_SOURCE_FCLK)
6777                 return 800000;
6778         else if (I915_READ(FUSE_STRAP) & HSW_CDCLK_LIMIT)
6779                 return 450000;
6780         else if (freq == LCPLL_CLK_FREQ_450)
6781                 return 450000;
6782         else if (IS_HSW_ULT(dev))
6783                 return 337500;
6784         else
6785                 return 540000;
6786 }
6787
6788 static int valleyview_get_display_clock_speed(struct drm_device *dev)
6789 {
6790         return vlv_get_cck_clock_hpll(to_i915(dev), "cdclk",
6791                                       CCK_DISPLAY_CLOCK_CONTROL);
6792 }
6793
6794 static int ilk_get_display_clock_speed(struct drm_device *dev)
6795 {
6796         return 450000;
6797 }
6798
6799 static int i945_get_display_clock_speed(struct drm_device *dev)
6800 {
6801         return 400000;
6802 }
6803
6804 static int i915_get_display_clock_speed(struct drm_device *dev)
6805 {
6806         return 333333;
6807 }
6808
6809 static int i9xx_misc_get_display_clock_speed(struct drm_device *dev)
6810 {
6811         return 200000;
6812 }
6813
6814 static int pnv_get_display_clock_speed(struct drm_device *dev)
6815 {
6816         u16 gcfgc = 0;
6817
6818         pci_read_config_word(dev->pdev, GCFGC, &gcfgc);
6819
6820         switch (gcfgc & GC_DISPLAY_CLOCK_MASK) {
6821         case GC_DISPLAY_CLOCK_267_MHZ_PNV:
6822                 return 266667;
6823         case GC_DISPLAY_CLOCK_333_MHZ_PNV:
6824                 return 333333;
6825         case GC_DISPLAY_CLOCK_444_MHZ_PNV:
6826                 return 444444;
6827         case GC_DISPLAY_CLOCK_200_MHZ_PNV:
6828                 return 200000;
6829         default:
6830                 DRM_ERROR("Unknown pnv display core clock 0x%04x\n", gcfgc);
6831         case GC_DISPLAY_CLOCK_133_MHZ_PNV:
6832                 return 133333;
6833         case GC_DISPLAY_CLOCK_167_MHZ_PNV:
6834                 return 166667;
6835         }
6836 }
6837
6838 static int i915gm_get_display_clock_speed(struct drm_device *dev)
6839 {
6840         u16 gcfgc = 0;
6841
6842         pci_read_config_word(dev->pdev, GCFGC, &gcfgc);
6843
6844         if (gcfgc & GC_LOW_FREQUENCY_ENABLE)
6845                 return 133333;
6846         else {
6847                 switch (gcfgc & GC_DISPLAY_CLOCK_MASK) {
6848                 case GC_DISPLAY_CLOCK_333_MHZ:
6849                         return 333333;
6850                 default:
6851                 case GC_DISPLAY_CLOCK_190_200_MHZ:
6852                         return 190000;
6853                 }
6854         }
6855 }
6856
6857 static int i865_get_display_clock_speed(struct drm_device *dev)
6858 {
6859         return 266667;
6860 }
6861
6862 static int i85x_get_display_clock_speed(struct drm_device *dev)
6863 {
6864         u16 hpllcc = 0;
6865
6866         /*
6867          * 852GM/852GMV only supports 133 MHz and the HPLLCC
6868          * encoding is different :(
6869          * FIXME is this the right way to detect 852GM/852GMV?
6870          */
6871         if (dev->pdev->revision == 0x1)
6872                 return 133333;
6873
6874         pci_bus_read_config_word(dev->pdev->bus,
6875                                  PCI_DEVFN(0, 3), HPLLCC, &hpllcc);
6876
6877         /* Assume that the hardware is in the high speed state.  This
6878          * should be the default.
6879          */
6880         switch (hpllcc & GC_CLOCK_CONTROL_MASK) {
6881         case GC_CLOCK_133_200:
6882         case GC_CLOCK_133_200_2:
6883         case GC_CLOCK_100_200:
6884                 return 200000;
6885         case GC_CLOCK_166_250:
6886                 return 250000;
6887         case GC_CLOCK_100_133:
6888                 return 133333;
6889         case GC_CLOCK_133_266:
6890         case GC_CLOCK_133_266_2:
6891         case GC_CLOCK_166_266:
6892                 return 266667;
6893         }
6894
6895         /* Shouldn't happen */
6896         return 0;
6897 }
6898
6899 static int i830_get_display_clock_speed(struct drm_device *dev)
6900 {
6901         return 133333;
6902 }
6903
6904 static unsigned int intel_hpll_vco(struct drm_device *dev)
6905 {
6906         struct drm_i915_private *dev_priv = to_i915(dev);
6907         static const unsigned int blb_vco[8] = {
6908                 [0] = 3200000,
6909                 [1] = 4000000,
6910                 [2] = 5333333,
6911                 [3] = 4800000,
6912                 [4] = 6400000,
6913         };
6914         static const unsigned int pnv_vco[8] = {
6915                 [0] = 3200000,
6916                 [1] = 4000000,
6917                 [2] = 5333333,
6918                 [3] = 4800000,
6919                 [4] = 2666667,
6920         };
6921         static const unsigned int cl_vco[8] = {
6922                 [0] = 3200000,
6923                 [1] = 4000000,
6924                 [2] = 5333333,
6925                 [3] = 6400000,
6926                 [4] = 3333333,
6927                 [5] = 3566667,
6928                 [6] = 4266667,
6929         };
6930         static const unsigned int elk_vco[8] = {
6931                 [0] = 3200000,
6932                 [1] = 4000000,
6933                 [2] = 5333333,
6934                 [3] = 4800000,
6935         };
6936         static const unsigned int ctg_vco[8] = {
6937                 [0] = 3200000,
6938                 [1] = 4000000,
6939                 [2] = 5333333,
6940                 [3] = 6400000,
6941                 [4] = 2666667,
6942                 [5] = 4266667,
6943         };
6944         const unsigned int *vco_table;
6945         unsigned int vco;
6946         uint8_t tmp = 0;
6947
6948         /* FIXME other chipsets? */
6949         if (IS_GM45(dev))
6950                 vco_table = ctg_vco;
6951         else if (IS_G4X(dev))
6952                 vco_table = elk_vco;
6953         else if (IS_CRESTLINE(dev))
6954                 vco_table = cl_vco;
6955         else if (IS_PINEVIEW(dev))
6956                 vco_table = pnv_vco;
6957         else if (IS_G33(dev))
6958                 vco_table = blb_vco;
6959         else
6960                 return 0;
6961
6962         tmp = I915_READ(IS_MOBILE(dev) ? HPLLVCO_MOBILE : HPLLVCO);
6963
6964         vco = vco_table[tmp & 0x7];
6965         if (vco == 0)
6966                 DRM_ERROR("Bad HPLL VCO (HPLLVCO=0x%02x)\n", tmp);
6967         else
6968                 DRM_DEBUG_KMS("HPLL VCO %u kHz\n", vco);
6969
6970         return vco;
6971 }
6972
6973 static int gm45_get_display_clock_speed(struct drm_device *dev)
6974 {
6975         unsigned int cdclk_sel, vco = intel_hpll_vco(dev);
6976         uint16_t tmp = 0;
6977
6978         pci_read_config_word(dev->pdev, GCFGC, &tmp);
6979
6980         cdclk_sel = (tmp >> 12) & 0x1;
6981
6982         switch (vco) {
6983         case 2666667:
6984         case 4000000:
6985         case 5333333:
6986                 return cdclk_sel ? 333333 : 222222;
6987         case 3200000:
6988                 return cdclk_sel ? 320000 : 228571;
6989         default:
6990                 DRM_ERROR("Unable to determine CDCLK. HPLL VCO=%u, CFGC=0x%04x\n", vco, tmp);
6991                 return 222222;
6992         }
6993 }
6994
6995 static int i965gm_get_display_clock_speed(struct drm_device *dev)
6996 {
6997         static const uint8_t div_3200[] = { 16, 10,  8 };
6998         static const uint8_t div_4000[] = { 20, 12, 10 };
6999         static const uint8_t div_5333[] = { 24, 16, 14 };
7000         const uint8_t *div_table;
7001         unsigned int cdclk_sel, vco = intel_hpll_vco(dev);
7002         uint16_t tmp = 0;
7003
7004         pci_read_config_word(dev->pdev, GCFGC, &tmp);
7005
7006         cdclk_sel = ((tmp >> 8) & 0x1f) - 1;
7007
7008         if (cdclk_sel >= ARRAY_SIZE(div_3200))
7009                 goto fail;
7010
7011         switch (vco) {
7012         case 3200000:
7013                 div_table = div_3200;
7014                 break;
7015         case 4000000:
7016                 div_table = div_4000;
7017                 break;
7018         case 5333333:
7019                 div_table = div_5333;
7020                 break;
7021         default:
7022                 goto fail;
7023         }
7024
7025         return DIV_ROUND_CLOSEST(vco, div_table[cdclk_sel]);
7026
7027 fail:
7028         DRM_ERROR("Unable to determine CDCLK. HPLL VCO=%u kHz, CFGC=0x%04x\n", vco, tmp);
7029         return 200000;
7030 }
7031
7032 static int g33_get_display_clock_speed(struct drm_device *dev)
7033 {
7034         static const uint8_t div_3200[] = { 12, 10,  8,  7, 5, 16 };
7035         static const uint8_t div_4000[] = { 14, 12, 10,  8, 6, 20 };
7036         static const uint8_t div_4800[] = { 20, 14, 12, 10, 8, 24 };
7037         static const uint8_t div_5333[] = { 20, 16, 12, 12, 8, 28 };
7038         const uint8_t *div_table;
7039         unsigned int cdclk_sel, vco = intel_hpll_vco(dev);
7040         uint16_t tmp = 0;
7041
7042         pci_read_config_word(dev->pdev, GCFGC, &tmp);
7043
7044         cdclk_sel = (tmp >> 4) & 0x7;
7045
7046         if (cdclk_sel >= ARRAY_SIZE(div_3200))
7047                 goto fail;
7048
7049         switch (vco) {
7050         case 3200000:
7051                 div_table = div_3200;
7052                 break;
7053         case 4000000:
7054                 div_table = div_4000;
7055                 break;
7056         case 4800000:
7057                 div_table = div_4800;
7058                 break;
7059         case 5333333:
7060                 div_table = div_5333;
7061                 break;
7062         default:
7063                 goto fail;
7064         }
7065
7066         return DIV_ROUND_CLOSEST(vco, div_table[cdclk_sel]);
7067
7068 fail:
7069         DRM_ERROR("Unable to determine CDCLK. HPLL VCO=%u kHz, CFGC=0x%08x\n", vco, tmp);
7070         return 190476;
7071 }
7072
7073 static void
7074 intel_reduce_m_n_ratio(uint32_t *num, uint32_t *den)
7075 {
7076         while (*num > DATA_LINK_M_N_MASK ||
7077                *den > DATA_LINK_M_N_MASK) {
7078                 *num >>= 1;
7079                 *den >>= 1;
7080         }
7081 }
7082
7083 static void compute_m_n(unsigned int m, unsigned int n,
7084                         uint32_t *ret_m, uint32_t *ret_n)
7085 {
7086         *ret_n = min_t(unsigned int, roundup_pow_of_two(n), DATA_LINK_N_MAX);
7087         *ret_m = div_u64((uint64_t) m * *ret_n, n);
7088         intel_reduce_m_n_ratio(ret_m, ret_n);
7089 }
7090
7091 void
7092 intel_link_compute_m_n(int bits_per_pixel, int nlanes,
7093                        int pixel_clock, int link_clock,
7094                        struct intel_link_m_n *m_n)
7095 {
7096         m_n->tu = 64;
7097
7098         compute_m_n(bits_per_pixel * pixel_clock,
7099                     link_clock * nlanes * 8,
7100                     &m_n->gmch_m, &m_n->gmch_n);
7101
7102         compute_m_n(pixel_clock, link_clock,
7103                     &m_n->link_m, &m_n->link_n);
7104 }
7105
7106 static inline bool intel_panel_use_ssc(struct drm_i915_private *dev_priv)
7107 {
7108         if (i915.panel_use_ssc >= 0)
7109                 return i915.panel_use_ssc != 0;
7110         return dev_priv->vbt.lvds_use_ssc
7111                 && !(dev_priv->quirks & QUIRK_LVDS_SSC_DISABLE);
7112 }
7113
7114 static uint32_t pnv_dpll_compute_fp(struct dpll *dpll)
7115 {
7116         return (1 << dpll->n) << 16 | dpll->m2;
7117 }
7118
7119 static uint32_t i9xx_dpll_compute_fp(struct dpll *dpll)
7120 {
7121         return dpll->n << 16 | dpll->m1 << 8 | dpll->m2;
7122 }
7123
7124 static void i9xx_update_pll_dividers(struct intel_crtc *crtc,
7125                                      struct intel_crtc_state *crtc_state,
7126                                      struct dpll *reduced_clock)
7127 {
7128         struct drm_device *dev = crtc->base.dev;
7129         u32 fp, fp2 = 0;
7130
7131         if (IS_PINEVIEW(dev)) {
7132                 fp = pnv_dpll_compute_fp(&crtc_state->dpll);
7133                 if (reduced_clock)
7134                         fp2 = pnv_dpll_compute_fp(reduced_clock);
7135         } else {
7136                 fp = i9xx_dpll_compute_fp(&crtc_state->dpll);
7137                 if (reduced_clock)
7138                         fp2 = i9xx_dpll_compute_fp(reduced_clock);
7139         }
7140
7141         crtc_state->dpll_hw_state.fp0 = fp;
7142
7143         crtc->lowfreq_avail = false;
7144         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS) &&
7145             reduced_clock) {
7146                 crtc_state->dpll_hw_state.fp1 = fp2;
7147                 crtc->lowfreq_avail = true;
7148         } else {
7149                 crtc_state->dpll_hw_state.fp1 = fp;
7150         }
7151 }
7152
7153 static void vlv_pllb_recal_opamp(struct drm_i915_private *dev_priv, enum pipe
7154                 pipe)
7155 {
7156         u32 reg_val;
7157
7158         /*
7159          * PLLB opamp always calibrates to max value of 0x3f, force enable it
7160          * and set it to a reasonable value instead.
7161          */
7162         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW9(1));
7163         reg_val &= 0xffffff00;
7164         reg_val |= 0x00000030;
7165         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW9(1), reg_val);
7166
7167         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_REF_DW13);
7168         reg_val &= 0x8cffffff;
7169         reg_val = 0x8c000000;
7170         vlv_dpio_write(dev_priv, pipe, VLV_REF_DW13, reg_val);
7171
7172         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW9(1));
7173         reg_val &= 0xffffff00;
7174         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW9(1), reg_val);
7175
7176         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_REF_DW13);
7177         reg_val &= 0x00ffffff;
7178         reg_val |= 0xb0000000;
7179         vlv_dpio_write(dev_priv, pipe, VLV_REF_DW13, reg_val);
7180 }
7181
7182 static void intel_pch_transcoder_set_m_n(struct intel_crtc *crtc,
7183                                          struct intel_link_m_n *m_n)
7184 {
7185         struct drm_device *dev = crtc->base.dev;
7186         struct drm_i915_private *dev_priv = to_i915(dev);
7187         int pipe = crtc->pipe;
7188
7189         I915_WRITE(PCH_TRANS_DATA_M1(pipe), TU_SIZE(m_n->tu) | m_n->gmch_m);
7190         I915_WRITE(PCH_TRANS_DATA_N1(pipe), m_n->gmch_n);
7191         I915_WRITE(PCH_TRANS_LINK_M1(pipe), m_n->link_m);
7192         I915_WRITE(PCH_TRANS_LINK_N1(pipe), m_n->link_n);
7193 }
7194
7195 static void intel_cpu_transcoder_set_m_n(struct intel_crtc *crtc,
7196                                          struct intel_link_m_n *m_n,
7197                                          struct intel_link_m_n *m2_n2)
7198 {
7199         struct drm_device *dev = crtc->base.dev;
7200         struct drm_i915_private *dev_priv = to_i915(dev);
7201         int pipe = crtc->pipe;
7202         enum transcoder transcoder = crtc->config->cpu_transcoder;
7203
7204         if (INTEL_INFO(dev)->gen >= 5) {
7205                 I915_WRITE(PIPE_DATA_M1(transcoder), TU_SIZE(m_n->tu) | m_n->gmch_m);
7206                 I915_WRITE(PIPE_DATA_N1(transcoder), m_n->gmch_n);
7207                 I915_WRITE(PIPE_LINK_M1(transcoder), m_n->link_m);
7208                 I915_WRITE(PIPE_LINK_N1(transcoder), m_n->link_n);
7209                 /* M2_N2 registers to be set only for gen < 8 (M2_N2 available
7210                  * for gen < 8) and if DRRS is supported (to make sure the
7211                  * registers are not unnecessarily accessed).
7212                  */
7213                 if (m2_n2 && (IS_CHERRYVIEW(dev) || INTEL_INFO(dev)->gen < 8) &&
7214                         crtc->config->has_drrs) {
7215                         I915_WRITE(PIPE_DATA_M2(transcoder),
7216                                         TU_SIZE(m2_n2->tu) | m2_n2->gmch_m);
7217                         I915_WRITE(PIPE_DATA_N2(transcoder), m2_n2->gmch_n);
7218                         I915_WRITE(PIPE_LINK_M2(transcoder), m2_n2->link_m);
7219                         I915_WRITE(PIPE_LINK_N2(transcoder), m2_n2->link_n);
7220                 }
7221         } else {
7222                 I915_WRITE(PIPE_DATA_M_G4X(pipe), TU_SIZE(m_n->tu) | m_n->gmch_m);
7223                 I915_WRITE(PIPE_DATA_N_G4X(pipe), m_n->gmch_n);
7224                 I915_WRITE(PIPE_LINK_M_G4X(pipe), m_n->link_m);
7225                 I915_WRITE(PIPE_LINK_N_G4X(pipe), m_n->link_n);
7226         }
7227 }
7228
7229 void intel_dp_set_m_n(struct intel_crtc *crtc, enum link_m_n_set m_n)
7230 {
7231         struct intel_link_m_n *dp_m_n, *dp_m2_n2 = NULL;
7232
7233         if (m_n == M1_N1) {
7234                 dp_m_n = &crtc->config->dp_m_n;
7235                 dp_m2_n2 = &crtc->config->dp_m2_n2;
7236         } else if (m_n == M2_N2) {
7237
7238                 /*
7239                  * M2_N2 registers are not supported. Hence m2_n2 divider value
7240                  * needs to be programmed into M1_N1.
7241                  */
7242                 dp_m_n = &crtc->config->dp_m2_n2;
7243         } else {
7244                 DRM_ERROR("Unsupported divider value\n");
7245                 return;
7246         }
7247
7248         if (crtc->config->has_pch_encoder)
7249                 intel_pch_transcoder_set_m_n(crtc, &crtc->config->dp_m_n);
7250         else
7251                 intel_cpu_transcoder_set_m_n(crtc, dp_m_n, dp_m2_n2);
7252 }
7253
7254 static void vlv_compute_dpll(struct intel_crtc *crtc,
7255                              struct intel_crtc_state *pipe_config)
7256 {
7257         pipe_config->dpll_hw_state.dpll = DPLL_INTEGRATED_REF_CLK_VLV |
7258                 DPLL_REF_CLK_ENABLE_VLV | DPLL_VGA_MODE_DIS;
7259         if (crtc->pipe != PIPE_A)
7260                 pipe_config->dpll_hw_state.dpll |= DPLL_INTEGRATED_CRI_CLK_VLV;
7261
7262         /* DPLL not used with DSI, but still need the rest set up */
7263         if (!intel_crtc_has_type(pipe_config, INTEL_OUTPUT_DSI))
7264                 pipe_config->dpll_hw_state.dpll |= DPLL_VCO_ENABLE |
7265                         DPLL_EXT_BUFFER_ENABLE_VLV;
7266
7267         pipe_config->dpll_hw_state.dpll_md =
7268                 (pipe_config->pixel_multiplier - 1) << DPLL_MD_UDI_MULTIPLIER_SHIFT;
7269 }
7270
7271 static void chv_compute_dpll(struct intel_crtc *crtc,
7272                              struct intel_crtc_state *pipe_config)
7273 {
7274         pipe_config->dpll_hw_state.dpll = DPLL_SSC_REF_CLK_CHV |
7275                 DPLL_REF_CLK_ENABLE_VLV | DPLL_VGA_MODE_DIS;
7276         if (crtc->pipe != PIPE_A)
7277                 pipe_config->dpll_hw_state.dpll |= DPLL_INTEGRATED_CRI_CLK_VLV;
7278
7279         /* DPLL not used with DSI, but still need the rest set up */
7280         if (!intel_crtc_has_type(pipe_config, INTEL_OUTPUT_DSI))
7281                 pipe_config->dpll_hw_state.dpll |= DPLL_VCO_ENABLE;
7282
7283         pipe_config->dpll_hw_state.dpll_md =
7284                 (pipe_config->pixel_multiplier - 1) << DPLL_MD_UDI_MULTIPLIER_SHIFT;
7285 }
7286
7287 static void vlv_prepare_pll(struct intel_crtc *crtc,
7288                             const struct intel_crtc_state *pipe_config)
7289 {
7290         struct drm_device *dev = crtc->base.dev;
7291         struct drm_i915_private *dev_priv = to_i915(dev);
7292         enum pipe pipe = crtc->pipe;
7293         u32 mdiv;
7294         u32 bestn, bestm1, bestm2, bestp1, bestp2;
7295         u32 coreclk, reg_val;
7296
7297         /* Enable Refclk */
7298         I915_WRITE(DPLL(pipe),
7299                    pipe_config->dpll_hw_state.dpll &
7300                    ~(DPLL_VCO_ENABLE | DPLL_EXT_BUFFER_ENABLE_VLV));
7301
7302         /* No need to actually set up the DPLL with DSI */
7303         if ((pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE) == 0)
7304                 return;
7305
7306         mutex_lock(&dev_priv->sb_lock);
7307
7308         bestn = pipe_config->dpll.n;
7309         bestm1 = pipe_config->dpll.m1;
7310         bestm2 = pipe_config->dpll.m2;
7311         bestp1 = pipe_config->dpll.p1;
7312         bestp2 = pipe_config->dpll.p2;
7313
7314         /* See eDP HDMI DPIO driver vbios notes doc */
7315
7316         /* PLL B needs special handling */
7317         if (pipe == PIPE_B)
7318                 vlv_pllb_recal_opamp(dev_priv, pipe);
7319
7320         /* Set up Tx target for periodic Rcomp update */
7321         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW9_BCAST, 0x0100000f);
7322
7323         /* Disable target IRef on PLL */
7324         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW8(pipe));
7325         reg_val &= 0x00ffffff;
7326         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW8(pipe), reg_val);
7327
7328         /* Disable fast lock */
7329         vlv_dpio_write(dev_priv, pipe, VLV_CMN_DW0, 0x610);
7330
7331         /* Set idtafcrecal before PLL is enabled */
7332         mdiv = ((bestm1 << DPIO_M1DIV_SHIFT) | (bestm2 & DPIO_M2DIV_MASK));
7333         mdiv |= ((bestp1 << DPIO_P1_SHIFT) | (bestp2 << DPIO_P2_SHIFT));
7334         mdiv |= ((bestn << DPIO_N_SHIFT));
7335         mdiv |= (1 << DPIO_K_SHIFT);
7336
7337         /*
7338          * Post divider depends on pixel clock rate, DAC vs digital (and LVDS,
7339          * but we don't support that).
7340          * Note: don't use the DAC post divider as it seems unstable.
7341          */
7342         mdiv |= (DPIO_POST_DIV_HDMIDP << DPIO_POST_DIV_SHIFT);
7343         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW3(pipe), mdiv);
7344
7345         mdiv |= DPIO_ENABLE_CALIBRATION;
7346         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW3(pipe), mdiv);
7347
7348         /* Set HBR and RBR LPF coefficients */
7349         if (pipe_config->port_clock == 162000 ||
7350             intel_crtc_has_type(crtc->config, INTEL_OUTPUT_ANALOG) ||
7351             intel_crtc_has_type(crtc->config, INTEL_OUTPUT_HDMI))
7352                 vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW10(pipe),
7353                                  0x009f0003);
7354         else
7355                 vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW10(pipe),
7356                                  0x00d0000f);
7357
7358         if (intel_crtc_has_dp_encoder(pipe_config)) {
7359                 /* Use SSC source */
7360                 if (pipe == PIPE_A)
7361                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
7362                                          0x0df40000);
7363                 else
7364                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
7365                                          0x0df70000);
7366         } else { /* HDMI or VGA */
7367                 /* Use bend source */
7368                 if (pipe == PIPE_A)
7369                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
7370                                          0x0df70000);
7371                 else
7372                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
7373                                          0x0df40000);
7374         }
7375
7376         coreclk = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW7(pipe));
7377         coreclk = (coreclk & 0x0000ff00) | 0x01c00000;
7378         if (intel_crtc_has_dp_encoder(crtc->config))
7379                 coreclk |= 0x01000000;
7380         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW7(pipe), coreclk);
7381
7382         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW11(pipe), 0x87871000);
7383         mutex_unlock(&dev_priv->sb_lock);
7384 }
7385
7386 static void chv_prepare_pll(struct intel_crtc *crtc,
7387                             const struct intel_crtc_state *pipe_config)
7388 {
7389         struct drm_device *dev = crtc->base.dev;
7390         struct drm_i915_private *dev_priv = to_i915(dev);
7391         enum pipe pipe = crtc->pipe;
7392         enum dpio_channel port = vlv_pipe_to_channel(pipe);
7393         u32 loopfilter, tribuf_calcntr;
7394         u32 bestn, bestm1, bestm2, bestp1, bestp2, bestm2_frac;
7395         u32 dpio_val;
7396         int vco;
7397
7398         /* Enable Refclk and SSC */
7399         I915_WRITE(DPLL(pipe),
7400                    pipe_config->dpll_hw_state.dpll & ~DPLL_VCO_ENABLE);
7401
7402         /* No need to actually set up the DPLL with DSI */
7403         if ((pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE) == 0)
7404                 return;
7405
7406         bestn = pipe_config->dpll.n;
7407         bestm2_frac = pipe_config->dpll.m2 & 0x3fffff;
7408         bestm1 = pipe_config->dpll.m1;
7409         bestm2 = pipe_config->dpll.m2 >> 22;
7410         bestp1 = pipe_config->dpll.p1;
7411         bestp2 = pipe_config->dpll.p2;
7412         vco = pipe_config->dpll.vco;
7413         dpio_val = 0;
7414         loopfilter = 0;
7415
7416         mutex_lock(&dev_priv->sb_lock);
7417
7418         /* p1 and p2 divider */
7419         vlv_dpio_write(dev_priv, pipe, CHV_CMN_DW13(port),
7420                         5 << DPIO_CHV_S1_DIV_SHIFT |
7421                         bestp1 << DPIO_CHV_P1_DIV_SHIFT |
7422                         bestp2 << DPIO_CHV_P2_DIV_SHIFT |
7423                         1 << DPIO_CHV_K_DIV_SHIFT);
7424
7425         /* Feedback post-divider - m2 */
7426         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW0(port), bestm2);
7427
7428         /* Feedback refclk divider - n and m1 */
7429         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW1(port),
7430                         DPIO_CHV_M1_DIV_BY_2 |
7431                         1 << DPIO_CHV_N_DIV_SHIFT);
7432
7433         /* M2 fraction division */
7434         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW2(port), bestm2_frac);
7435
7436         /* M2 fraction division enable */
7437         dpio_val = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW3(port));
7438         dpio_val &= ~(DPIO_CHV_FEEDFWD_GAIN_MASK | DPIO_CHV_FRAC_DIV_EN);
7439         dpio_val |= (2 << DPIO_CHV_FEEDFWD_GAIN_SHIFT);
7440         if (bestm2_frac)
7441                 dpio_val |= DPIO_CHV_FRAC_DIV_EN;
7442         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW3(port), dpio_val);
7443
7444         /* Program digital lock detect threshold */
7445         dpio_val = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW9(port));
7446         dpio_val &= ~(DPIO_CHV_INT_LOCK_THRESHOLD_MASK |
7447                                         DPIO_CHV_INT_LOCK_THRESHOLD_SEL_COARSE);
7448         dpio_val |= (0x5 << DPIO_CHV_INT_LOCK_THRESHOLD_SHIFT);
7449         if (!bestm2_frac)
7450                 dpio_val |= DPIO_CHV_INT_LOCK_THRESHOLD_SEL_COARSE;
7451         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW9(port), dpio_val);
7452
7453         /* Loop filter */
7454         if (vco == 5400000) {
7455                 loopfilter |= (0x3 << DPIO_CHV_PROP_COEFF_SHIFT);
7456                 loopfilter |= (0x8 << DPIO_CHV_INT_COEFF_SHIFT);
7457                 loopfilter |= (0x1 << DPIO_CHV_GAIN_CTRL_SHIFT);
7458                 tribuf_calcntr = 0x9;
7459         } else if (vco <= 6200000) {
7460                 loopfilter |= (0x5 << DPIO_CHV_PROP_COEFF_SHIFT);
7461                 loopfilter |= (0xB << DPIO_CHV_INT_COEFF_SHIFT);
7462                 loopfilter |= (0x3 << DPIO_CHV_GAIN_CTRL_SHIFT);
7463                 tribuf_calcntr = 0x9;
7464         } else if (vco <= 6480000) {
7465                 loopfilter |= (0x4 << DPIO_CHV_PROP_COEFF_SHIFT);
7466                 loopfilter |= (0x9 << DPIO_CHV_INT_COEFF_SHIFT);
7467                 loopfilter |= (0x3 << DPIO_CHV_GAIN_CTRL_SHIFT);
7468                 tribuf_calcntr = 0x8;
7469         } else {
7470                 /* Not supported. Apply the same limits as in the max case */
7471                 loopfilter |= (0x4 << DPIO_CHV_PROP_COEFF_SHIFT);
7472                 loopfilter |= (0x9 << DPIO_CHV_INT_COEFF_SHIFT);
7473                 loopfilter |= (0x3 << DPIO_CHV_GAIN_CTRL_SHIFT);
7474                 tribuf_calcntr = 0;
7475         }
7476         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW6(port), loopfilter);
7477
7478         dpio_val = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW8(port));
7479         dpio_val &= ~DPIO_CHV_TDC_TARGET_CNT_MASK;
7480         dpio_val |= (tribuf_calcntr << DPIO_CHV_TDC_TARGET_CNT_SHIFT);
7481         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW8(port), dpio_val);
7482
7483         /* AFC Recal */
7484         vlv_dpio_write(dev_priv, pipe, CHV_CMN_DW14(port),
7485                         vlv_dpio_read(dev_priv, pipe, CHV_CMN_DW14(port)) |
7486                         DPIO_AFC_RECAL);
7487
7488         mutex_unlock(&dev_priv->sb_lock);
7489 }
7490
7491 /**
7492  * vlv_force_pll_on - forcibly enable just the PLL
7493  * @dev_priv: i915 private structure
7494  * @pipe: pipe PLL to enable
7495  * @dpll: PLL configuration
7496  *
7497  * Enable the PLL for @pipe using the supplied @dpll config. To be used
7498  * in cases where we need the PLL enabled even when @pipe is not going to
7499  * be enabled.
7500  */
7501 int vlv_force_pll_on(struct drm_device *dev, enum pipe pipe,
7502                      const struct dpll *dpll)
7503 {
7504         struct intel_crtc *crtc =
7505                 to_intel_crtc(intel_get_crtc_for_pipe(dev, pipe));
7506         struct intel_crtc_state *pipe_config;
7507
7508         pipe_config = kzalloc(sizeof(*pipe_config), GFP_KERNEL);
7509         if (!pipe_config)
7510                 return -ENOMEM;
7511
7512         pipe_config->base.crtc = &crtc->base;
7513         pipe_config->pixel_multiplier = 1;
7514         pipe_config->dpll = *dpll;
7515
7516         if (IS_CHERRYVIEW(dev)) {
7517                 chv_compute_dpll(crtc, pipe_config);
7518                 chv_prepare_pll(crtc, pipe_config);
7519                 chv_enable_pll(crtc, pipe_config);
7520         } else {
7521                 vlv_compute_dpll(crtc, pipe_config);
7522                 vlv_prepare_pll(crtc, pipe_config);
7523                 vlv_enable_pll(crtc, pipe_config);
7524         }
7525
7526         kfree(pipe_config);
7527
7528         return 0;
7529 }
7530
7531 /**
7532  * vlv_force_pll_off - forcibly disable just the PLL
7533  * @dev_priv: i915 private structure
7534  * @pipe: pipe PLL to disable
7535  *
7536  * Disable the PLL for @pipe. To be used in cases where we need
7537  * the PLL enabled even when @pipe is not going to be enabled.
7538  */
7539 void vlv_force_pll_off(struct drm_device *dev, enum pipe pipe)
7540 {
7541         if (IS_CHERRYVIEW(dev))
7542                 chv_disable_pll(to_i915(dev), pipe);
7543         else
7544                 vlv_disable_pll(to_i915(dev), pipe);
7545 }
7546
7547 static void i9xx_compute_dpll(struct intel_crtc *crtc,
7548                               struct intel_crtc_state *crtc_state,
7549                               struct dpll *reduced_clock)
7550 {
7551         struct drm_device *dev = crtc->base.dev;
7552         struct drm_i915_private *dev_priv = to_i915(dev);
7553         u32 dpll;
7554         struct dpll *clock = &crtc_state->dpll;
7555
7556         i9xx_update_pll_dividers(crtc, crtc_state, reduced_clock);
7557
7558         dpll = DPLL_VGA_MODE_DIS;
7559
7560         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS))
7561                 dpll |= DPLLB_MODE_LVDS;
7562         else
7563                 dpll |= DPLLB_MODE_DAC_SERIAL;
7564
7565         if (IS_I945G(dev) || IS_I945GM(dev) || IS_G33(dev)) {
7566                 dpll |= (crtc_state->pixel_multiplier - 1)
7567                         << SDVO_MULTIPLIER_SHIFT_HIRES;
7568         }
7569
7570         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_SDVO) ||
7571             intel_crtc_has_type(crtc_state, INTEL_OUTPUT_HDMI))
7572                 dpll |= DPLL_SDVO_HIGH_SPEED;
7573
7574         if (intel_crtc_has_dp_encoder(crtc_state))
7575                 dpll |= DPLL_SDVO_HIGH_SPEED;
7576
7577         /* compute bitmask from p1 value */
7578         if (IS_PINEVIEW(dev))
7579                 dpll |= (1 << (clock->p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT_PINEVIEW;
7580         else {
7581                 dpll |= (1 << (clock->p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT;
7582                 if (IS_G4X(dev) && reduced_clock)
7583                         dpll |= (1 << (reduced_clock->p1 - 1)) << DPLL_FPA1_P1_POST_DIV_SHIFT;
7584         }
7585         switch (clock->p2) {
7586         case 5:
7587                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_5;
7588                 break;
7589         case 7:
7590                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_7;
7591                 break;
7592         case 10:
7593                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_10;
7594                 break;
7595         case 14:
7596                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_14;
7597                 break;
7598         }
7599         if (INTEL_INFO(dev)->gen >= 4)
7600                 dpll |= (6 << PLL_LOAD_PULSE_PHASE_SHIFT);
7601
7602         if (crtc_state->sdvo_tv_clock)
7603                 dpll |= PLL_REF_INPUT_TVCLKINBC;
7604         else if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS) &&
7605                  intel_panel_use_ssc(dev_priv))
7606                 dpll |= PLLB_REF_INPUT_SPREADSPECTRUMIN;
7607         else
7608                 dpll |= PLL_REF_INPUT_DREFCLK;
7609
7610         dpll |= DPLL_VCO_ENABLE;
7611         crtc_state->dpll_hw_state.dpll = dpll;
7612
7613         if (INTEL_INFO(dev)->gen >= 4) {
7614                 u32 dpll_md = (crtc_state->pixel_multiplier - 1)
7615                         << DPLL_MD_UDI_MULTIPLIER_SHIFT;
7616                 crtc_state->dpll_hw_state.dpll_md = dpll_md;
7617         }
7618 }
7619
7620 static void i8xx_compute_dpll(struct intel_crtc *crtc,
7621                               struct intel_crtc_state *crtc_state,
7622                               struct dpll *reduced_clock)
7623 {
7624         struct drm_device *dev = crtc->base.dev;
7625         struct drm_i915_private *dev_priv = to_i915(dev);
7626         u32 dpll;
7627         struct dpll *clock = &crtc_state->dpll;
7628
7629         i9xx_update_pll_dividers(crtc, crtc_state, reduced_clock);
7630
7631         dpll = DPLL_VGA_MODE_DIS;
7632
7633         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
7634                 dpll |= (1 << (clock->p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT;
7635         } else {
7636                 if (clock->p1 == 2)
7637                         dpll |= PLL_P1_DIVIDE_BY_TWO;
7638                 else
7639                         dpll |= (clock->p1 - 2) << DPLL_FPA01_P1_POST_DIV_SHIFT;
7640                 if (clock->p2 == 4)
7641                         dpll |= PLL_P2_DIVIDE_BY_4;
7642         }
7643
7644         if (!IS_I830(dev) && intel_crtc_has_type(crtc_state, INTEL_OUTPUT_DVO))
7645                 dpll |= DPLL_DVO_2X_MODE;
7646
7647         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS) &&
7648             intel_panel_use_ssc(dev_priv))
7649                 dpll |= PLLB_REF_INPUT_SPREADSPECTRUMIN;
7650         else
7651                 dpll |= PLL_REF_INPUT_DREFCLK;
7652
7653         dpll |= DPLL_VCO_ENABLE;
7654         crtc_state->dpll_hw_state.dpll = dpll;
7655 }
7656
7657 static void intel_set_pipe_timings(struct intel_crtc *intel_crtc)
7658 {
7659         struct drm_device *dev = intel_crtc->base.dev;
7660         struct drm_i915_private *dev_priv = to_i915(dev);
7661         enum pipe pipe = intel_crtc->pipe;
7662         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
7663         const struct drm_display_mode *adjusted_mode = &intel_crtc->config->base.adjusted_mode;
7664         uint32_t crtc_vtotal, crtc_vblank_end;
7665         int vsyncshift = 0;
7666
7667         /* We need to be careful not to changed the adjusted mode, for otherwise
7668          * the hw state checker will get angry at the mismatch. */
7669         crtc_vtotal = adjusted_mode->crtc_vtotal;
7670         crtc_vblank_end = adjusted_mode->crtc_vblank_end;
7671
7672         if (adjusted_mode->flags & DRM_MODE_FLAG_INTERLACE) {
7673                 /* the chip adds 2 halflines automatically */
7674                 crtc_vtotal -= 1;
7675                 crtc_vblank_end -= 1;
7676
7677                 if (intel_crtc_has_type(intel_crtc->config, INTEL_OUTPUT_SDVO))
7678                         vsyncshift = (adjusted_mode->crtc_htotal - 1) / 2;
7679                 else
7680                         vsyncshift = adjusted_mode->crtc_hsync_start -
7681                                 adjusted_mode->crtc_htotal / 2;
7682                 if (vsyncshift < 0)
7683                         vsyncshift += adjusted_mode->crtc_htotal;
7684         }
7685
7686         if (INTEL_INFO(dev)->gen > 3)
7687                 I915_WRITE(VSYNCSHIFT(cpu_transcoder), vsyncshift);
7688
7689         I915_WRITE(HTOTAL(cpu_transcoder),
7690                    (adjusted_mode->crtc_hdisplay - 1) |
7691                    ((adjusted_mode->crtc_htotal - 1) << 16));
7692         I915_WRITE(HBLANK(cpu_transcoder),
7693                    (adjusted_mode->crtc_hblank_start - 1) |
7694                    ((adjusted_mode->crtc_hblank_end - 1) << 16));
7695         I915_WRITE(HSYNC(cpu_transcoder),
7696                    (adjusted_mode->crtc_hsync_start - 1) |
7697                    ((adjusted_mode->crtc_hsync_end - 1) << 16));
7698
7699         I915_WRITE(VTOTAL(cpu_transcoder),
7700                    (adjusted_mode->crtc_vdisplay - 1) |
7701                    ((crtc_vtotal - 1) << 16));
7702         I915_WRITE(VBLANK(cpu_transcoder),
7703                    (adjusted_mode->crtc_vblank_start - 1) |
7704                    ((crtc_vblank_end - 1) << 16));
7705         I915_WRITE(VSYNC(cpu_transcoder),
7706                    (adjusted_mode->crtc_vsync_start - 1) |
7707                    ((adjusted_mode->crtc_vsync_end - 1) << 16));
7708
7709         /* Workaround: when the EDP input selection is B, the VTOTAL_B must be
7710          * programmed with the VTOTAL_EDP value. Same for VTOTAL_C. This is
7711          * documented on the DDI_FUNC_CTL register description, EDP Input Select
7712          * bits. */
7713         if (IS_HASWELL(dev) && cpu_transcoder == TRANSCODER_EDP &&
7714             (pipe == PIPE_B || pipe == PIPE_C))
7715                 I915_WRITE(VTOTAL(pipe), I915_READ(VTOTAL(cpu_transcoder)));
7716
7717 }
7718
7719 static void intel_set_pipe_src_size(struct intel_crtc *intel_crtc)
7720 {
7721         struct drm_device *dev = intel_crtc->base.dev;
7722         struct drm_i915_private *dev_priv = to_i915(dev);
7723         enum pipe pipe = intel_crtc->pipe;
7724
7725         /* pipesrc controls the size that is scaled from, which should
7726          * always be the user's requested size.
7727          */
7728         I915_WRITE(PIPESRC(pipe),
7729                    ((intel_crtc->config->pipe_src_w - 1) << 16) |
7730                    (intel_crtc->config->pipe_src_h - 1));
7731 }
7732
7733 static void intel_get_pipe_timings(struct intel_crtc *crtc,
7734                                    struct intel_crtc_state *pipe_config)
7735 {
7736         struct drm_device *dev = crtc->base.dev;
7737         struct drm_i915_private *dev_priv = to_i915(dev);
7738         enum transcoder cpu_transcoder = pipe_config->cpu_transcoder;
7739         uint32_t tmp;
7740
7741         tmp = I915_READ(HTOTAL(cpu_transcoder));
7742         pipe_config->base.adjusted_mode.crtc_hdisplay = (tmp & 0xffff) + 1;
7743         pipe_config->base.adjusted_mode.crtc_htotal = ((tmp >> 16) & 0xffff) + 1;
7744         tmp = I915_READ(HBLANK(cpu_transcoder));
7745         pipe_config->base.adjusted_mode.crtc_hblank_start = (tmp & 0xffff) + 1;
7746         pipe_config->base.adjusted_mode.crtc_hblank_end = ((tmp >> 16) & 0xffff) + 1;
7747         tmp = I915_READ(HSYNC(cpu_transcoder));
7748         pipe_config->base.adjusted_mode.crtc_hsync_start = (tmp & 0xffff) + 1;
7749         pipe_config->base.adjusted_mode.crtc_hsync_end = ((tmp >> 16) & 0xffff) + 1;
7750
7751         tmp = I915_READ(VTOTAL(cpu_transcoder));
7752         pipe_config->base.adjusted_mode.crtc_vdisplay = (tmp & 0xffff) + 1;
7753         pipe_config->base.adjusted_mode.crtc_vtotal = ((tmp >> 16) & 0xffff) + 1;
7754         tmp = I915_READ(VBLANK(cpu_transcoder));
7755         pipe_config->base.adjusted_mode.crtc_vblank_start = (tmp & 0xffff) + 1;
7756         pipe_config->base.adjusted_mode.crtc_vblank_end = ((tmp >> 16) & 0xffff) + 1;
7757         tmp = I915_READ(VSYNC(cpu_transcoder));
7758         pipe_config->base.adjusted_mode.crtc_vsync_start = (tmp & 0xffff) + 1;
7759         pipe_config->base.adjusted_mode.crtc_vsync_end = ((tmp >> 16) & 0xffff) + 1;
7760
7761         if (I915_READ(PIPECONF(cpu_transcoder)) & PIPECONF_INTERLACE_MASK) {
7762                 pipe_config->base.adjusted_mode.flags |= DRM_MODE_FLAG_INTERLACE;
7763                 pipe_config->base.adjusted_mode.crtc_vtotal += 1;
7764                 pipe_config->base.adjusted_mode.crtc_vblank_end += 1;
7765         }
7766 }
7767
7768 static void intel_get_pipe_src_size(struct intel_crtc *crtc,
7769                                     struct intel_crtc_state *pipe_config)
7770 {
7771         struct drm_device *dev = crtc->base.dev;
7772         struct drm_i915_private *dev_priv = to_i915(dev);
7773         u32 tmp;
7774
7775         tmp = I915_READ(PIPESRC(crtc->pipe));
7776         pipe_config->pipe_src_h = (tmp & 0xffff) + 1;
7777         pipe_config->pipe_src_w = ((tmp >> 16) & 0xffff) + 1;
7778
7779         pipe_config->base.mode.vdisplay = pipe_config->pipe_src_h;
7780         pipe_config->base.mode.hdisplay = pipe_config->pipe_src_w;
7781 }
7782
7783 void intel_mode_from_pipe_config(struct drm_display_mode *mode,
7784                                  struct intel_crtc_state *pipe_config)
7785 {
7786         mode->hdisplay = pipe_config->base.adjusted_mode.crtc_hdisplay;
7787         mode->htotal = pipe_config->base.adjusted_mode.crtc_htotal;
7788         mode->hsync_start = pipe_config->base.adjusted_mode.crtc_hsync_start;
7789         mode->hsync_end = pipe_config->base.adjusted_mode.crtc_hsync_end;
7790
7791         mode->vdisplay = pipe_config->base.adjusted_mode.crtc_vdisplay;
7792         mode->vtotal = pipe_config->base.adjusted_mode.crtc_vtotal;
7793         mode->vsync_start = pipe_config->base.adjusted_mode.crtc_vsync_start;
7794         mode->vsync_end = pipe_config->base.adjusted_mode.crtc_vsync_end;
7795
7796         mode->flags = pipe_config->base.adjusted_mode.flags;
7797         mode->type = DRM_MODE_TYPE_DRIVER;
7798
7799         mode->clock = pipe_config->base.adjusted_mode.crtc_clock;
7800         mode->flags |= pipe_config->base.adjusted_mode.flags;
7801
7802         mode->hsync = drm_mode_hsync(mode);
7803         mode->vrefresh = drm_mode_vrefresh(mode);
7804         drm_mode_set_name(mode);
7805 }
7806
7807 static void i9xx_set_pipeconf(struct intel_crtc *intel_crtc)
7808 {
7809         struct drm_device *dev = intel_crtc->base.dev;
7810         struct drm_i915_private *dev_priv = to_i915(dev);
7811         uint32_t pipeconf;
7812
7813         pipeconf = 0;
7814
7815         if ((intel_crtc->pipe == PIPE_A && dev_priv->quirks & QUIRK_PIPEA_FORCE) ||
7816             (intel_crtc->pipe == PIPE_B && dev_priv->quirks & QUIRK_PIPEB_FORCE))
7817                 pipeconf |= I915_READ(PIPECONF(intel_crtc->pipe)) & PIPECONF_ENABLE;
7818
7819         if (intel_crtc->config->double_wide)
7820                 pipeconf |= PIPECONF_DOUBLE_WIDE;
7821
7822         /* only g4x and later have fancy bpc/dither controls */
7823         if (IS_G4X(dev) || IS_VALLEYVIEW(dev) || IS_CHERRYVIEW(dev)) {
7824                 /* Bspec claims that we can't use dithering for 30bpp pipes. */
7825                 if (intel_crtc->config->dither && intel_crtc->config->pipe_bpp != 30)
7826                         pipeconf |= PIPECONF_DITHER_EN |
7827                                     PIPECONF_DITHER_TYPE_SP;
7828
7829                 switch (intel_crtc->config->pipe_bpp) {
7830                 case 18:
7831                         pipeconf |= PIPECONF_6BPC;
7832                         break;
7833                 case 24:
7834                         pipeconf |= PIPECONF_8BPC;
7835                         break;
7836                 case 30:
7837                         pipeconf |= PIPECONF_10BPC;
7838                         break;
7839                 default:
7840                         /* Case prevented by intel_choose_pipe_bpp_dither. */
7841                         BUG();
7842                 }
7843         }
7844
7845         if (HAS_PIPE_CXSR(dev)) {
7846                 if (intel_crtc->lowfreq_avail) {
7847                         DRM_DEBUG_KMS("enabling CxSR downclocking\n");
7848                         pipeconf |= PIPECONF_CXSR_DOWNCLOCK;
7849                 } else {
7850                         DRM_DEBUG_KMS("disabling CxSR downclocking\n");
7851                 }
7852         }
7853
7854         if (intel_crtc->config->base.adjusted_mode.flags & DRM_MODE_FLAG_INTERLACE) {
7855                 if (INTEL_INFO(dev)->gen < 4 ||
7856                     intel_crtc_has_type(intel_crtc->config, INTEL_OUTPUT_SDVO))
7857                         pipeconf |= PIPECONF_INTERLACE_W_FIELD_INDICATION;
7858                 else
7859                         pipeconf |= PIPECONF_INTERLACE_W_SYNC_SHIFT;
7860         } else
7861                 pipeconf |= PIPECONF_PROGRESSIVE;
7862
7863         if ((IS_VALLEYVIEW(dev) || IS_CHERRYVIEW(dev)) &&
7864              intel_crtc->config->limited_color_range)
7865                 pipeconf |= PIPECONF_COLOR_RANGE_SELECT;
7866
7867         I915_WRITE(PIPECONF(intel_crtc->pipe), pipeconf);
7868         POSTING_READ(PIPECONF(intel_crtc->pipe));
7869 }
7870
7871 static int i8xx_crtc_compute_clock(struct intel_crtc *crtc,
7872                                    struct intel_crtc_state *crtc_state)
7873 {
7874         struct drm_device *dev = crtc->base.dev;
7875         struct drm_i915_private *dev_priv = to_i915(dev);
7876         const struct intel_limit *limit;
7877         int refclk = 48000;
7878
7879         memset(&crtc_state->dpll_hw_state, 0,
7880                sizeof(crtc_state->dpll_hw_state));
7881
7882         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
7883                 if (intel_panel_use_ssc(dev_priv)) {
7884                         refclk = dev_priv->vbt.lvds_ssc_freq;
7885                         DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n", refclk);
7886                 }
7887
7888                 limit = &intel_limits_i8xx_lvds;
7889         } else if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_DVO)) {
7890                 limit = &intel_limits_i8xx_dvo;
7891         } else {
7892                 limit = &intel_limits_i8xx_dac;
7893         }
7894
7895         if (!crtc_state->clock_set &&
7896             !i9xx_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
7897                                  refclk, NULL, &crtc_state->dpll)) {
7898                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
7899                 return -EINVAL;
7900         }
7901
7902         i8xx_compute_dpll(crtc, crtc_state, NULL);
7903
7904         return 0;
7905 }
7906
7907 static int g4x_crtc_compute_clock(struct intel_crtc *crtc,
7908                                   struct intel_crtc_state *crtc_state)
7909 {
7910         struct drm_device *dev = crtc->base.dev;
7911         struct drm_i915_private *dev_priv = to_i915(dev);
7912         const struct intel_limit *limit;
7913         int refclk = 96000;
7914
7915         memset(&crtc_state->dpll_hw_state, 0,
7916                sizeof(crtc_state->dpll_hw_state));
7917
7918         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
7919                 if (intel_panel_use_ssc(dev_priv)) {
7920                         refclk = dev_priv->vbt.lvds_ssc_freq;
7921                         DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n", refclk);
7922                 }
7923
7924                 if (intel_is_dual_link_lvds(dev))
7925                         limit = &intel_limits_g4x_dual_channel_lvds;
7926                 else
7927                         limit = &intel_limits_g4x_single_channel_lvds;
7928         } else if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_HDMI) ||
7929                    intel_crtc_has_type(crtc_state, INTEL_OUTPUT_ANALOG)) {
7930                 limit = &intel_limits_g4x_hdmi;
7931         } else if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_SDVO)) {
7932                 limit = &intel_limits_g4x_sdvo;
7933         } else {
7934                 /* The option is for other outputs */
7935                 limit = &intel_limits_i9xx_sdvo;
7936         }
7937
7938         if (!crtc_state->clock_set &&
7939             !g4x_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
7940                                 refclk, NULL, &crtc_state->dpll)) {
7941                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
7942                 return -EINVAL;
7943         }
7944
7945         i9xx_compute_dpll(crtc, crtc_state, NULL);
7946
7947         return 0;
7948 }
7949
7950 static int pnv_crtc_compute_clock(struct intel_crtc *crtc,
7951                                   struct intel_crtc_state *crtc_state)
7952 {
7953         struct drm_device *dev = crtc->base.dev;
7954         struct drm_i915_private *dev_priv = to_i915(dev);
7955         const struct intel_limit *limit;
7956         int refclk = 96000;
7957
7958         memset(&crtc_state->dpll_hw_state, 0,
7959                sizeof(crtc_state->dpll_hw_state));
7960
7961         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
7962                 if (intel_panel_use_ssc(dev_priv)) {
7963                         refclk = dev_priv->vbt.lvds_ssc_freq;
7964                         DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n", refclk);
7965                 }
7966
7967                 limit = &intel_limits_pineview_lvds;
7968         } else {
7969                 limit = &intel_limits_pineview_sdvo;
7970         }
7971
7972         if (!crtc_state->clock_set &&
7973             !pnv_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
7974                                 refclk, NULL, &crtc_state->dpll)) {
7975                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
7976                 return -EINVAL;
7977         }
7978
7979         i9xx_compute_dpll(crtc, crtc_state, NULL);
7980
7981         return 0;
7982 }
7983
7984 static int i9xx_crtc_compute_clock(struct intel_crtc *crtc,
7985                                    struct intel_crtc_state *crtc_state)
7986 {
7987         struct drm_device *dev = crtc->base.dev;
7988         struct drm_i915_private *dev_priv = to_i915(dev);
7989         const struct intel_limit *limit;
7990         int refclk = 96000;
7991
7992         memset(&crtc_state->dpll_hw_state, 0,
7993                sizeof(crtc_state->dpll_hw_state));
7994
7995         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
7996                 if (intel_panel_use_ssc(dev_priv)) {
7997                         refclk = dev_priv->vbt.lvds_ssc_freq;
7998                         DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n", refclk);
7999                 }
8000
8001                 limit = &intel_limits_i9xx_lvds;
8002         } else {
8003                 limit = &intel_limits_i9xx_sdvo;
8004         }
8005
8006         if (!crtc_state->clock_set &&
8007             !i9xx_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
8008                                  refclk, NULL, &crtc_state->dpll)) {
8009                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
8010                 return -EINVAL;
8011         }
8012
8013         i9xx_compute_dpll(crtc, crtc_state, NULL);
8014
8015         return 0;
8016 }
8017
8018 static int chv_crtc_compute_clock(struct intel_crtc *crtc,
8019                                   struct intel_crtc_state *crtc_state)
8020 {
8021         int refclk = 100000;
8022         const struct intel_limit *limit = &intel_limits_chv;
8023
8024         memset(&crtc_state->dpll_hw_state, 0,
8025                sizeof(crtc_state->dpll_hw_state));
8026
8027         if (!crtc_state->clock_set &&
8028             !chv_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
8029                                 refclk, NULL, &crtc_state->dpll)) {
8030                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
8031                 return -EINVAL;
8032         }
8033
8034         chv_compute_dpll(crtc, crtc_state);
8035
8036         return 0;
8037 }
8038
8039 static int vlv_crtc_compute_clock(struct intel_crtc *crtc,
8040                                   struct intel_crtc_state *crtc_state)
8041 {
8042         int refclk = 100000;
8043         const struct intel_limit *limit = &intel_limits_vlv;
8044
8045         memset(&crtc_state->dpll_hw_state, 0,
8046                sizeof(crtc_state->dpll_hw_state));
8047
8048         if (!crtc_state->clock_set &&
8049             !vlv_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
8050                                 refclk, NULL, &crtc_state->dpll)) {
8051                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
8052                 return -EINVAL;
8053         }
8054
8055         vlv_compute_dpll(crtc, crtc_state);
8056
8057         return 0;
8058 }
8059
8060 static void i9xx_get_pfit_config(struct intel_crtc *crtc,
8061                                  struct intel_crtc_state *pipe_config)
8062 {
8063         struct drm_device *dev = crtc->base.dev;
8064         struct drm_i915_private *dev_priv = to_i915(dev);
8065         uint32_t tmp;
8066
8067         if (INTEL_INFO(dev)->gen <= 3 && (IS_I830(dev) || !IS_MOBILE(dev)))
8068                 return;
8069
8070         tmp = I915_READ(PFIT_CONTROL);
8071         if (!(tmp & PFIT_ENABLE))
8072                 return;
8073
8074         /* Check whether the pfit is attached to our pipe. */
8075         if (INTEL_INFO(dev)->gen < 4) {
8076                 if (crtc->pipe != PIPE_B)
8077                         return;
8078         } else {
8079                 if ((tmp & PFIT_PIPE_MASK) != (crtc->pipe << PFIT_PIPE_SHIFT))
8080                         return;
8081         }
8082
8083         pipe_config->gmch_pfit.control = tmp;
8084         pipe_config->gmch_pfit.pgm_ratios = I915_READ(PFIT_PGM_RATIOS);
8085 }
8086
8087 static void vlv_crtc_clock_get(struct intel_crtc *crtc,
8088                                struct intel_crtc_state *pipe_config)
8089 {
8090         struct drm_device *dev = crtc->base.dev;
8091         struct drm_i915_private *dev_priv = to_i915(dev);
8092         int pipe = pipe_config->cpu_transcoder;
8093         struct dpll clock;
8094         u32 mdiv;
8095         int refclk = 100000;
8096
8097         /* In case of DSI, DPLL will not be used */
8098         if ((pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE) == 0)
8099                 return;
8100
8101         mutex_lock(&dev_priv->sb_lock);
8102         mdiv = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW3(pipe));
8103         mutex_unlock(&dev_priv->sb_lock);
8104
8105         clock.m1 = (mdiv >> DPIO_M1DIV_SHIFT) & 7;
8106         clock.m2 = mdiv & DPIO_M2DIV_MASK;
8107         clock.n = (mdiv >> DPIO_N_SHIFT) & 0xf;
8108         clock.p1 = (mdiv >> DPIO_P1_SHIFT) & 7;
8109         clock.p2 = (mdiv >> DPIO_P2_SHIFT) & 0x1f;
8110
8111         pipe_config->port_clock = vlv_calc_dpll_params(refclk, &clock);
8112 }
8113
8114 static void
8115 i9xx_get_initial_plane_config(struct intel_crtc *crtc,
8116                               struct intel_initial_plane_config *plane_config)
8117 {
8118         struct drm_device *dev = crtc->base.dev;
8119         struct drm_i915_private *dev_priv = to_i915(dev);
8120         u32 val, base, offset;
8121         int pipe = crtc->pipe, plane = crtc->plane;
8122         int fourcc, pixel_format;
8123         unsigned int aligned_height;
8124         struct drm_framebuffer *fb;
8125         struct intel_framebuffer *intel_fb;
8126
8127         val = I915_READ(DSPCNTR(plane));
8128         if (!(val & DISPLAY_PLANE_ENABLE))
8129                 return;
8130
8131         intel_fb = kzalloc(sizeof(*intel_fb), GFP_KERNEL);
8132         if (!intel_fb) {
8133                 DRM_DEBUG_KMS("failed to alloc fb\n");
8134                 return;
8135         }
8136
8137         fb = &intel_fb->base;
8138
8139         if (INTEL_INFO(dev)->gen >= 4) {
8140                 if (val & DISPPLANE_TILED) {
8141                         plane_config->tiling = I915_TILING_X;
8142                         fb->modifier[0] = I915_FORMAT_MOD_X_TILED;
8143                 }
8144         }
8145
8146         pixel_format = val & DISPPLANE_PIXFORMAT_MASK;
8147         fourcc = i9xx_format_to_fourcc(pixel_format);
8148         fb->pixel_format = fourcc;
8149         fb->bits_per_pixel = drm_format_plane_cpp(fourcc, 0) * 8;
8150
8151         if (INTEL_INFO(dev)->gen >= 4) {
8152                 if (plane_config->tiling)
8153                         offset = I915_READ(DSPTILEOFF(plane));
8154                 else
8155                         offset = I915_READ(DSPLINOFF(plane));
8156                 base = I915_READ(DSPSURF(plane)) & 0xfffff000;
8157         } else {
8158                 base = I915_READ(DSPADDR(plane));
8159         }
8160         plane_config->base = base;
8161
8162         val = I915_READ(PIPESRC(pipe));
8163         fb->width = ((val >> 16) & 0xfff) + 1;
8164         fb->height = ((val >> 0) & 0xfff) + 1;
8165
8166         val = I915_READ(DSPSTRIDE(pipe));
8167         fb->pitches[0] = val & 0xffffffc0;
8168
8169         aligned_height = intel_fb_align_height(dev, fb->height,
8170                                                fb->pixel_format,
8171                                                fb->modifier[0]);
8172
8173         plane_config->size = fb->pitches[0] * aligned_height;
8174
8175         DRM_DEBUG_KMS("pipe/plane %c/%d with fb: size=%dx%d@%d, offset=%x, pitch %d, size 0x%x\n",
8176                       pipe_name(pipe), plane, fb->width, fb->height,
8177                       fb->bits_per_pixel, base, fb->pitches[0],
8178                       plane_config->size);
8179
8180         plane_config->fb = intel_fb;
8181 }
8182
8183 static void chv_crtc_clock_get(struct intel_crtc *crtc,
8184                                struct intel_crtc_state *pipe_config)
8185 {
8186         struct drm_device *dev = crtc->base.dev;
8187         struct drm_i915_private *dev_priv = to_i915(dev);
8188         int pipe = pipe_config->cpu_transcoder;
8189         enum dpio_channel port = vlv_pipe_to_channel(pipe);
8190         struct dpll clock;
8191         u32 cmn_dw13, pll_dw0, pll_dw1, pll_dw2, pll_dw3;
8192         int refclk = 100000;
8193
8194         /* In case of DSI, DPLL will not be used */
8195         if ((pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE) == 0)
8196                 return;
8197
8198         mutex_lock(&dev_priv->sb_lock);
8199         cmn_dw13 = vlv_dpio_read(dev_priv, pipe, CHV_CMN_DW13(port));
8200         pll_dw0 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW0(port));
8201         pll_dw1 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW1(port));
8202         pll_dw2 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW2(port));
8203         pll_dw3 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW3(port));
8204         mutex_unlock(&dev_priv->sb_lock);
8205
8206         clock.m1 = (pll_dw1 & 0x7) == DPIO_CHV_M1_DIV_BY_2 ? 2 : 0;
8207         clock.m2 = (pll_dw0 & 0xff) << 22;
8208         if (pll_dw3 & DPIO_CHV_FRAC_DIV_EN)
8209                 clock.m2 |= pll_dw2 & 0x3fffff;
8210         clock.n = (pll_dw1 >> DPIO_CHV_N_DIV_SHIFT) & 0xf;
8211         clock.p1 = (cmn_dw13 >> DPIO_CHV_P1_DIV_SHIFT) & 0x7;
8212         clock.p2 = (cmn_dw13 >> DPIO_CHV_P2_DIV_SHIFT) & 0x1f;
8213
8214         pipe_config->port_clock = chv_calc_dpll_params(refclk, &clock);
8215 }
8216
8217 static bool i9xx_get_pipe_config(struct intel_crtc *crtc,
8218                                  struct intel_crtc_state *pipe_config)
8219 {
8220         struct drm_device *dev = crtc->base.dev;
8221         struct drm_i915_private *dev_priv = to_i915(dev);
8222         enum intel_display_power_domain power_domain;
8223         uint32_t tmp;
8224         bool ret;
8225
8226         power_domain = POWER_DOMAIN_PIPE(crtc->pipe);
8227         if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
8228                 return false;
8229
8230         pipe_config->cpu_transcoder = (enum transcoder) crtc->pipe;
8231         pipe_config->shared_dpll = NULL;
8232
8233         ret = false;
8234
8235         tmp = I915_READ(PIPECONF(crtc->pipe));
8236         if (!(tmp & PIPECONF_ENABLE))
8237                 goto out;
8238
8239         if (IS_G4X(dev) || IS_VALLEYVIEW(dev) || IS_CHERRYVIEW(dev)) {
8240                 switch (tmp & PIPECONF_BPC_MASK) {
8241                 case PIPECONF_6BPC:
8242                         pipe_config->pipe_bpp = 18;
8243                         break;
8244                 case PIPECONF_8BPC:
8245                         pipe_config->pipe_bpp = 24;
8246                         break;
8247                 case PIPECONF_10BPC:
8248                         pipe_config->pipe_bpp = 30;
8249                         break;
8250                 default:
8251                         break;
8252                 }
8253         }
8254
8255         if ((IS_VALLEYVIEW(dev) || IS_CHERRYVIEW(dev)) &&
8256             (tmp & PIPECONF_COLOR_RANGE_SELECT))
8257                 pipe_config->limited_color_range = true;
8258
8259         if (INTEL_INFO(dev)->gen < 4)
8260                 pipe_config->double_wide = tmp & PIPECONF_DOUBLE_WIDE;
8261
8262         intel_get_pipe_timings(crtc, pipe_config);
8263         intel_get_pipe_src_size(crtc, pipe_config);
8264
8265         i9xx_get_pfit_config(crtc, pipe_config);
8266
8267         if (INTEL_INFO(dev)->gen >= 4) {
8268                 /* No way to read it out on pipes B and C */
8269                 if (IS_CHERRYVIEW(dev) && crtc->pipe != PIPE_A)
8270                         tmp = dev_priv->chv_dpll_md[crtc->pipe];
8271                 else
8272                         tmp = I915_READ(DPLL_MD(crtc->pipe));
8273                 pipe_config->pixel_multiplier =
8274                         ((tmp & DPLL_MD_UDI_MULTIPLIER_MASK)
8275                          >> DPLL_MD_UDI_MULTIPLIER_SHIFT) + 1;
8276                 pipe_config->dpll_hw_state.dpll_md = tmp;
8277         } else if (IS_I945G(dev) || IS_I945GM(dev) || IS_G33(dev)) {
8278                 tmp = I915_READ(DPLL(crtc->pipe));
8279                 pipe_config->pixel_multiplier =
8280                         ((tmp & SDVO_MULTIPLIER_MASK)
8281                          >> SDVO_MULTIPLIER_SHIFT_HIRES) + 1;
8282         } else {
8283                 /* Note that on i915G/GM the pixel multiplier is in the sdvo
8284                  * port and will be fixed up in the encoder->get_config
8285                  * function. */
8286                 pipe_config->pixel_multiplier = 1;
8287         }
8288         pipe_config->dpll_hw_state.dpll = I915_READ(DPLL(crtc->pipe));
8289         if (!IS_VALLEYVIEW(dev) && !IS_CHERRYVIEW(dev)) {
8290                 /*
8291                  * DPLL_DVO_2X_MODE must be enabled for both DPLLs
8292                  * on 830. Filter it out here so that we don't
8293                  * report errors due to that.
8294                  */
8295                 if (IS_I830(dev))
8296                         pipe_config->dpll_hw_state.dpll &= ~DPLL_DVO_2X_MODE;
8297
8298                 pipe_config->dpll_hw_state.fp0 = I915_READ(FP0(crtc->pipe));
8299                 pipe_config->dpll_hw_state.fp1 = I915_READ(FP1(crtc->pipe));
8300         } else {
8301                 /* Mask out read-only status bits. */
8302                 pipe_config->dpll_hw_state.dpll &= ~(DPLL_LOCK_VLV |
8303                                                      DPLL_PORTC_READY_MASK |
8304                                                      DPLL_PORTB_READY_MASK);
8305         }
8306
8307         if (IS_CHERRYVIEW(dev))
8308                 chv_crtc_clock_get(crtc, pipe_config);
8309         else if (IS_VALLEYVIEW(dev))
8310                 vlv_crtc_clock_get(crtc, pipe_config);
8311         else
8312                 i9xx_crtc_clock_get(crtc, pipe_config);
8313
8314         /*
8315          * Normally the dotclock is filled in by the encoder .get_config()
8316          * but in case the pipe is enabled w/o any ports we need a sane
8317          * default.
8318          */
8319         pipe_config->base.adjusted_mode.crtc_clock =
8320                 pipe_config->port_clock / pipe_config->pixel_multiplier;
8321
8322         ret = true;
8323
8324 out:
8325         intel_display_power_put(dev_priv, power_domain);
8326
8327         return ret;
8328 }
8329
8330 static void ironlake_init_pch_refclk(struct drm_device *dev)
8331 {
8332         struct drm_i915_private *dev_priv = to_i915(dev);
8333         struct intel_encoder *encoder;
8334         int i;
8335         u32 val, final;
8336         bool has_lvds = false;
8337         bool has_cpu_edp = false;
8338         bool has_panel = false;
8339         bool has_ck505 = false;
8340         bool can_ssc = false;
8341         bool using_ssc_source = false;
8342
8343         /* We need to take the global config into account */
8344         for_each_intel_encoder(dev, encoder) {
8345                 switch (encoder->type) {
8346                 case INTEL_OUTPUT_LVDS:
8347                         has_panel = true;
8348                         has_lvds = true;
8349                         break;
8350                 case INTEL_OUTPUT_EDP:
8351                         has_panel = true;
8352                         if (enc_to_dig_port(&encoder->base)->port == PORT_A)
8353                                 has_cpu_edp = true;
8354                         break;
8355                 default:
8356                         break;
8357                 }
8358         }
8359
8360         if (HAS_PCH_IBX(dev)) {
8361                 has_ck505 = dev_priv->vbt.display_clock_mode;
8362                 can_ssc = has_ck505;
8363         } else {
8364                 has_ck505 = false;
8365                 can_ssc = true;
8366         }
8367
8368         /* Check if any DPLLs are using the SSC source */
8369         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
8370                 u32 temp = I915_READ(PCH_DPLL(i));
8371
8372                 if (!(temp & DPLL_VCO_ENABLE))
8373                         continue;
8374
8375                 if ((temp & PLL_REF_INPUT_MASK) ==
8376                     PLLB_REF_INPUT_SPREADSPECTRUMIN) {
8377                         using_ssc_source = true;
8378                         break;
8379                 }
8380         }
8381
8382         DRM_DEBUG_KMS("has_panel %d has_lvds %d has_ck505 %d using_ssc_source %d\n",
8383                       has_panel, has_lvds, has_ck505, using_ssc_source);
8384
8385         /* Ironlake: try to setup display ref clock before DPLL
8386          * enabling. This is only under driver's control after
8387          * PCH B stepping, previous chipset stepping should be
8388          * ignoring this setting.
8389          */
8390         val = I915_READ(PCH_DREF_CONTROL);
8391
8392         /* As we must carefully and slowly disable/enable each source in turn,
8393          * compute the final state we want first and check if we need to
8394          * make any changes at all.
8395          */
8396         final = val;
8397         final &= ~DREF_NONSPREAD_SOURCE_MASK;
8398         if (has_ck505)
8399                 final |= DREF_NONSPREAD_CK505_ENABLE;
8400         else
8401                 final |= DREF_NONSPREAD_SOURCE_ENABLE;
8402
8403         final &= ~DREF_SSC_SOURCE_MASK;
8404         final &= ~DREF_CPU_SOURCE_OUTPUT_MASK;
8405         final &= ~DREF_SSC1_ENABLE;
8406
8407         if (has_panel) {
8408                 final |= DREF_SSC_SOURCE_ENABLE;
8409
8410                 if (intel_panel_use_ssc(dev_priv) && can_ssc)
8411                         final |= DREF_SSC1_ENABLE;
8412
8413                 if (has_cpu_edp) {
8414                         if (intel_panel_use_ssc(dev_priv) && can_ssc)
8415                                 final |= DREF_CPU_SOURCE_OUTPUT_DOWNSPREAD;
8416                         else
8417                                 final |= DREF_CPU_SOURCE_OUTPUT_NONSPREAD;
8418                 } else
8419                         final |= DREF_CPU_SOURCE_OUTPUT_DISABLE;
8420         } else if (using_ssc_source) {
8421                 final |= DREF_SSC_SOURCE_ENABLE;
8422                 final |= DREF_SSC1_ENABLE;
8423         }
8424
8425         if (final == val)
8426                 return;
8427
8428         /* Always enable nonspread source */
8429         val &= ~DREF_NONSPREAD_SOURCE_MASK;
8430
8431         if (has_ck505)
8432                 val |= DREF_NONSPREAD_CK505_ENABLE;
8433         else
8434                 val |= DREF_NONSPREAD_SOURCE_ENABLE;
8435
8436         if (has_panel) {
8437                 val &= ~DREF_SSC_SOURCE_MASK;
8438                 val |= DREF_SSC_SOURCE_ENABLE;
8439
8440                 /* SSC must be turned on before enabling the CPU output  */
8441                 if (intel_panel_use_ssc(dev_priv) && can_ssc) {
8442                         DRM_DEBUG_KMS("Using SSC on panel\n");
8443                         val |= DREF_SSC1_ENABLE;
8444                 } else
8445                         val &= ~DREF_SSC1_ENABLE;
8446
8447                 /* Get SSC going before enabling the outputs */
8448                 I915_WRITE(PCH_DREF_CONTROL, val);
8449                 POSTING_READ(PCH_DREF_CONTROL);
8450                 udelay(200);
8451
8452                 val &= ~DREF_CPU_SOURCE_OUTPUT_MASK;
8453
8454                 /* Enable CPU source on CPU attached eDP */
8455                 if (has_cpu_edp) {
8456                         if (intel_panel_use_ssc(dev_priv) && can_ssc) {
8457                                 DRM_DEBUG_KMS("Using SSC on eDP\n");
8458                                 val |= DREF_CPU_SOURCE_OUTPUT_DOWNSPREAD;
8459                         } else
8460                                 val |= DREF_CPU_SOURCE_OUTPUT_NONSPREAD;
8461                 } else
8462                         val |= DREF_CPU_SOURCE_OUTPUT_DISABLE;
8463
8464                 I915_WRITE(PCH_DREF_CONTROL, val);
8465                 POSTING_READ(PCH_DREF_CONTROL);
8466                 udelay(200);
8467         } else {
8468                 DRM_DEBUG_KMS("Disabling CPU source output\n");
8469
8470                 val &= ~DREF_CPU_SOURCE_OUTPUT_MASK;
8471
8472                 /* Turn off CPU output */
8473                 val |= DREF_CPU_SOURCE_OUTPUT_DISABLE;
8474
8475                 I915_WRITE(PCH_DREF_CONTROL, val);
8476                 POSTING_READ(PCH_DREF_CONTROL);
8477                 udelay(200);
8478
8479                 if (!using_ssc_source) {
8480                         DRM_DEBUG_KMS("Disabling SSC source\n");
8481
8482                         /* Turn off the SSC source */
8483                         val &= ~DREF_SSC_SOURCE_MASK;
8484                         val |= DREF_SSC_SOURCE_DISABLE;
8485
8486                         /* Turn off SSC1 */
8487                         val &= ~DREF_SSC1_ENABLE;
8488
8489                         I915_WRITE(PCH_DREF_CONTROL, val);
8490                         POSTING_READ(PCH_DREF_CONTROL);
8491                         udelay(200);
8492                 }
8493         }
8494
8495         BUG_ON(val != final);
8496 }
8497
8498 static void lpt_reset_fdi_mphy(struct drm_i915_private *dev_priv)
8499 {
8500         uint32_t tmp;
8501
8502         tmp = I915_READ(SOUTH_CHICKEN2);
8503         tmp |= FDI_MPHY_IOSFSB_RESET_CTL;
8504         I915_WRITE(SOUTH_CHICKEN2, tmp);
8505
8506         if (wait_for_us(I915_READ(SOUTH_CHICKEN2) &
8507                         FDI_MPHY_IOSFSB_RESET_STATUS, 100))
8508                 DRM_ERROR("FDI mPHY reset assert timeout\n");
8509
8510         tmp = I915_READ(SOUTH_CHICKEN2);
8511         tmp &= ~FDI_MPHY_IOSFSB_RESET_CTL;
8512         I915_WRITE(SOUTH_CHICKEN2, tmp);
8513
8514         if (wait_for_us((I915_READ(SOUTH_CHICKEN2) &
8515                          FDI_MPHY_IOSFSB_RESET_STATUS) == 0, 100))
8516                 DRM_ERROR("FDI mPHY reset de-assert timeout\n");
8517 }
8518
8519 /* WaMPhyProgramming:hsw */
8520 static void lpt_program_fdi_mphy(struct drm_i915_private *dev_priv)
8521 {
8522         uint32_t tmp;
8523
8524         tmp = intel_sbi_read(dev_priv, 0x8008, SBI_MPHY);
8525         tmp &= ~(0xFF << 24);
8526         tmp |= (0x12 << 24);
8527         intel_sbi_write(dev_priv, 0x8008, tmp, SBI_MPHY);
8528
8529         tmp = intel_sbi_read(dev_priv, 0x2008, SBI_MPHY);
8530         tmp |= (1 << 11);
8531         intel_sbi_write(dev_priv, 0x2008, tmp, SBI_MPHY);
8532
8533         tmp = intel_sbi_read(dev_priv, 0x2108, SBI_MPHY);
8534         tmp |= (1 << 11);
8535         intel_sbi_write(dev_priv, 0x2108, tmp, SBI_MPHY);
8536
8537         tmp = intel_sbi_read(dev_priv, 0x206C, SBI_MPHY);
8538         tmp |= (1 << 24) | (1 << 21) | (1 << 18);
8539         intel_sbi_write(dev_priv, 0x206C, tmp, SBI_MPHY);
8540
8541         tmp = intel_sbi_read(dev_priv, 0x216C, SBI_MPHY);
8542         tmp |= (1 << 24) | (1 << 21) | (1 << 18);
8543         intel_sbi_write(dev_priv, 0x216C, tmp, SBI_MPHY);
8544
8545         tmp = intel_sbi_read(dev_priv, 0x2080, SBI_MPHY);
8546         tmp &= ~(7 << 13);
8547         tmp |= (5 << 13);
8548         intel_sbi_write(dev_priv, 0x2080, tmp, SBI_MPHY);
8549
8550         tmp = intel_sbi_read(dev_priv, 0x2180, SBI_MPHY);
8551         tmp &= ~(7 << 13);
8552         tmp |= (5 << 13);
8553         intel_sbi_write(dev_priv, 0x2180, tmp, SBI_MPHY);
8554
8555         tmp = intel_sbi_read(dev_priv, 0x208C, SBI_MPHY);
8556         tmp &= ~0xFF;
8557         tmp |= 0x1C;
8558         intel_sbi_write(dev_priv, 0x208C, tmp, SBI_MPHY);
8559
8560         tmp = intel_sbi_read(dev_priv, 0x218C, SBI_MPHY);
8561         tmp &= ~0xFF;
8562         tmp |= 0x1C;
8563         intel_sbi_write(dev_priv, 0x218C, tmp, SBI_MPHY);
8564
8565         tmp = intel_sbi_read(dev_priv, 0x2098, SBI_MPHY);
8566         tmp &= ~(0xFF << 16);
8567         tmp |= (0x1C << 16);
8568         intel_sbi_write(dev_priv, 0x2098, tmp, SBI_MPHY);
8569
8570         tmp = intel_sbi_read(dev_priv, 0x2198, SBI_MPHY);
8571         tmp &= ~(0xFF << 16);
8572         tmp |= (0x1C << 16);
8573         intel_sbi_write(dev_priv, 0x2198, tmp, SBI_MPHY);
8574
8575         tmp = intel_sbi_read(dev_priv, 0x20C4, SBI_MPHY);
8576         tmp |= (1 << 27);
8577         intel_sbi_write(dev_priv, 0x20C4, tmp, SBI_MPHY);
8578
8579         tmp = intel_sbi_read(dev_priv, 0x21C4, SBI_MPHY);
8580         tmp |= (1 << 27);
8581         intel_sbi_write(dev_priv, 0x21C4, tmp, SBI_MPHY);
8582
8583         tmp = intel_sbi_read(dev_priv, 0x20EC, SBI_MPHY);
8584         tmp &= ~(0xF << 28);
8585         tmp |= (4 << 28);
8586         intel_sbi_write(dev_priv, 0x20EC, tmp, SBI_MPHY);
8587
8588         tmp = intel_sbi_read(dev_priv, 0x21EC, SBI_MPHY);
8589         tmp &= ~(0xF << 28);
8590         tmp |= (4 << 28);
8591         intel_sbi_write(dev_priv, 0x21EC, tmp, SBI_MPHY);
8592 }
8593
8594 /* Implements 3 different sequences from BSpec chapter "Display iCLK
8595  * Programming" based on the parameters passed:
8596  * - Sequence to enable CLKOUT_DP
8597  * - Sequence to enable CLKOUT_DP without spread
8598  * - Sequence to enable CLKOUT_DP for FDI usage and configure PCH FDI I/O
8599  */
8600 static void lpt_enable_clkout_dp(struct drm_device *dev, bool with_spread,
8601                                  bool with_fdi)
8602 {
8603         struct drm_i915_private *dev_priv = to_i915(dev);
8604         uint32_t reg, tmp;
8605
8606         if (WARN(with_fdi && !with_spread, "FDI requires downspread\n"))
8607                 with_spread = true;
8608         if (WARN(HAS_PCH_LPT_LP(dev) && with_fdi, "LP PCH doesn't have FDI\n"))
8609                 with_fdi = false;
8610
8611         mutex_lock(&dev_priv->sb_lock);
8612
8613         tmp = intel_sbi_read(dev_priv, SBI_SSCCTL, SBI_ICLK);
8614         tmp &= ~SBI_SSCCTL_DISABLE;
8615         tmp |= SBI_SSCCTL_PATHALT;
8616         intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
8617
8618         udelay(24);
8619
8620         if (with_spread) {
8621                 tmp = intel_sbi_read(dev_priv, SBI_SSCCTL, SBI_ICLK);
8622                 tmp &= ~SBI_SSCCTL_PATHALT;
8623                 intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
8624
8625                 if (with_fdi) {
8626                         lpt_reset_fdi_mphy(dev_priv);
8627                         lpt_program_fdi_mphy(dev_priv);
8628                 }
8629         }
8630
8631         reg = HAS_PCH_LPT_LP(dev) ? SBI_GEN0 : SBI_DBUFF0;
8632         tmp = intel_sbi_read(dev_priv, reg, SBI_ICLK);
8633         tmp |= SBI_GEN0_CFG_BUFFENABLE_DISABLE;
8634         intel_sbi_write(dev_priv, reg, tmp, SBI_ICLK);
8635
8636         mutex_unlock(&dev_priv->sb_lock);
8637 }
8638
8639 /* Sequence to disable CLKOUT_DP */
8640 static void lpt_disable_clkout_dp(struct drm_device *dev)
8641 {
8642         struct drm_i915_private *dev_priv = to_i915(dev);
8643         uint32_t reg, tmp;
8644
8645         mutex_lock(&dev_priv->sb_lock);
8646
8647         reg = HAS_PCH_LPT_LP(dev) ? SBI_GEN0 : SBI_DBUFF0;
8648         tmp = intel_sbi_read(dev_priv, reg, SBI_ICLK);
8649         tmp &= ~SBI_GEN0_CFG_BUFFENABLE_DISABLE;
8650         intel_sbi_write(dev_priv, reg, tmp, SBI_ICLK);
8651
8652         tmp = intel_sbi_read(dev_priv, SBI_SSCCTL, SBI_ICLK);
8653         if (!(tmp & SBI_SSCCTL_DISABLE)) {
8654                 if (!(tmp & SBI_SSCCTL_PATHALT)) {
8655                         tmp |= SBI_SSCCTL_PATHALT;
8656                         intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
8657                         udelay(32);
8658                 }
8659                 tmp |= SBI_SSCCTL_DISABLE;
8660                 intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
8661         }
8662
8663         mutex_unlock(&dev_priv->sb_lock);
8664 }
8665
8666 #define BEND_IDX(steps) ((50 + (steps)) / 5)
8667
8668 static const uint16_t sscdivintphase[] = {
8669         [BEND_IDX( 50)] = 0x3B23,
8670         [BEND_IDX( 45)] = 0x3B23,
8671         [BEND_IDX( 40)] = 0x3C23,
8672         [BEND_IDX( 35)] = 0x3C23,
8673         [BEND_IDX( 30)] = 0x3D23,
8674         [BEND_IDX( 25)] = 0x3D23,
8675         [BEND_IDX( 20)] = 0x3E23,
8676         [BEND_IDX( 15)] = 0x3E23,
8677         [BEND_IDX( 10)] = 0x3F23,
8678         [BEND_IDX(  5)] = 0x3F23,
8679         [BEND_IDX(  0)] = 0x0025,
8680         [BEND_IDX( -5)] = 0x0025,
8681         [BEND_IDX(-10)] = 0x0125,
8682         [BEND_IDX(-15)] = 0x0125,
8683         [BEND_IDX(-20)] = 0x0225,
8684         [BEND_IDX(-25)] = 0x0225,
8685         [BEND_IDX(-30)] = 0x0325,
8686         [BEND_IDX(-35)] = 0x0325,
8687         [BEND_IDX(-40)] = 0x0425,
8688         [BEND_IDX(-45)] = 0x0425,
8689         [BEND_IDX(-50)] = 0x0525,
8690 };
8691
8692 /*
8693  * Bend CLKOUT_DP
8694  * steps -50 to 50 inclusive, in steps of 5
8695  * < 0 slow down the clock, > 0 speed up the clock, 0 == no bend (135MHz)
8696  * change in clock period = -(steps / 10) * 5.787 ps
8697  */
8698 static void lpt_bend_clkout_dp(struct drm_i915_private *dev_priv, int steps)
8699 {
8700         uint32_t tmp;
8701         int idx = BEND_IDX(steps);
8702
8703         if (WARN_ON(steps % 5 != 0))
8704                 return;
8705
8706         if (WARN_ON(idx >= ARRAY_SIZE(sscdivintphase)))
8707                 return;
8708
8709         mutex_lock(&dev_priv->sb_lock);
8710
8711         if (steps % 10 != 0)
8712                 tmp = 0xAAAAAAAB;
8713         else
8714                 tmp = 0x00000000;
8715         intel_sbi_write(dev_priv, SBI_SSCDITHPHASE, tmp, SBI_ICLK);
8716
8717         tmp = intel_sbi_read(dev_priv, SBI_SSCDIVINTPHASE, SBI_ICLK);
8718         tmp &= 0xffff0000;
8719         tmp |= sscdivintphase[idx];
8720         intel_sbi_write(dev_priv, SBI_SSCDIVINTPHASE, tmp, SBI_ICLK);
8721
8722         mutex_unlock(&dev_priv->sb_lock);
8723 }
8724
8725 #undef BEND_IDX
8726
8727 static void lpt_init_pch_refclk(struct drm_device *dev)
8728 {
8729         struct intel_encoder *encoder;
8730         bool has_vga = false;
8731
8732         for_each_intel_encoder(dev, encoder) {
8733                 switch (encoder->type) {
8734                 case INTEL_OUTPUT_ANALOG:
8735                         has_vga = true;
8736                         break;
8737                 default:
8738                         break;
8739                 }
8740         }
8741
8742         if (has_vga) {
8743                 lpt_bend_clkout_dp(to_i915(dev), 0);
8744                 lpt_enable_clkout_dp(dev, true, true);
8745         } else {
8746                 lpt_disable_clkout_dp(dev);
8747         }
8748 }
8749
8750 /*
8751  * Initialize reference clocks when the driver loads
8752  */
8753 void intel_init_pch_refclk(struct drm_device *dev)
8754 {
8755         if (HAS_PCH_IBX(dev) || HAS_PCH_CPT(dev))
8756                 ironlake_init_pch_refclk(dev);
8757         else if (HAS_PCH_LPT(dev))
8758                 lpt_init_pch_refclk(dev);
8759 }
8760
8761 static void ironlake_set_pipeconf(struct drm_crtc *crtc)
8762 {
8763         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
8764         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
8765         int pipe = intel_crtc->pipe;
8766         uint32_t val;
8767
8768         val = 0;
8769
8770         switch (intel_crtc->config->pipe_bpp) {
8771         case 18:
8772                 val |= PIPECONF_6BPC;
8773                 break;
8774         case 24:
8775                 val |= PIPECONF_8BPC;
8776                 break;
8777         case 30:
8778                 val |= PIPECONF_10BPC;
8779                 break;
8780         case 36:
8781                 val |= PIPECONF_12BPC;
8782                 break;
8783         default:
8784                 /* Case prevented by intel_choose_pipe_bpp_dither. */
8785                 BUG();
8786         }
8787
8788         if (intel_crtc->config->dither)
8789                 val |= (PIPECONF_DITHER_EN | PIPECONF_DITHER_TYPE_SP);
8790
8791         if (intel_crtc->config->base.adjusted_mode.flags & DRM_MODE_FLAG_INTERLACE)
8792                 val |= PIPECONF_INTERLACED_ILK;
8793         else
8794                 val |= PIPECONF_PROGRESSIVE;
8795
8796         if (intel_crtc->config->limited_color_range)
8797                 val |= PIPECONF_COLOR_RANGE_SELECT;
8798
8799         I915_WRITE(PIPECONF(pipe), val);
8800         POSTING_READ(PIPECONF(pipe));
8801 }
8802
8803 static void haswell_set_pipeconf(struct drm_crtc *crtc)
8804 {
8805         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
8806         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
8807         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
8808         u32 val = 0;
8809
8810         if (IS_HASWELL(dev_priv) && intel_crtc->config->dither)
8811                 val |= (PIPECONF_DITHER_EN | PIPECONF_DITHER_TYPE_SP);
8812
8813         if (intel_crtc->config->base.adjusted_mode.flags & DRM_MODE_FLAG_INTERLACE)
8814                 val |= PIPECONF_INTERLACED_ILK;
8815         else
8816                 val |= PIPECONF_PROGRESSIVE;
8817
8818         I915_WRITE(PIPECONF(cpu_transcoder), val);
8819         POSTING_READ(PIPECONF(cpu_transcoder));
8820 }
8821
8822 static void haswell_set_pipemisc(struct drm_crtc *crtc)
8823 {
8824         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
8825         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
8826
8827         if (IS_BROADWELL(dev_priv) || INTEL_INFO(dev_priv)->gen >= 9) {
8828                 u32 val = 0;
8829
8830                 switch (intel_crtc->config->pipe_bpp) {
8831                 case 18:
8832                         val |= PIPEMISC_DITHER_6_BPC;
8833                         break;
8834                 case 24:
8835                         val |= PIPEMISC_DITHER_8_BPC;
8836                         break;
8837                 case 30:
8838                         val |= PIPEMISC_DITHER_10_BPC;
8839                         break;
8840                 case 36:
8841                         val |= PIPEMISC_DITHER_12_BPC;
8842                         break;
8843                 default:
8844                         /* Case prevented by pipe_config_set_bpp. */
8845                         BUG();
8846                 }
8847
8848                 if (intel_crtc->config->dither)
8849                         val |= PIPEMISC_DITHER_ENABLE | PIPEMISC_DITHER_TYPE_SP;
8850
8851                 I915_WRITE(PIPEMISC(intel_crtc->pipe), val);
8852         }
8853 }
8854
8855 int ironlake_get_lanes_required(int target_clock, int link_bw, int bpp)
8856 {
8857         /*
8858          * Account for spread spectrum to avoid
8859          * oversubscribing the link. Max center spread
8860          * is 2.5%; use 5% for safety's sake.
8861          */
8862         u32 bps = target_clock * bpp * 21 / 20;
8863         return DIV_ROUND_UP(bps, link_bw * 8);
8864 }
8865
8866 static bool ironlake_needs_fb_cb_tune(struct dpll *dpll, int factor)
8867 {
8868         return i9xx_dpll_compute_m(dpll) < factor * dpll->n;
8869 }
8870
8871 static void ironlake_compute_dpll(struct intel_crtc *intel_crtc,
8872                                   struct intel_crtc_state *crtc_state,
8873                                   struct dpll *reduced_clock)
8874 {
8875         struct drm_crtc *crtc = &intel_crtc->base;
8876         struct drm_device *dev = crtc->dev;
8877         struct drm_i915_private *dev_priv = to_i915(dev);
8878         u32 dpll, fp, fp2;
8879         int factor;
8880
8881         /* Enable autotuning of the PLL clock (if permissible) */
8882         factor = 21;
8883         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
8884                 if ((intel_panel_use_ssc(dev_priv) &&
8885                      dev_priv->vbt.lvds_ssc_freq == 100000) ||
8886                     (HAS_PCH_IBX(dev) && intel_is_dual_link_lvds(dev)))
8887                         factor = 25;
8888         } else if (crtc_state->sdvo_tv_clock)
8889                 factor = 20;
8890
8891         fp = i9xx_dpll_compute_fp(&crtc_state->dpll);
8892
8893         if (ironlake_needs_fb_cb_tune(&crtc_state->dpll, factor))
8894                 fp |= FP_CB_TUNE;
8895
8896         if (reduced_clock) {
8897                 fp2 = i9xx_dpll_compute_fp(reduced_clock);
8898
8899                 if (reduced_clock->m < factor * reduced_clock->n)
8900                         fp2 |= FP_CB_TUNE;
8901         } else {
8902                 fp2 = fp;
8903         }
8904
8905         dpll = 0;
8906
8907         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS))
8908                 dpll |= DPLLB_MODE_LVDS;
8909         else
8910                 dpll |= DPLLB_MODE_DAC_SERIAL;
8911
8912         dpll |= (crtc_state->pixel_multiplier - 1)
8913                 << PLL_REF_SDVO_HDMI_MULTIPLIER_SHIFT;
8914
8915         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_SDVO) ||
8916             intel_crtc_has_type(crtc_state, INTEL_OUTPUT_HDMI))
8917                 dpll |= DPLL_SDVO_HIGH_SPEED;
8918
8919         if (intel_crtc_has_dp_encoder(crtc_state))
8920                 dpll |= DPLL_SDVO_HIGH_SPEED;
8921
8922         /* compute bitmask from p1 value */
8923         dpll |= (1 << (crtc_state->dpll.p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT;
8924         /* also FPA1 */
8925         dpll |= (1 << (crtc_state->dpll.p1 - 1)) << DPLL_FPA1_P1_POST_DIV_SHIFT;
8926
8927         switch (crtc_state->dpll.p2) {
8928         case 5:
8929                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_5;
8930                 break;
8931         case 7:
8932                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_7;
8933                 break;
8934         case 10:
8935                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_10;
8936                 break;
8937         case 14:
8938                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_14;
8939                 break;
8940         }
8941
8942         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS) &&
8943             intel_panel_use_ssc(dev_priv))
8944                 dpll |= PLLB_REF_INPUT_SPREADSPECTRUMIN;
8945         else
8946                 dpll |= PLL_REF_INPUT_DREFCLK;
8947
8948         dpll |= DPLL_VCO_ENABLE;
8949
8950         crtc_state->dpll_hw_state.dpll = dpll;
8951         crtc_state->dpll_hw_state.fp0 = fp;
8952         crtc_state->dpll_hw_state.fp1 = fp2;
8953 }
8954
8955 static int ironlake_crtc_compute_clock(struct intel_crtc *crtc,
8956                                        struct intel_crtc_state *crtc_state)
8957 {
8958         struct drm_device *dev = crtc->base.dev;
8959         struct drm_i915_private *dev_priv = to_i915(dev);
8960         struct dpll reduced_clock;
8961         bool has_reduced_clock = false;
8962         struct intel_shared_dpll *pll;
8963         const struct intel_limit *limit;
8964         int refclk = 120000;
8965
8966         memset(&crtc_state->dpll_hw_state, 0,
8967                sizeof(crtc_state->dpll_hw_state));
8968
8969         crtc->lowfreq_avail = false;
8970
8971         /* CPU eDP is the only output that doesn't need a PCH PLL of its own. */
8972         if (!crtc_state->has_pch_encoder)
8973                 return 0;
8974
8975         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
8976                 if (intel_panel_use_ssc(dev_priv)) {
8977                         DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n",
8978                                       dev_priv->vbt.lvds_ssc_freq);
8979                         refclk = dev_priv->vbt.lvds_ssc_freq;
8980                 }
8981
8982                 if (intel_is_dual_link_lvds(dev)) {
8983                         if (refclk == 100000)
8984                                 limit = &intel_limits_ironlake_dual_lvds_100m;
8985                         else
8986                                 limit = &intel_limits_ironlake_dual_lvds;
8987                 } else {
8988                         if (refclk == 100000)
8989                                 limit = &intel_limits_ironlake_single_lvds_100m;
8990                         else
8991                                 limit = &intel_limits_ironlake_single_lvds;
8992                 }
8993         } else {
8994                 limit = &intel_limits_ironlake_dac;
8995         }
8996
8997         if (!crtc_state->clock_set &&
8998             !g4x_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
8999                                 refclk, NULL, &crtc_state->dpll)) {
9000                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
9001                 return -EINVAL;
9002         }
9003
9004         ironlake_compute_dpll(crtc, crtc_state,
9005                               has_reduced_clock ? &reduced_clock : NULL);
9006
9007         pll = intel_get_shared_dpll(crtc, crtc_state, NULL);
9008         if (pll == NULL) {
9009                 DRM_DEBUG_DRIVER("failed to find PLL for pipe %c\n",
9010                                  pipe_name(crtc->pipe));
9011                 return -EINVAL;
9012         }
9013
9014         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS) &&
9015             has_reduced_clock)
9016                 crtc->lowfreq_avail = true;
9017
9018         return 0;
9019 }
9020
9021 static void intel_pch_transcoder_get_m_n(struct intel_crtc *crtc,
9022                                          struct intel_link_m_n *m_n)
9023 {
9024         struct drm_device *dev = crtc->base.dev;
9025         struct drm_i915_private *dev_priv = to_i915(dev);
9026         enum pipe pipe = crtc->pipe;
9027
9028         m_n->link_m = I915_READ(PCH_TRANS_LINK_M1(pipe));
9029         m_n->link_n = I915_READ(PCH_TRANS_LINK_N1(pipe));
9030         m_n->gmch_m = I915_READ(PCH_TRANS_DATA_M1(pipe))
9031                 & ~TU_SIZE_MASK;
9032         m_n->gmch_n = I915_READ(PCH_TRANS_DATA_N1(pipe));
9033         m_n->tu = ((I915_READ(PCH_TRANS_DATA_M1(pipe))
9034                     & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
9035 }
9036
9037 static void intel_cpu_transcoder_get_m_n(struct intel_crtc *crtc,
9038                                          enum transcoder transcoder,
9039                                          struct intel_link_m_n *m_n,
9040                                          struct intel_link_m_n *m2_n2)
9041 {
9042         struct drm_device *dev = crtc->base.dev;
9043         struct drm_i915_private *dev_priv = to_i915(dev);
9044         enum pipe pipe = crtc->pipe;
9045
9046         if (INTEL_INFO(dev)->gen >= 5) {
9047                 m_n->link_m = I915_READ(PIPE_LINK_M1(transcoder));
9048                 m_n->link_n = I915_READ(PIPE_LINK_N1(transcoder));
9049                 m_n->gmch_m = I915_READ(PIPE_DATA_M1(transcoder))
9050                         & ~TU_SIZE_MASK;
9051                 m_n->gmch_n = I915_READ(PIPE_DATA_N1(transcoder));
9052                 m_n->tu = ((I915_READ(PIPE_DATA_M1(transcoder))
9053                             & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
9054                 /* Read M2_N2 registers only for gen < 8 (M2_N2 available for
9055                  * gen < 8) and if DRRS is supported (to make sure the
9056                  * registers are not unnecessarily read).
9057                  */
9058                 if (m2_n2 && INTEL_INFO(dev)->gen < 8 &&
9059                         crtc->config->has_drrs) {
9060                         m2_n2->link_m = I915_READ(PIPE_LINK_M2(transcoder));
9061                         m2_n2->link_n = I915_READ(PIPE_LINK_N2(transcoder));
9062                         m2_n2->gmch_m = I915_READ(PIPE_DATA_M2(transcoder))
9063                                         & ~TU_SIZE_MASK;
9064                         m2_n2->gmch_n = I915_READ(PIPE_DATA_N2(transcoder));
9065                         m2_n2->tu = ((I915_READ(PIPE_DATA_M2(transcoder))
9066                                         & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
9067                 }
9068         } else {
9069                 m_n->link_m = I915_READ(PIPE_LINK_M_G4X(pipe));
9070                 m_n->link_n = I915_READ(PIPE_LINK_N_G4X(pipe));
9071                 m_n->gmch_m = I915_READ(PIPE_DATA_M_G4X(pipe))
9072                         & ~TU_SIZE_MASK;
9073                 m_n->gmch_n = I915_READ(PIPE_DATA_N_G4X(pipe));
9074                 m_n->tu = ((I915_READ(PIPE_DATA_M_G4X(pipe))
9075                             & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
9076         }
9077 }
9078
9079 void intel_dp_get_m_n(struct intel_crtc *crtc,
9080                       struct intel_crtc_state *pipe_config)
9081 {
9082         if (pipe_config->has_pch_encoder)
9083                 intel_pch_transcoder_get_m_n(crtc, &pipe_config->dp_m_n);
9084         else
9085                 intel_cpu_transcoder_get_m_n(crtc, pipe_config->cpu_transcoder,
9086                                              &pipe_config->dp_m_n,
9087                                              &pipe_config->dp_m2_n2);
9088 }
9089
9090 static void ironlake_get_fdi_m_n_config(struct intel_crtc *crtc,
9091                                         struct intel_crtc_state *pipe_config)
9092 {
9093         intel_cpu_transcoder_get_m_n(crtc, pipe_config->cpu_transcoder,
9094                                      &pipe_config->fdi_m_n, NULL);
9095 }
9096
9097 static void skylake_get_pfit_config(struct intel_crtc *crtc,
9098                                     struct intel_crtc_state *pipe_config)
9099 {
9100         struct drm_device *dev = crtc->base.dev;
9101         struct drm_i915_private *dev_priv = to_i915(dev);
9102         struct intel_crtc_scaler_state *scaler_state = &pipe_config->scaler_state;
9103         uint32_t ps_ctrl = 0;
9104         int id = -1;
9105         int i;
9106
9107         /* find scaler attached to this pipe */
9108         for (i = 0; i < crtc->num_scalers; i++) {
9109                 ps_ctrl = I915_READ(SKL_PS_CTRL(crtc->pipe, i));
9110                 if (ps_ctrl & PS_SCALER_EN && !(ps_ctrl & PS_PLANE_SEL_MASK)) {
9111                         id = i;
9112                         pipe_config->pch_pfit.enabled = true;
9113                         pipe_config->pch_pfit.pos = I915_READ(SKL_PS_WIN_POS(crtc->pipe, i));
9114                         pipe_config->pch_pfit.size = I915_READ(SKL_PS_WIN_SZ(crtc->pipe, i));
9115                         break;
9116                 }
9117         }
9118
9119         scaler_state->scaler_id = id;
9120         if (id >= 0) {
9121                 scaler_state->scaler_users |= (1 << SKL_CRTC_INDEX);
9122         } else {
9123                 scaler_state->scaler_users &= ~(1 << SKL_CRTC_INDEX);
9124         }
9125 }
9126
9127 static void
9128 skylake_get_initial_plane_config(struct intel_crtc *crtc,
9129                                  struct intel_initial_plane_config *plane_config)
9130 {
9131         struct drm_device *dev = crtc->base.dev;
9132         struct drm_i915_private *dev_priv = to_i915(dev);
9133         u32 val, base, offset, stride_mult, tiling;
9134         int pipe = crtc->pipe;
9135         int fourcc, pixel_format;
9136         unsigned int aligned_height;
9137         struct drm_framebuffer *fb;
9138         struct intel_framebuffer *intel_fb;
9139
9140         intel_fb = kzalloc(sizeof(*intel_fb), GFP_KERNEL);
9141         if (!intel_fb) {
9142                 DRM_DEBUG_KMS("failed to alloc fb\n");
9143                 return;
9144         }
9145
9146         fb = &intel_fb->base;
9147
9148         val = I915_READ(PLANE_CTL(pipe, 0));
9149         if (!(val & PLANE_CTL_ENABLE))
9150                 goto error;
9151
9152         pixel_format = val & PLANE_CTL_FORMAT_MASK;
9153         fourcc = skl_format_to_fourcc(pixel_format,
9154                                       val & PLANE_CTL_ORDER_RGBX,
9155                                       val & PLANE_CTL_ALPHA_MASK);
9156         fb->pixel_format = fourcc;
9157         fb->bits_per_pixel = drm_format_plane_cpp(fourcc, 0) * 8;
9158
9159         tiling = val & PLANE_CTL_TILED_MASK;
9160         switch (tiling) {
9161         case PLANE_CTL_TILED_LINEAR:
9162                 fb->modifier[0] = DRM_FORMAT_MOD_NONE;
9163                 break;
9164         case PLANE_CTL_TILED_X:
9165                 plane_config->tiling = I915_TILING_X;
9166                 fb->modifier[0] = I915_FORMAT_MOD_X_TILED;
9167                 break;
9168         case PLANE_CTL_TILED_Y:
9169                 fb->modifier[0] = I915_FORMAT_MOD_Y_TILED;
9170                 break;
9171         case PLANE_CTL_TILED_YF:
9172                 fb->modifier[0] = I915_FORMAT_MOD_Yf_TILED;
9173                 break;
9174         default:
9175                 MISSING_CASE(tiling);
9176                 goto error;
9177         }
9178
9179         base = I915_READ(PLANE_SURF(pipe, 0)) & 0xfffff000;
9180         plane_config->base = base;
9181
9182         offset = I915_READ(PLANE_OFFSET(pipe, 0));
9183
9184         val = I915_READ(PLANE_SIZE(pipe, 0));
9185         fb->height = ((val >> 16) & 0xfff) + 1;
9186         fb->width = ((val >> 0) & 0x1fff) + 1;
9187
9188         val = I915_READ(PLANE_STRIDE(pipe, 0));
9189         stride_mult = intel_fb_stride_alignment(dev_priv, fb->modifier[0],
9190                                                 fb->pixel_format);
9191         fb->pitches[0] = (val & 0x3ff) * stride_mult;
9192
9193         aligned_height = intel_fb_align_height(dev, fb->height,
9194                                                fb->pixel_format,
9195                                                fb->modifier[0]);
9196
9197         plane_config->size = fb->pitches[0] * aligned_height;
9198
9199         DRM_DEBUG_KMS("pipe %c with fb: size=%dx%d@%d, offset=%x, pitch %d, size 0x%x\n",
9200                       pipe_name(pipe), fb->width, fb->height,
9201                       fb->bits_per_pixel, base, fb->pitches[0],
9202                       plane_config->size);
9203
9204         plane_config->fb = intel_fb;
9205         return;
9206
9207 error:
9208         kfree(fb);
9209 }
9210
9211 static void ironlake_get_pfit_config(struct intel_crtc *crtc,
9212                                      struct intel_crtc_state *pipe_config)
9213 {
9214         struct drm_device *dev = crtc->base.dev;
9215         struct drm_i915_private *dev_priv = to_i915(dev);
9216         uint32_t tmp;
9217
9218         tmp = I915_READ(PF_CTL(crtc->pipe));
9219
9220         if (tmp & PF_ENABLE) {
9221                 pipe_config->pch_pfit.enabled = true;
9222                 pipe_config->pch_pfit.pos = I915_READ(PF_WIN_POS(crtc->pipe));
9223                 pipe_config->pch_pfit.size = I915_READ(PF_WIN_SZ(crtc->pipe));
9224
9225                 /* We currently do not free assignements of panel fitters on
9226                  * ivb/hsw (since we don't use the higher upscaling modes which
9227                  * differentiates them) so just WARN about this case for now. */
9228                 if (IS_GEN7(dev)) {
9229                         WARN_ON((tmp & PF_PIPE_SEL_MASK_IVB) !=
9230                                 PF_PIPE_SEL_IVB(crtc->pipe));
9231                 }
9232         }
9233 }
9234
9235 static void
9236 ironlake_get_initial_plane_config(struct intel_crtc *crtc,
9237                                   struct intel_initial_plane_config *plane_config)
9238 {
9239         struct drm_device *dev = crtc->base.dev;
9240         struct drm_i915_private *dev_priv = to_i915(dev);
9241         u32 val, base, offset;
9242         int pipe = crtc->pipe;
9243         int fourcc, pixel_format;
9244         unsigned int aligned_height;
9245         struct drm_framebuffer *fb;
9246         struct intel_framebuffer *intel_fb;
9247
9248         val = I915_READ(DSPCNTR(pipe));
9249         if (!(val & DISPLAY_PLANE_ENABLE))
9250                 return;
9251
9252         intel_fb = kzalloc(sizeof(*intel_fb), GFP_KERNEL);
9253         if (!intel_fb) {
9254                 DRM_DEBUG_KMS("failed to alloc fb\n");
9255                 return;
9256         }
9257
9258         fb = &intel_fb->base;
9259
9260         if (INTEL_INFO(dev)->gen >= 4) {
9261                 if (val & DISPPLANE_TILED) {
9262                         plane_config->tiling = I915_TILING_X;
9263                         fb->modifier[0] = I915_FORMAT_MOD_X_TILED;
9264                 }
9265         }
9266
9267         pixel_format = val & DISPPLANE_PIXFORMAT_MASK;
9268         fourcc = i9xx_format_to_fourcc(pixel_format);
9269         fb->pixel_format = fourcc;
9270         fb->bits_per_pixel = drm_format_plane_cpp(fourcc, 0) * 8;
9271
9272         base = I915_READ(DSPSURF(pipe)) & 0xfffff000;
9273         if (IS_HASWELL(dev) || IS_BROADWELL(dev)) {
9274                 offset = I915_READ(DSPOFFSET(pipe));
9275         } else {
9276                 if (plane_config->tiling)
9277                         offset = I915_READ(DSPTILEOFF(pipe));
9278                 else
9279                         offset = I915_READ(DSPLINOFF(pipe));
9280         }
9281         plane_config->base = base;
9282
9283         val = I915_READ(PIPESRC(pipe));
9284         fb->width = ((val >> 16) & 0xfff) + 1;
9285         fb->height = ((val >> 0) & 0xfff) + 1;
9286
9287         val = I915_READ(DSPSTRIDE(pipe));
9288         fb->pitches[0] = val & 0xffffffc0;
9289
9290         aligned_height = intel_fb_align_height(dev, fb->height,
9291                                                fb->pixel_format,
9292                                                fb->modifier[0]);
9293
9294         plane_config->size = fb->pitches[0] * aligned_height;
9295
9296         DRM_DEBUG_KMS("pipe %c with fb: size=%dx%d@%d, offset=%x, pitch %d, size 0x%x\n",
9297                       pipe_name(pipe), fb->width, fb->height,
9298                       fb->bits_per_pixel, base, fb->pitches[0],
9299                       plane_config->size);
9300
9301         plane_config->fb = intel_fb;
9302 }
9303
9304 static bool ironlake_get_pipe_config(struct intel_crtc *crtc,
9305                                      struct intel_crtc_state *pipe_config)
9306 {
9307         struct drm_device *dev = crtc->base.dev;
9308         struct drm_i915_private *dev_priv = to_i915(dev);
9309         enum intel_display_power_domain power_domain;
9310         uint32_t tmp;
9311         bool ret;
9312
9313         power_domain = POWER_DOMAIN_PIPE(crtc->pipe);
9314         if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
9315                 return false;
9316
9317         pipe_config->cpu_transcoder = (enum transcoder) crtc->pipe;
9318         pipe_config->shared_dpll = NULL;
9319
9320         ret = false;
9321         tmp = I915_READ(PIPECONF(crtc->pipe));
9322         if (!(tmp & PIPECONF_ENABLE))
9323                 goto out;
9324
9325         switch (tmp & PIPECONF_BPC_MASK) {
9326         case PIPECONF_6BPC:
9327                 pipe_config->pipe_bpp = 18;
9328                 break;
9329         case PIPECONF_8BPC:
9330                 pipe_config->pipe_bpp = 24;
9331                 break;
9332         case PIPECONF_10BPC:
9333                 pipe_config->pipe_bpp = 30;
9334                 break;
9335         case PIPECONF_12BPC:
9336                 pipe_config->pipe_bpp = 36;
9337                 break;
9338         default:
9339                 break;
9340         }
9341
9342         if (tmp & PIPECONF_COLOR_RANGE_SELECT)
9343                 pipe_config->limited_color_range = true;
9344
9345         if (I915_READ(PCH_TRANSCONF(crtc->pipe)) & TRANS_ENABLE) {
9346                 struct intel_shared_dpll *pll;
9347                 enum intel_dpll_id pll_id;
9348
9349                 pipe_config->has_pch_encoder = true;
9350
9351                 tmp = I915_READ(FDI_RX_CTL(crtc->pipe));
9352                 pipe_config->fdi_lanes = ((FDI_DP_PORT_WIDTH_MASK & tmp) >>
9353                                           FDI_DP_PORT_WIDTH_SHIFT) + 1;
9354
9355                 ironlake_get_fdi_m_n_config(crtc, pipe_config);
9356
9357                 if (HAS_PCH_IBX(dev_priv)) {
9358                         /*
9359                          * The pipe->pch transcoder and pch transcoder->pll
9360                          * mapping is fixed.
9361                          */
9362                         pll_id = (enum intel_dpll_id) crtc->pipe;
9363                 } else {
9364                         tmp = I915_READ(PCH_DPLL_SEL);
9365                         if (tmp & TRANS_DPLLB_SEL(crtc->pipe))
9366                                 pll_id = DPLL_ID_PCH_PLL_B;
9367                         else
9368                                 pll_id= DPLL_ID_PCH_PLL_A;
9369                 }
9370
9371                 pipe_config->shared_dpll =
9372                         intel_get_shared_dpll_by_id(dev_priv, pll_id);
9373                 pll = pipe_config->shared_dpll;
9374
9375                 WARN_ON(!pll->funcs.get_hw_state(dev_priv, pll,
9376                                                  &pipe_config->dpll_hw_state));
9377
9378                 tmp = pipe_config->dpll_hw_state.dpll;
9379                 pipe_config->pixel_multiplier =
9380                         ((tmp & PLL_REF_SDVO_HDMI_MULTIPLIER_MASK)
9381                          >> PLL_REF_SDVO_HDMI_MULTIPLIER_SHIFT) + 1;
9382
9383                 ironlake_pch_clock_get(crtc, pipe_config);
9384         } else {
9385                 pipe_config->pixel_multiplier = 1;
9386         }
9387
9388         intel_get_pipe_timings(crtc, pipe_config);
9389         intel_get_pipe_src_size(crtc, pipe_config);
9390
9391         ironlake_get_pfit_config(crtc, pipe_config);
9392
9393         ret = true;
9394
9395 out:
9396         intel_display_power_put(dev_priv, power_domain);
9397
9398         return ret;
9399 }
9400
9401 static void assert_can_disable_lcpll(struct drm_i915_private *dev_priv)
9402 {
9403         struct drm_device *dev = &dev_priv->drm;
9404         struct intel_crtc *crtc;
9405
9406         for_each_intel_crtc(dev, crtc)
9407                 I915_STATE_WARN(crtc->active, "CRTC for pipe %c enabled\n",
9408                      pipe_name(crtc->pipe));
9409
9410         I915_STATE_WARN(I915_READ(HSW_PWR_WELL_DRIVER), "Power well on\n");
9411         I915_STATE_WARN(I915_READ(SPLL_CTL) & SPLL_PLL_ENABLE, "SPLL enabled\n");
9412         I915_STATE_WARN(I915_READ(WRPLL_CTL(0)) & WRPLL_PLL_ENABLE, "WRPLL1 enabled\n");
9413         I915_STATE_WARN(I915_READ(WRPLL_CTL(1)) & WRPLL_PLL_ENABLE, "WRPLL2 enabled\n");
9414         I915_STATE_WARN(I915_READ(PCH_PP_STATUS) & PP_ON, "Panel power on\n");
9415         I915_STATE_WARN(I915_READ(BLC_PWM_CPU_CTL2) & BLM_PWM_ENABLE,
9416              "CPU PWM1 enabled\n");
9417         if (IS_HASWELL(dev))
9418                 I915_STATE_WARN(I915_READ(HSW_BLC_PWM2_CTL) & BLM_PWM_ENABLE,
9419                      "CPU PWM2 enabled\n");
9420         I915_STATE_WARN(I915_READ(BLC_PWM_PCH_CTL1) & BLM_PCH_PWM_ENABLE,
9421              "PCH PWM1 enabled\n");
9422         I915_STATE_WARN(I915_READ(UTIL_PIN_CTL) & UTIL_PIN_ENABLE,
9423              "Utility pin enabled\n");
9424         I915_STATE_WARN(I915_READ(PCH_GTC_CTL) & PCH_GTC_ENABLE, "PCH GTC enabled\n");
9425
9426         /*
9427          * In theory we can still leave IRQs enabled, as long as only the HPD
9428          * interrupts remain enabled. We used to check for that, but since it's
9429          * gen-specific and since we only disable LCPLL after we fully disable
9430          * the interrupts, the check below should be enough.
9431          */
9432         I915_STATE_WARN(intel_irqs_enabled(dev_priv), "IRQs enabled\n");
9433 }
9434
9435 static uint32_t hsw_read_dcomp(struct drm_i915_private *dev_priv)
9436 {
9437         struct drm_device *dev = &dev_priv->drm;
9438
9439         if (IS_HASWELL(dev))
9440                 return I915_READ(D_COMP_HSW);
9441         else
9442                 return I915_READ(D_COMP_BDW);
9443 }
9444
9445 static void hsw_write_dcomp(struct drm_i915_private *dev_priv, uint32_t val)
9446 {
9447         struct drm_device *dev = &dev_priv->drm;
9448
9449         if (IS_HASWELL(dev)) {
9450                 mutex_lock(&dev_priv->rps.hw_lock);
9451                 if (sandybridge_pcode_write(dev_priv, GEN6_PCODE_WRITE_D_COMP,
9452                                             val))
9453                         DRM_ERROR("Failed to write to D_COMP\n");
9454                 mutex_unlock(&dev_priv->rps.hw_lock);
9455         } else {
9456                 I915_WRITE(D_COMP_BDW, val);
9457                 POSTING_READ(D_COMP_BDW);
9458         }
9459 }
9460
9461 /*
9462  * This function implements pieces of two sequences from BSpec:
9463  * - Sequence for display software to disable LCPLL
9464  * - Sequence for display software to allow package C8+
9465  * The steps implemented here are just the steps that actually touch the LCPLL
9466  * register. Callers should take care of disabling all the display engine
9467  * functions, doing the mode unset, fixing interrupts, etc.
9468  */
9469 static void hsw_disable_lcpll(struct drm_i915_private *dev_priv,
9470                               bool switch_to_fclk, bool allow_power_down)
9471 {
9472         uint32_t val;
9473
9474         assert_can_disable_lcpll(dev_priv);
9475
9476         val = I915_READ(LCPLL_CTL);
9477
9478         if (switch_to_fclk) {
9479                 val |= LCPLL_CD_SOURCE_FCLK;
9480                 I915_WRITE(LCPLL_CTL, val);
9481
9482                 if (wait_for_us(I915_READ(LCPLL_CTL) &
9483                                 LCPLL_CD_SOURCE_FCLK_DONE, 1))
9484                         DRM_ERROR("Switching to FCLK failed\n");
9485
9486                 val = I915_READ(LCPLL_CTL);
9487         }
9488
9489         val |= LCPLL_PLL_DISABLE;
9490         I915_WRITE(LCPLL_CTL, val);
9491         POSTING_READ(LCPLL_CTL);
9492
9493         if (intel_wait_for_register(dev_priv, LCPLL_CTL, LCPLL_PLL_LOCK, 0, 1))
9494                 DRM_ERROR("LCPLL still locked\n");
9495
9496         val = hsw_read_dcomp(dev_priv);
9497         val |= D_COMP_COMP_DISABLE;
9498         hsw_write_dcomp(dev_priv, val);
9499         ndelay(100);
9500
9501         if (wait_for((hsw_read_dcomp(dev_priv) & D_COMP_RCOMP_IN_PROGRESS) == 0,
9502                      1))
9503                 DRM_ERROR("D_COMP RCOMP still in progress\n");
9504
9505         if (allow_power_down) {
9506                 val = I915_READ(LCPLL_CTL);
9507                 val |= LCPLL_POWER_DOWN_ALLOW;
9508                 I915_WRITE(LCPLL_CTL, val);
9509                 POSTING_READ(LCPLL_CTL);
9510         }
9511 }
9512
9513 /*
9514  * Fully restores LCPLL, disallowing power down and switching back to LCPLL
9515  * source.
9516  */
9517 static void hsw_restore_lcpll(struct drm_i915_private *dev_priv)
9518 {
9519         uint32_t val;
9520
9521         val = I915_READ(LCPLL_CTL);
9522
9523         if ((val & (LCPLL_PLL_LOCK | LCPLL_PLL_DISABLE | LCPLL_CD_SOURCE_FCLK |
9524                     LCPLL_POWER_DOWN_ALLOW)) == LCPLL_PLL_LOCK)
9525                 return;
9526
9527         /*
9528          * Make sure we're not on PC8 state before disabling PC8, otherwise
9529          * we'll hang the machine. To prevent PC8 state, just enable force_wake.
9530          */
9531         intel_uncore_forcewake_get(dev_priv, FORCEWAKE_ALL);
9532
9533         if (val & LCPLL_POWER_DOWN_ALLOW) {
9534                 val &= ~LCPLL_POWER_DOWN_ALLOW;
9535                 I915_WRITE(LCPLL_CTL, val);
9536                 POSTING_READ(LCPLL_CTL);
9537         }
9538
9539         val = hsw_read_dcomp(dev_priv);
9540         val |= D_COMP_COMP_FORCE;
9541         val &= ~D_COMP_COMP_DISABLE;
9542         hsw_write_dcomp(dev_priv, val);
9543
9544         val = I915_READ(LCPLL_CTL);
9545         val &= ~LCPLL_PLL_DISABLE;
9546         I915_WRITE(LCPLL_CTL, val);
9547
9548         if (intel_wait_for_register(dev_priv,
9549                                     LCPLL_CTL, LCPLL_PLL_LOCK, LCPLL_PLL_LOCK,
9550                                     5))
9551                 DRM_ERROR("LCPLL not locked yet\n");
9552
9553         if (val & LCPLL_CD_SOURCE_FCLK) {
9554                 val = I915_READ(LCPLL_CTL);
9555                 val &= ~LCPLL_CD_SOURCE_FCLK;
9556                 I915_WRITE(LCPLL_CTL, val);
9557
9558                 if (wait_for_us((I915_READ(LCPLL_CTL) &
9559                                  LCPLL_CD_SOURCE_FCLK_DONE) == 0, 1))
9560                         DRM_ERROR("Switching back to LCPLL failed\n");
9561         }
9562
9563         intel_uncore_forcewake_put(dev_priv, FORCEWAKE_ALL);
9564         intel_update_cdclk(&dev_priv->drm);
9565 }
9566
9567 /*
9568  * Package states C8 and deeper are really deep PC states that can only be
9569  * reached when all the devices on the system allow it, so even if the graphics
9570  * device allows PC8+, it doesn't mean the system will actually get to these
9571  * states. Our driver only allows PC8+ when going into runtime PM.
9572  *
9573  * The requirements for PC8+ are that all the outputs are disabled, the power
9574  * well is disabled and most interrupts are disabled, and these are also
9575  * requirements for runtime PM. When these conditions are met, we manually do
9576  * the other conditions: disable the interrupts, clocks and switch LCPLL refclk
9577  * to Fclk. If we're in PC8+ and we get an non-hotplug interrupt, we can hard
9578  * hang the machine.
9579  *
9580  * When we really reach PC8 or deeper states (not just when we allow it) we lose
9581  * the state of some registers, so when we come back from PC8+ we need to
9582  * restore this state. We don't get into PC8+ if we're not in RC6, so we don't
9583  * need to take care of the registers kept by RC6. Notice that this happens even
9584  * if we don't put the device in PCI D3 state (which is what currently happens
9585  * because of the runtime PM support).
9586  *
9587  * For more, read "Display Sequences for Package C8" on the hardware
9588  * documentation.
9589  */
9590 void hsw_enable_pc8(struct drm_i915_private *dev_priv)
9591 {
9592         struct drm_device *dev = &dev_priv->drm;
9593         uint32_t val;
9594
9595         DRM_DEBUG_KMS("Enabling package C8+\n");
9596
9597         if (HAS_PCH_LPT_LP(dev)) {
9598                 val = I915_READ(SOUTH_DSPCLK_GATE_D);
9599                 val &= ~PCH_LP_PARTITION_LEVEL_DISABLE;
9600                 I915_WRITE(SOUTH_DSPCLK_GATE_D, val);
9601         }
9602
9603         lpt_disable_clkout_dp(dev);
9604         hsw_disable_lcpll(dev_priv, true, true);
9605 }
9606
9607 void hsw_disable_pc8(struct drm_i915_private *dev_priv)
9608 {
9609         struct drm_device *dev = &dev_priv->drm;
9610         uint32_t val;
9611
9612         DRM_DEBUG_KMS("Disabling package C8+\n");
9613
9614         hsw_restore_lcpll(dev_priv);
9615         lpt_init_pch_refclk(dev);
9616
9617         if (HAS_PCH_LPT_LP(dev)) {
9618                 val = I915_READ(SOUTH_DSPCLK_GATE_D);
9619                 val |= PCH_LP_PARTITION_LEVEL_DISABLE;
9620                 I915_WRITE(SOUTH_DSPCLK_GATE_D, val);
9621         }
9622 }
9623
9624 static void bxt_modeset_commit_cdclk(struct drm_atomic_state *old_state)
9625 {
9626         struct drm_device *dev = old_state->dev;
9627         struct intel_atomic_state *old_intel_state =
9628                 to_intel_atomic_state(old_state);
9629         unsigned int req_cdclk = old_intel_state->dev_cdclk;
9630
9631         bxt_set_cdclk(to_i915(dev), req_cdclk);
9632 }
9633
9634 /* compute the max rate for new configuration */
9635 static int ilk_max_pixel_rate(struct drm_atomic_state *state)
9636 {
9637         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
9638         struct drm_i915_private *dev_priv = to_i915(state->dev);
9639         struct drm_crtc *crtc;
9640         struct drm_crtc_state *cstate;
9641         struct intel_crtc_state *crtc_state;
9642         unsigned max_pixel_rate = 0, i;
9643         enum pipe pipe;
9644
9645         memcpy(intel_state->min_pixclk, dev_priv->min_pixclk,
9646                sizeof(intel_state->min_pixclk));
9647
9648         for_each_crtc_in_state(state, crtc, cstate, i) {
9649                 int pixel_rate;
9650
9651                 crtc_state = to_intel_crtc_state(cstate);
9652                 if (!crtc_state->base.enable) {
9653                         intel_state->min_pixclk[i] = 0;
9654                         continue;
9655                 }
9656
9657                 pixel_rate = ilk_pipe_pixel_rate(crtc_state);
9658
9659                 /* pixel rate mustn't exceed 95% of cdclk with IPS on BDW */
9660                 if (IS_BROADWELL(dev_priv) && crtc_state->ips_enabled)
9661                         pixel_rate = DIV_ROUND_UP(pixel_rate * 100, 95);
9662
9663                 intel_state->min_pixclk[i] = pixel_rate;
9664         }
9665
9666         for_each_pipe(dev_priv, pipe)
9667                 max_pixel_rate = max(intel_state->min_pixclk[pipe], max_pixel_rate);
9668
9669         return max_pixel_rate;
9670 }
9671
9672 static void broadwell_set_cdclk(struct drm_device *dev, int cdclk)
9673 {
9674         struct drm_i915_private *dev_priv = to_i915(dev);
9675         uint32_t val, data;
9676         int ret;
9677
9678         if (WARN((I915_READ(LCPLL_CTL) &
9679                   (LCPLL_PLL_DISABLE | LCPLL_PLL_LOCK |
9680                    LCPLL_CD_CLOCK_DISABLE | LCPLL_ROOT_CD_CLOCK_DISABLE |
9681                    LCPLL_CD2X_CLOCK_DISABLE | LCPLL_POWER_DOWN_ALLOW |
9682                    LCPLL_CD_SOURCE_FCLK)) != LCPLL_PLL_LOCK,
9683                  "trying to change cdclk frequency with cdclk not enabled\n"))
9684                 return;
9685
9686         mutex_lock(&dev_priv->rps.hw_lock);
9687         ret = sandybridge_pcode_write(dev_priv,
9688                                       BDW_PCODE_DISPLAY_FREQ_CHANGE_REQ, 0x0);
9689         mutex_unlock(&dev_priv->rps.hw_lock);
9690         if (ret) {
9691                 DRM_ERROR("failed to inform pcode about cdclk change\n");
9692                 return;
9693         }
9694
9695         val = I915_READ(LCPLL_CTL);
9696         val |= LCPLL_CD_SOURCE_FCLK;
9697         I915_WRITE(LCPLL_CTL, val);
9698
9699         if (wait_for_us(I915_READ(LCPLL_CTL) &
9700                         LCPLL_CD_SOURCE_FCLK_DONE, 1))
9701                 DRM_ERROR("Switching to FCLK failed\n");
9702
9703         val = I915_READ(LCPLL_CTL);
9704         val &= ~LCPLL_CLK_FREQ_MASK;
9705
9706         switch (cdclk) {
9707         case 450000:
9708                 val |= LCPLL_CLK_FREQ_450;
9709                 data = 0;
9710                 break;
9711         case 540000:
9712                 val |= LCPLL_CLK_FREQ_54O_BDW;
9713                 data = 1;
9714                 break;
9715         case 337500:
9716                 val |= LCPLL_CLK_FREQ_337_5_BDW;
9717                 data = 2;
9718                 break;
9719         case 675000:
9720                 val |= LCPLL_CLK_FREQ_675_BDW;
9721                 data = 3;
9722                 break;
9723         default:
9724                 WARN(1, "invalid cdclk frequency\n");
9725                 return;
9726         }
9727
9728         I915_WRITE(LCPLL_CTL, val);
9729
9730         val = I915_READ(LCPLL_CTL);
9731         val &= ~LCPLL_CD_SOURCE_FCLK;
9732         I915_WRITE(LCPLL_CTL, val);
9733
9734         if (wait_for_us((I915_READ(LCPLL_CTL) &
9735                         LCPLL_CD_SOURCE_FCLK_DONE) == 0, 1))
9736                 DRM_ERROR("Switching back to LCPLL failed\n");
9737
9738         mutex_lock(&dev_priv->rps.hw_lock);
9739         sandybridge_pcode_write(dev_priv, HSW_PCODE_DE_WRITE_FREQ_REQ, data);
9740         mutex_unlock(&dev_priv->rps.hw_lock);
9741
9742         I915_WRITE(CDCLK_FREQ, DIV_ROUND_CLOSEST(cdclk, 1000) - 1);
9743
9744         intel_update_cdclk(dev);
9745
9746         WARN(cdclk != dev_priv->cdclk_freq,
9747              "cdclk requested %d kHz but got %d kHz\n",
9748              cdclk, dev_priv->cdclk_freq);
9749 }
9750
9751 static int broadwell_calc_cdclk(int max_pixclk)
9752 {
9753         if (max_pixclk > 540000)
9754                 return 675000;
9755         else if (max_pixclk > 450000)
9756                 return 540000;
9757         else if (max_pixclk > 337500)
9758                 return 450000;
9759         else
9760                 return 337500;
9761 }
9762
9763 static int broadwell_modeset_calc_cdclk(struct drm_atomic_state *state)
9764 {
9765         struct drm_i915_private *dev_priv = to_i915(state->dev);
9766         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
9767         int max_pixclk = ilk_max_pixel_rate(state);
9768         int cdclk;
9769
9770         /*
9771          * FIXME should also account for plane ratio
9772          * once 64bpp pixel formats are supported.
9773          */
9774         cdclk = broadwell_calc_cdclk(max_pixclk);
9775
9776         if (cdclk > dev_priv->max_cdclk_freq) {
9777                 DRM_DEBUG_KMS("requested cdclk (%d kHz) exceeds max (%d kHz)\n",
9778                               cdclk, dev_priv->max_cdclk_freq);
9779                 return -EINVAL;
9780         }
9781
9782         intel_state->cdclk = intel_state->dev_cdclk = cdclk;
9783         if (!intel_state->active_crtcs)
9784                 intel_state->dev_cdclk = broadwell_calc_cdclk(0);
9785
9786         return 0;
9787 }
9788
9789 static void broadwell_modeset_commit_cdclk(struct drm_atomic_state *old_state)
9790 {
9791         struct drm_device *dev = old_state->dev;
9792         struct intel_atomic_state *old_intel_state =
9793                 to_intel_atomic_state(old_state);
9794         unsigned req_cdclk = old_intel_state->dev_cdclk;
9795
9796         broadwell_set_cdclk(dev, req_cdclk);
9797 }
9798
9799 static int skl_modeset_calc_cdclk(struct drm_atomic_state *state)
9800 {
9801         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
9802         struct drm_i915_private *dev_priv = to_i915(state->dev);
9803         const int max_pixclk = ilk_max_pixel_rate(state);
9804         int vco = intel_state->cdclk_pll_vco;
9805         int cdclk;
9806
9807         /*
9808          * FIXME should also account for plane ratio
9809          * once 64bpp pixel formats are supported.
9810          */
9811         cdclk = skl_calc_cdclk(max_pixclk, vco);
9812
9813         /*
9814          * FIXME move the cdclk caclulation to
9815          * compute_config() so we can fail gracegully.
9816          */
9817         if (cdclk > dev_priv->max_cdclk_freq) {
9818                 DRM_ERROR("requested cdclk (%d kHz) exceeds max (%d kHz)\n",
9819                           cdclk, dev_priv->max_cdclk_freq);
9820                 cdclk = dev_priv->max_cdclk_freq;
9821         }
9822
9823         intel_state->cdclk = intel_state->dev_cdclk = cdclk;
9824         if (!intel_state->active_crtcs)
9825                 intel_state->dev_cdclk = skl_calc_cdclk(0, vco);
9826
9827         return 0;
9828 }
9829
9830 static void skl_modeset_commit_cdclk(struct drm_atomic_state *old_state)
9831 {
9832         struct drm_i915_private *dev_priv = to_i915(old_state->dev);
9833         struct intel_atomic_state *intel_state = to_intel_atomic_state(old_state);
9834         unsigned int req_cdclk = intel_state->dev_cdclk;
9835         unsigned int req_vco = intel_state->cdclk_pll_vco;
9836
9837         skl_set_cdclk(dev_priv, req_cdclk, req_vco);
9838 }
9839
9840 static int haswell_crtc_compute_clock(struct intel_crtc *crtc,
9841                                       struct intel_crtc_state *crtc_state)
9842 {
9843         if (!intel_crtc_has_type(crtc_state, INTEL_OUTPUT_DSI)) {
9844                 if (!intel_ddi_pll_select(crtc, crtc_state))
9845                         return -EINVAL;
9846         }
9847
9848         crtc->lowfreq_avail = false;
9849
9850         return 0;
9851 }
9852
9853 static void bxt_get_ddi_pll(struct drm_i915_private *dev_priv,
9854                                 enum port port,
9855                                 struct intel_crtc_state *pipe_config)
9856 {
9857         enum intel_dpll_id id;
9858
9859         switch (port) {
9860         case PORT_A:
9861                 pipe_config->ddi_pll_sel = SKL_DPLL0;
9862                 id = DPLL_ID_SKL_DPLL0;
9863                 break;
9864         case PORT_B:
9865                 pipe_config->ddi_pll_sel = SKL_DPLL1;
9866                 id = DPLL_ID_SKL_DPLL1;
9867                 break;
9868         case PORT_C:
9869                 pipe_config->ddi_pll_sel = SKL_DPLL2;
9870                 id = DPLL_ID_SKL_DPLL2;
9871                 break;
9872         default:
9873                 DRM_ERROR("Incorrect port type\n");
9874                 return;
9875         }
9876
9877         pipe_config->shared_dpll = intel_get_shared_dpll_by_id(dev_priv, id);
9878 }
9879
9880 static void skylake_get_ddi_pll(struct drm_i915_private *dev_priv,
9881                                 enum port port,
9882                                 struct intel_crtc_state *pipe_config)
9883 {
9884         enum intel_dpll_id id;
9885         u32 temp;
9886
9887         temp = I915_READ(DPLL_CTRL2) & DPLL_CTRL2_DDI_CLK_SEL_MASK(port);
9888         pipe_config->ddi_pll_sel = temp >> (port * 3 + 1);
9889
9890         switch (pipe_config->ddi_pll_sel) {
9891         case SKL_DPLL0:
9892                 id = DPLL_ID_SKL_DPLL0;
9893                 break;
9894         case SKL_DPLL1:
9895                 id = DPLL_ID_SKL_DPLL1;
9896                 break;
9897         case SKL_DPLL2:
9898                 id = DPLL_ID_SKL_DPLL2;
9899                 break;
9900         case SKL_DPLL3:
9901                 id = DPLL_ID_SKL_DPLL3;
9902                 break;
9903         default:
9904                 MISSING_CASE(pipe_config->ddi_pll_sel);
9905                 return;
9906         }
9907
9908         pipe_config->shared_dpll = intel_get_shared_dpll_by_id(dev_priv, id);
9909 }
9910
9911 static void haswell_get_ddi_pll(struct drm_i915_private *dev_priv,
9912                                 enum port port,
9913                                 struct intel_crtc_state *pipe_config)
9914 {
9915         enum intel_dpll_id id;
9916
9917         pipe_config->ddi_pll_sel = I915_READ(PORT_CLK_SEL(port));
9918
9919         switch (pipe_config->ddi_pll_sel) {
9920         case PORT_CLK_SEL_WRPLL1:
9921                 id = DPLL_ID_WRPLL1;
9922                 break;
9923         case PORT_CLK_SEL_WRPLL2:
9924                 id = DPLL_ID_WRPLL2;
9925                 break;
9926         case PORT_CLK_SEL_SPLL:
9927                 id = DPLL_ID_SPLL;
9928                 break;
9929         case PORT_CLK_SEL_LCPLL_810:
9930                 id = DPLL_ID_LCPLL_810;
9931                 break;
9932         case PORT_CLK_SEL_LCPLL_1350:
9933                 id = DPLL_ID_LCPLL_1350;
9934                 break;
9935         case PORT_CLK_SEL_LCPLL_2700:
9936                 id = DPLL_ID_LCPLL_2700;
9937                 break;
9938         default:
9939                 MISSING_CASE(pipe_config->ddi_pll_sel);
9940                 /* fall through */
9941         case PORT_CLK_SEL_NONE:
9942                 return;
9943         }
9944
9945         pipe_config->shared_dpll = intel_get_shared_dpll_by_id(dev_priv, id);
9946 }
9947
9948 static bool hsw_get_transcoder_state(struct intel_crtc *crtc,
9949                                      struct intel_crtc_state *pipe_config,
9950                                      unsigned long *power_domain_mask)
9951 {
9952         struct drm_device *dev = crtc->base.dev;
9953         struct drm_i915_private *dev_priv = to_i915(dev);
9954         enum intel_display_power_domain power_domain;
9955         u32 tmp;
9956
9957         /*
9958          * The pipe->transcoder mapping is fixed with the exception of the eDP
9959          * transcoder handled below.
9960          */
9961         pipe_config->cpu_transcoder = (enum transcoder) crtc->pipe;
9962
9963         /*
9964          * XXX: Do intel_display_power_get_if_enabled before reading this (for
9965          * consistency and less surprising code; it's in always on power).
9966          */
9967         tmp = I915_READ(TRANS_DDI_FUNC_CTL(TRANSCODER_EDP));
9968         if (tmp & TRANS_DDI_FUNC_ENABLE) {
9969                 enum pipe trans_edp_pipe;
9970                 switch (tmp & TRANS_DDI_EDP_INPUT_MASK) {
9971                 default:
9972                         WARN(1, "unknown pipe linked to edp transcoder\n");
9973                 case TRANS_DDI_EDP_INPUT_A_ONOFF:
9974                 case TRANS_DDI_EDP_INPUT_A_ON:
9975                         trans_edp_pipe = PIPE_A;
9976                         break;
9977                 case TRANS_DDI_EDP_INPUT_B_ONOFF:
9978                         trans_edp_pipe = PIPE_B;
9979                         break;
9980                 case TRANS_DDI_EDP_INPUT_C_ONOFF:
9981                         trans_edp_pipe = PIPE_C;
9982                         break;
9983                 }
9984
9985                 if (trans_edp_pipe == crtc->pipe)
9986                         pipe_config->cpu_transcoder = TRANSCODER_EDP;
9987         }
9988
9989         power_domain = POWER_DOMAIN_TRANSCODER(pipe_config->cpu_transcoder);
9990         if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
9991                 return false;
9992         *power_domain_mask |= BIT(power_domain);
9993
9994         tmp = I915_READ(PIPECONF(pipe_config->cpu_transcoder));
9995
9996         return tmp & PIPECONF_ENABLE;
9997 }
9998
9999 static bool bxt_get_dsi_transcoder_state(struct intel_crtc *crtc,
10000                                          struct intel_crtc_state *pipe_config,
10001                                          unsigned long *power_domain_mask)
10002 {
10003         struct drm_device *dev = crtc->base.dev;
10004         struct drm_i915_private *dev_priv = to_i915(dev);
10005         enum intel_display_power_domain power_domain;
10006         enum port port;
10007         enum transcoder cpu_transcoder;
10008         u32 tmp;
10009
10010         for_each_port_masked(port, BIT(PORT_A) | BIT(PORT_C)) {
10011                 if (port == PORT_A)
10012                         cpu_transcoder = TRANSCODER_DSI_A;
10013                 else
10014                         cpu_transcoder = TRANSCODER_DSI_C;
10015
10016                 power_domain = POWER_DOMAIN_TRANSCODER(cpu_transcoder);
10017                 if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
10018                         continue;
10019                 *power_domain_mask |= BIT(power_domain);
10020
10021                 /*
10022                  * The PLL needs to be enabled with a valid divider
10023                  * configuration, otherwise accessing DSI registers will hang
10024                  * the machine. See BSpec North Display Engine
10025                  * registers/MIPI[BXT]. We can break out here early, since we
10026                  * need the same DSI PLL to be enabled for both DSI ports.
10027                  */
10028                 if (!intel_dsi_pll_is_enabled(dev_priv))
10029                         break;
10030
10031                 /* XXX: this works for video mode only */
10032                 tmp = I915_READ(BXT_MIPI_PORT_CTRL(port));
10033                 if (!(tmp & DPI_ENABLE))
10034                         continue;
10035
10036                 tmp = I915_READ(MIPI_CTRL(port));
10037                 if ((tmp & BXT_PIPE_SELECT_MASK) != BXT_PIPE_SELECT(crtc->pipe))
10038                         continue;
10039
10040                 pipe_config->cpu_transcoder = cpu_transcoder;
10041                 break;
10042         }
10043
10044         return transcoder_is_dsi(pipe_config->cpu_transcoder);
10045 }
10046
10047 static void haswell_get_ddi_port_state(struct intel_crtc *crtc,
10048                                        struct intel_crtc_state *pipe_config)
10049 {
10050         struct drm_device *dev = crtc->base.dev;
10051         struct drm_i915_private *dev_priv = to_i915(dev);
10052         struct intel_shared_dpll *pll;
10053         enum port port;
10054         uint32_t tmp;
10055
10056         tmp = I915_READ(TRANS_DDI_FUNC_CTL(pipe_config->cpu_transcoder));
10057
10058         port = (tmp & TRANS_DDI_PORT_MASK) >> TRANS_DDI_PORT_SHIFT;
10059
10060         if (IS_SKYLAKE(dev) || IS_KABYLAKE(dev))
10061                 skylake_get_ddi_pll(dev_priv, port, pipe_config);
10062         else if (IS_BROXTON(dev))
10063                 bxt_get_ddi_pll(dev_priv, port, pipe_config);
10064         else
10065                 haswell_get_ddi_pll(dev_priv, port, pipe_config);
10066
10067         pll = pipe_config->shared_dpll;
10068         if (pll) {
10069                 WARN_ON(!pll->funcs.get_hw_state(dev_priv, pll,
10070                                                  &pipe_config->dpll_hw_state));
10071         }
10072
10073         /*
10074          * Haswell has only FDI/PCH transcoder A. It is which is connected to
10075          * DDI E. So just check whether this pipe is wired to DDI E and whether
10076          * the PCH transcoder is on.
10077          */
10078         if (INTEL_INFO(dev)->gen < 9 &&
10079             (port == PORT_E) && I915_READ(LPT_TRANSCONF) & TRANS_ENABLE) {
10080                 pipe_config->has_pch_encoder = true;
10081
10082                 tmp = I915_READ(FDI_RX_CTL(PIPE_A));
10083                 pipe_config->fdi_lanes = ((FDI_DP_PORT_WIDTH_MASK & tmp) >>
10084                                           FDI_DP_PORT_WIDTH_SHIFT) + 1;
10085
10086                 ironlake_get_fdi_m_n_config(crtc, pipe_config);
10087         }
10088 }
10089
10090 static bool haswell_get_pipe_config(struct intel_crtc *crtc,
10091                                     struct intel_crtc_state *pipe_config)
10092 {
10093         struct drm_device *dev = crtc->base.dev;
10094         struct drm_i915_private *dev_priv = to_i915(dev);
10095         enum intel_display_power_domain power_domain;
10096         unsigned long power_domain_mask;
10097         bool active;
10098
10099         power_domain = POWER_DOMAIN_PIPE(crtc->pipe);
10100         if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
10101                 return false;
10102         power_domain_mask = BIT(power_domain);
10103
10104         pipe_config->shared_dpll = NULL;
10105
10106         active = hsw_get_transcoder_state(crtc, pipe_config, &power_domain_mask);
10107
10108         if (IS_BROXTON(dev_priv) &&
10109             bxt_get_dsi_transcoder_state(crtc, pipe_config, &power_domain_mask)) {
10110                 WARN_ON(active);
10111                 active = true;
10112         }
10113
10114         if (!active)
10115                 goto out;
10116
10117         if (!transcoder_is_dsi(pipe_config->cpu_transcoder)) {
10118                 haswell_get_ddi_port_state(crtc, pipe_config);
10119                 intel_get_pipe_timings(crtc, pipe_config);
10120         }
10121
10122         intel_get_pipe_src_size(crtc, pipe_config);
10123
10124         pipe_config->gamma_mode =
10125                 I915_READ(GAMMA_MODE(crtc->pipe)) & GAMMA_MODE_MODE_MASK;
10126
10127         if (INTEL_INFO(dev)->gen >= 9) {
10128                 skl_init_scalers(dev, crtc, pipe_config);
10129         }
10130
10131         if (INTEL_INFO(dev)->gen >= 9) {
10132                 pipe_config->scaler_state.scaler_id = -1;
10133                 pipe_config->scaler_state.scaler_users &= ~(1 << SKL_CRTC_INDEX);
10134         }
10135
10136         power_domain = POWER_DOMAIN_PIPE_PANEL_FITTER(crtc->pipe);
10137         if (intel_display_power_get_if_enabled(dev_priv, power_domain)) {
10138                 power_domain_mask |= BIT(power_domain);
10139                 if (INTEL_INFO(dev)->gen >= 9)
10140                         skylake_get_pfit_config(crtc, pipe_config);
10141                 else
10142                         ironlake_get_pfit_config(crtc, pipe_config);
10143         }
10144
10145         if (IS_HASWELL(dev))
10146                 pipe_config->ips_enabled = hsw_crtc_supports_ips(crtc) &&
10147                         (I915_READ(IPS_CTL) & IPS_ENABLE);
10148
10149         if (pipe_config->cpu_transcoder != TRANSCODER_EDP &&
10150             !transcoder_is_dsi(pipe_config->cpu_transcoder)) {
10151                 pipe_config->pixel_multiplier =
10152                         I915_READ(PIPE_MULT(pipe_config->cpu_transcoder)) + 1;
10153         } else {
10154                 pipe_config->pixel_multiplier = 1;
10155         }
10156
10157 out:
10158         for_each_power_domain(power_domain, power_domain_mask)
10159                 intel_display_power_put(dev_priv, power_domain);
10160
10161         return active;
10162 }
10163
10164 static void i845_update_cursor(struct drm_crtc *crtc, u32 base,
10165                                const struct intel_plane_state *plane_state)
10166 {
10167         struct drm_device *dev = crtc->dev;
10168         struct drm_i915_private *dev_priv = to_i915(dev);
10169         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10170         uint32_t cntl = 0, size = 0;
10171
10172         if (plane_state && plane_state->base.visible) {
10173                 unsigned int width = plane_state->base.crtc_w;
10174                 unsigned int height = plane_state->base.crtc_h;
10175                 unsigned int stride = roundup_pow_of_two(width) * 4;
10176
10177                 switch (stride) {
10178                 default:
10179                         WARN_ONCE(1, "Invalid cursor width/stride, width=%u, stride=%u\n",
10180                                   width, stride);
10181                         stride = 256;
10182                         /* fallthrough */
10183                 case 256:
10184                 case 512:
10185                 case 1024:
10186                 case 2048:
10187                         break;
10188                 }
10189
10190                 cntl |= CURSOR_ENABLE |
10191                         CURSOR_GAMMA_ENABLE |
10192                         CURSOR_FORMAT_ARGB |
10193                         CURSOR_STRIDE(stride);
10194
10195                 size = (height << 12) | width;
10196         }
10197
10198         if (intel_crtc->cursor_cntl != 0 &&
10199             (intel_crtc->cursor_base != base ||
10200              intel_crtc->cursor_size != size ||
10201              intel_crtc->cursor_cntl != cntl)) {
10202                 /* On these chipsets we can only modify the base/size/stride
10203                  * whilst the cursor is disabled.
10204                  */
10205                 I915_WRITE(CURCNTR(PIPE_A), 0);
10206                 POSTING_READ(CURCNTR(PIPE_A));
10207                 intel_crtc->cursor_cntl = 0;
10208         }
10209
10210         if (intel_crtc->cursor_base != base) {
10211                 I915_WRITE(CURBASE(PIPE_A), base);
10212                 intel_crtc->cursor_base = base;
10213         }
10214
10215         if (intel_crtc->cursor_size != size) {
10216                 I915_WRITE(CURSIZE, size);
10217                 intel_crtc->cursor_size = size;
10218         }
10219
10220         if (intel_crtc->cursor_cntl != cntl) {
10221                 I915_WRITE(CURCNTR(PIPE_A), cntl);
10222                 POSTING_READ(CURCNTR(PIPE_A));
10223                 intel_crtc->cursor_cntl = cntl;
10224         }
10225 }
10226
10227 static void i9xx_update_cursor(struct drm_crtc *crtc, u32 base,
10228                                const struct intel_plane_state *plane_state)
10229 {
10230         struct drm_device *dev = crtc->dev;
10231         struct drm_i915_private *dev_priv = to_i915(dev);
10232         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10233         int pipe = intel_crtc->pipe;
10234         uint32_t cntl = 0;
10235
10236         if (plane_state && plane_state->base.visible) {
10237                 cntl = MCURSOR_GAMMA_ENABLE;
10238                 switch (plane_state->base.crtc_w) {
10239                         case 64:
10240                                 cntl |= CURSOR_MODE_64_ARGB_AX;
10241                                 break;
10242                         case 128:
10243                                 cntl |= CURSOR_MODE_128_ARGB_AX;
10244                                 break;
10245                         case 256:
10246                                 cntl |= CURSOR_MODE_256_ARGB_AX;
10247                                 break;
10248                         default:
10249                                 MISSING_CASE(plane_state->base.crtc_w);
10250                                 return;
10251                 }
10252                 cntl |= pipe << 28; /* Connect to correct pipe */
10253
10254                 if (HAS_DDI(dev))
10255                         cntl |= CURSOR_PIPE_CSC_ENABLE;
10256
10257                 if (plane_state->base.rotation == DRM_ROTATE_180)
10258                         cntl |= CURSOR_ROTATE_180;
10259         }
10260
10261         if (intel_crtc->cursor_cntl != cntl) {
10262                 I915_WRITE(CURCNTR(pipe), cntl);
10263                 POSTING_READ(CURCNTR(pipe));
10264                 intel_crtc->cursor_cntl = cntl;
10265         }
10266
10267         /* and commit changes on next vblank */
10268         I915_WRITE(CURBASE(pipe), base);
10269         POSTING_READ(CURBASE(pipe));
10270
10271         intel_crtc->cursor_base = base;
10272 }
10273
10274 /* If no-part of the cursor is visible on the framebuffer, then the GPU may hang... */
10275 static void intel_crtc_update_cursor(struct drm_crtc *crtc,
10276                                      const struct intel_plane_state *plane_state)
10277 {
10278         struct drm_device *dev = crtc->dev;
10279         struct drm_i915_private *dev_priv = to_i915(dev);
10280         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10281         int pipe = intel_crtc->pipe;
10282         u32 base = intel_crtc->cursor_addr;
10283         u32 pos = 0;
10284
10285         if (plane_state) {
10286                 int x = plane_state->base.crtc_x;
10287                 int y = plane_state->base.crtc_y;
10288
10289                 if (x < 0) {
10290                         pos |= CURSOR_POS_SIGN << CURSOR_X_SHIFT;
10291                         x = -x;
10292                 }
10293                 pos |= x << CURSOR_X_SHIFT;
10294
10295                 if (y < 0) {
10296                         pos |= CURSOR_POS_SIGN << CURSOR_Y_SHIFT;
10297                         y = -y;
10298                 }
10299                 pos |= y << CURSOR_Y_SHIFT;
10300
10301                 /* ILK+ do this automagically */
10302                 if (HAS_GMCH_DISPLAY(dev) &&
10303                     plane_state->base.rotation == DRM_ROTATE_180) {
10304                         base += (plane_state->base.crtc_h *
10305                                  plane_state->base.crtc_w - 1) * 4;
10306                 }
10307         }
10308
10309         I915_WRITE(CURPOS(pipe), pos);
10310
10311         if (IS_845G(dev) || IS_I865G(dev))
10312                 i845_update_cursor(crtc, base, plane_state);
10313         else
10314                 i9xx_update_cursor(crtc, base, plane_state);
10315 }
10316
10317 static bool cursor_size_ok(struct drm_device *dev,
10318                            uint32_t width, uint32_t height)
10319 {
10320         if (width == 0 || height == 0)
10321                 return false;
10322
10323         /*
10324          * 845g/865g are special in that they are only limited by
10325          * the width of their cursors, the height is arbitrary up to
10326          * the precision of the register. Everything else requires
10327          * square cursors, limited to a few power-of-two sizes.
10328          */
10329         if (IS_845G(dev) || IS_I865G(dev)) {
10330                 if ((width & 63) != 0)
10331                         return false;
10332
10333                 if (width > (IS_845G(dev) ? 64 : 512))
10334                         return false;
10335
10336                 if (height > 1023)
10337                         return false;
10338         } else {
10339                 switch (width | height) {
10340                 case 256:
10341                 case 128:
10342                         if (IS_GEN2(dev))
10343                                 return false;
10344                 case 64:
10345                         break;
10346                 default:
10347                         return false;
10348                 }
10349         }
10350
10351         return true;
10352 }
10353
10354 /* VESA 640x480x72Hz mode to set on the pipe */
10355 static struct drm_display_mode load_detect_mode = {
10356         DRM_MODE("640x480", DRM_MODE_TYPE_DEFAULT, 31500, 640, 664,
10357                  704, 832, 0, 480, 489, 491, 520, 0, DRM_MODE_FLAG_NHSYNC | DRM_MODE_FLAG_NVSYNC),
10358 };
10359
10360 struct drm_framebuffer *
10361 __intel_framebuffer_create(struct drm_device *dev,
10362                            struct drm_mode_fb_cmd2 *mode_cmd,
10363                            struct drm_i915_gem_object *obj)
10364 {
10365         struct intel_framebuffer *intel_fb;
10366         int ret;
10367
10368         intel_fb = kzalloc(sizeof(*intel_fb), GFP_KERNEL);
10369         if (!intel_fb)
10370                 return ERR_PTR(-ENOMEM);
10371
10372         ret = intel_framebuffer_init(dev, intel_fb, mode_cmd, obj);
10373         if (ret)
10374                 goto err;
10375
10376         return &intel_fb->base;
10377
10378 err:
10379         kfree(intel_fb);
10380         return ERR_PTR(ret);
10381 }
10382
10383 static struct drm_framebuffer *
10384 intel_framebuffer_create(struct drm_device *dev,
10385                          struct drm_mode_fb_cmd2 *mode_cmd,
10386                          struct drm_i915_gem_object *obj)
10387 {
10388         struct drm_framebuffer *fb;
10389         int ret;
10390
10391         ret = i915_mutex_lock_interruptible(dev);
10392         if (ret)
10393                 return ERR_PTR(ret);
10394         fb = __intel_framebuffer_create(dev, mode_cmd, obj);
10395         mutex_unlock(&dev->struct_mutex);
10396
10397         return fb;
10398 }
10399
10400 static u32
10401 intel_framebuffer_pitch_for_width(int width, int bpp)
10402 {
10403         u32 pitch = DIV_ROUND_UP(width * bpp, 8);
10404         return ALIGN(pitch, 64);
10405 }
10406
10407 static u32
10408 intel_framebuffer_size_for_mode(struct drm_display_mode *mode, int bpp)
10409 {
10410         u32 pitch = intel_framebuffer_pitch_for_width(mode->hdisplay, bpp);
10411         return PAGE_ALIGN(pitch * mode->vdisplay);
10412 }
10413
10414 static struct drm_framebuffer *
10415 intel_framebuffer_create_for_mode(struct drm_device *dev,
10416                                   struct drm_display_mode *mode,
10417                                   int depth, int bpp)
10418 {
10419         struct drm_framebuffer *fb;
10420         struct drm_i915_gem_object *obj;
10421         struct drm_mode_fb_cmd2 mode_cmd = { 0 };
10422
10423         obj = i915_gem_object_create(dev,
10424                                     intel_framebuffer_size_for_mode(mode, bpp));
10425         if (IS_ERR(obj))
10426                 return ERR_CAST(obj);
10427
10428         mode_cmd.width = mode->hdisplay;
10429         mode_cmd.height = mode->vdisplay;
10430         mode_cmd.pitches[0] = intel_framebuffer_pitch_for_width(mode_cmd.width,
10431                                                                 bpp);
10432         mode_cmd.pixel_format = drm_mode_legacy_fb_format(bpp, depth);
10433
10434         fb = intel_framebuffer_create(dev, &mode_cmd, obj);
10435         if (IS_ERR(fb))
10436                 i915_gem_object_put_unlocked(obj);
10437
10438         return fb;
10439 }
10440
10441 static struct drm_framebuffer *
10442 mode_fits_in_fbdev(struct drm_device *dev,
10443                    struct drm_display_mode *mode)
10444 {
10445 #ifdef CONFIG_DRM_FBDEV_EMULATION
10446         struct drm_i915_private *dev_priv = to_i915(dev);
10447         struct drm_i915_gem_object *obj;
10448         struct drm_framebuffer *fb;
10449
10450         if (!dev_priv->fbdev)
10451                 return NULL;
10452
10453         if (!dev_priv->fbdev->fb)
10454                 return NULL;
10455
10456         obj = dev_priv->fbdev->fb->obj;
10457         BUG_ON(!obj);
10458
10459         fb = &dev_priv->fbdev->fb->base;
10460         if (fb->pitches[0] < intel_framebuffer_pitch_for_width(mode->hdisplay,
10461                                                                fb->bits_per_pixel))
10462                 return NULL;
10463
10464         if (obj->base.size < mode->vdisplay * fb->pitches[0])
10465                 return NULL;
10466
10467         drm_framebuffer_reference(fb);
10468         return fb;
10469 #else
10470         return NULL;
10471 #endif
10472 }
10473
10474 static int intel_modeset_setup_plane_state(struct drm_atomic_state *state,
10475                                            struct drm_crtc *crtc,
10476                                            struct drm_display_mode *mode,
10477                                            struct drm_framebuffer *fb,
10478                                            int x, int y)
10479 {
10480         struct drm_plane_state *plane_state;
10481         int hdisplay, vdisplay;
10482         int ret;
10483
10484         plane_state = drm_atomic_get_plane_state(state, crtc->primary);
10485         if (IS_ERR(plane_state))
10486                 return PTR_ERR(plane_state);
10487
10488         if (mode)
10489                 drm_crtc_get_hv_timing(mode, &hdisplay, &vdisplay);
10490         else
10491                 hdisplay = vdisplay = 0;
10492
10493         ret = drm_atomic_set_crtc_for_plane(plane_state, fb ? crtc : NULL);
10494         if (ret)
10495                 return ret;
10496         drm_atomic_set_fb_for_plane(plane_state, fb);
10497         plane_state->crtc_x = 0;
10498         plane_state->crtc_y = 0;
10499         plane_state->crtc_w = hdisplay;
10500         plane_state->crtc_h = vdisplay;
10501         plane_state->src_x = x << 16;
10502         plane_state->src_y = y << 16;
10503         plane_state->src_w = hdisplay << 16;
10504         plane_state->src_h = vdisplay << 16;
10505
10506         return 0;
10507 }
10508
10509 bool intel_get_load_detect_pipe(struct drm_connector *connector,
10510                                 struct drm_display_mode *mode,
10511                                 struct intel_load_detect_pipe *old,
10512                                 struct drm_modeset_acquire_ctx *ctx)
10513 {
10514         struct intel_crtc *intel_crtc;
10515         struct intel_encoder *intel_encoder =
10516                 intel_attached_encoder(connector);
10517         struct drm_crtc *possible_crtc;
10518         struct drm_encoder *encoder = &intel_encoder->base;
10519         struct drm_crtc *crtc = NULL;
10520         struct drm_device *dev = encoder->dev;
10521         struct drm_framebuffer *fb;
10522         struct drm_mode_config *config = &dev->mode_config;
10523         struct drm_atomic_state *state = NULL, *restore_state = NULL;
10524         struct drm_connector_state *connector_state;
10525         struct intel_crtc_state *crtc_state;
10526         int ret, i = -1;
10527
10528         DRM_DEBUG_KMS("[CONNECTOR:%d:%s], [ENCODER:%d:%s]\n",
10529                       connector->base.id, connector->name,
10530                       encoder->base.id, encoder->name);
10531
10532         old->restore_state = NULL;
10533
10534 retry:
10535         ret = drm_modeset_lock(&config->connection_mutex, ctx);
10536         if (ret)
10537                 goto fail;
10538
10539         /*
10540          * Algorithm gets a little messy:
10541          *
10542          *   - if the connector already has an assigned crtc, use it (but make
10543          *     sure it's on first)
10544          *
10545          *   - try to find the first unused crtc that can drive this connector,
10546          *     and use that if we find one
10547          */
10548
10549         /* See if we already have a CRTC for this connector */
10550         if (connector->state->crtc) {
10551                 crtc = connector->state->crtc;
10552
10553                 ret = drm_modeset_lock(&crtc->mutex, ctx);
10554                 if (ret)
10555                         goto fail;
10556
10557                 /* Make sure the crtc and connector are running */
10558                 goto found;
10559         }
10560
10561         /* Find an unused one (if possible) */
10562         for_each_crtc(dev, possible_crtc) {
10563                 i++;
10564                 if (!(encoder->possible_crtcs & (1 << i)))
10565                         continue;
10566
10567                 ret = drm_modeset_lock(&possible_crtc->mutex, ctx);
10568                 if (ret)
10569                         goto fail;
10570
10571                 if (possible_crtc->state->enable) {
10572                         drm_modeset_unlock(&possible_crtc->mutex);
10573                         continue;
10574                 }
10575
10576                 crtc = possible_crtc;
10577                 break;
10578         }
10579
10580         /*
10581          * If we didn't find an unused CRTC, don't use any.
10582          */
10583         if (!crtc) {
10584                 DRM_DEBUG_KMS("no pipe available for load-detect\n");
10585                 goto fail;
10586         }
10587
10588 found:
10589         intel_crtc = to_intel_crtc(crtc);
10590
10591         ret = drm_modeset_lock(&crtc->primary->mutex, ctx);
10592         if (ret)
10593                 goto fail;
10594
10595         state = drm_atomic_state_alloc(dev);
10596         restore_state = drm_atomic_state_alloc(dev);
10597         if (!state || !restore_state) {
10598                 ret = -ENOMEM;
10599                 goto fail;
10600         }
10601
10602         state->acquire_ctx = ctx;
10603         restore_state->acquire_ctx = ctx;
10604
10605         connector_state = drm_atomic_get_connector_state(state, connector);
10606         if (IS_ERR(connector_state)) {
10607                 ret = PTR_ERR(connector_state);
10608                 goto fail;
10609         }
10610
10611         ret = drm_atomic_set_crtc_for_connector(connector_state, crtc);
10612         if (ret)
10613                 goto fail;
10614
10615         crtc_state = intel_atomic_get_crtc_state(state, intel_crtc);
10616         if (IS_ERR(crtc_state)) {
10617                 ret = PTR_ERR(crtc_state);
10618                 goto fail;
10619         }
10620
10621         crtc_state->base.active = crtc_state->base.enable = true;
10622
10623         if (!mode)
10624                 mode = &load_detect_mode;
10625
10626         /* We need a framebuffer large enough to accommodate all accesses
10627          * that the plane may generate whilst we perform load detection.
10628          * We can not rely on the fbcon either being present (we get called
10629          * during its initialisation to detect all boot displays, or it may
10630          * not even exist) or that it is large enough to satisfy the
10631          * requested mode.
10632          */
10633         fb = mode_fits_in_fbdev(dev, mode);
10634         if (fb == NULL) {
10635                 DRM_DEBUG_KMS("creating tmp fb for load-detection\n");
10636                 fb = intel_framebuffer_create_for_mode(dev, mode, 24, 32);
10637         } else
10638                 DRM_DEBUG_KMS("reusing fbdev for load-detection framebuffer\n");
10639         if (IS_ERR(fb)) {
10640                 DRM_DEBUG_KMS("failed to allocate framebuffer for load-detection\n");
10641                 goto fail;
10642         }
10643
10644         ret = intel_modeset_setup_plane_state(state, crtc, mode, fb, 0, 0);
10645         if (ret)
10646                 goto fail;
10647
10648         drm_framebuffer_unreference(fb);
10649
10650         ret = drm_atomic_set_mode_for_crtc(&crtc_state->base, mode);
10651         if (ret)
10652                 goto fail;
10653
10654         ret = PTR_ERR_OR_ZERO(drm_atomic_get_connector_state(restore_state, connector));
10655         if (!ret)
10656                 ret = PTR_ERR_OR_ZERO(drm_atomic_get_crtc_state(restore_state, crtc));
10657         if (!ret)
10658                 ret = PTR_ERR_OR_ZERO(drm_atomic_get_plane_state(restore_state, crtc->primary));
10659         if (ret) {
10660                 DRM_DEBUG_KMS("Failed to create a copy of old state to restore: %i\n", ret);
10661                 goto fail;
10662         }
10663
10664         ret = drm_atomic_commit(state);
10665         if (ret) {
10666                 DRM_DEBUG_KMS("failed to set mode on load-detect pipe\n");
10667                 goto fail;
10668         }
10669
10670         old->restore_state = restore_state;
10671
10672         /* let the connector get through one full cycle before testing */
10673         intel_wait_for_vblank(dev, intel_crtc->pipe);
10674         return true;
10675
10676 fail:
10677         drm_atomic_state_free(state);
10678         drm_atomic_state_free(restore_state);
10679         restore_state = state = NULL;
10680
10681         if (ret == -EDEADLK) {
10682                 drm_modeset_backoff(ctx);
10683                 goto retry;
10684         }
10685
10686         return false;
10687 }
10688
10689 void intel_release_load_detect_pipe(struct drm_connector *connector,
10690                                     struct intel_load_detect_pipe *old,
10691                                     struct drm_modeset_acquire_ctx *ctx)
10692 {
10693         struct intel_encoder *intel_encoder =
10694                 intel_attached_encoder(connector);
10695         struct drm_encoder *encoder = &intel_encoder->base;
10696         struct drm_atomic_state *state = old->restore_state;
10697         int ret;
10698
10699         DRM_DEBUG_KMS("[CONNECTOR:%d:%s], [ENCODER:%d:%s]\n",
10700                       connector->base.id, connector->name,
10701                       encoder->base.id, encoder->name);
10702
10703         if (!state)
10704                 return;
10705
10706         ret = drm_atomic_commit(state);
10707         if (ret) {
10708                 DRM_DEBUG_KMS("Couldn't release load detect pipe: %i\n", ret);
10709                 drm_atomic_state_free(state);
10710         }
10711 }
10712
10713 static int i9xx_pll_refclk(struct drm_device *dev,
10714                            const struct intel_crtc_state *pipe_config)
10715 {
10716         struct drm_i915_private *dev_priv = to_i915(dev);
10717         u32 dpll = pipe_config->dpll_hw_state.dpll;
10718
10719         if ((dpll & PLL_REF_INPUT_MASK) == PLLB_REF_INPUT_SPREADSPECTRUMIN)
10720                 return dev_priv->vbt.lvds_ssc_freq;
10721         else if (HAS_PCH_SPLIT(dev))
10722                 return 120000;
10723         else if (!IS_GEN2(dev))
10724                 return 96000;
10725         else
10726                 return 48000;
10727 }
10728
10729 /* Returns the clock of the currently programmed mode of the given pipe. */
10730 static void i9xx_crtc_clock_get(struct intel_crtc *crtc,
10731                                 struct intel_crtc_state *pipe_config)
10732 {
10733         struct drm_device *dev = crtc->base.dev;
10734         struct drm_i915_private *dev_priv = to_i915(dev);
10735         int pipe = pipe_config->cpu_transcoder;
10736         u32 dpll = pipe_config->dpll_hw_state.dpll;
10737         u32 fp;
10738         struct dpll clock;
10739         int port_clock;
10740         int refclk = i9xx_pll_refclk(dev, pipe_config);
10741
10742         if ((dpll & DISPLAY_RATE_SELECT_FPA1) == 0)
10743                 fp = pipe_config->dpll_hw_state.fp0;
10744         else
10745                 fp = pipe_config->dpll_hw_state.fp1;
10746
10747         clock.m1 = (fp & FP_M1_DIV_MASK) >> FP_M1_DIV_SHIFT;
10748         if (IS_PINEVIEW(dev)) {
10749                 clock.n = ffs((fp & FP_N_PINEVIEW_DIV_MASK) >> FP_N_DIV_SHIFT) - 1;
10750                 clock.m2 = (fp & FP_M2_PINEVIEW_DIV_MASK) >> FP_M2_DIV_SHIFT;
10751         } else {
10752                 clock.n = (fp & FP_N_DIV_MASK) >> FP_N_DIV_SHIFT;
10753                 clock.m2 = (fp & FP_M2_DIV_MASK) >> FP_M2_DIV_SHIFT;
10754         }
10755
10756         if (!IS_GEN2(dev)) {
10757                 if (IS_PINEVIEW(dev))
10758                         clock.p1 = ffs((dpll & DPLL_FPA01_P1_POST_DIV_MASK_PINEVIEW) >>
10759                                 DPLL_FPA01_P1_POST_DIV_SHIFT_PINEVIEW);
10760                 else
10761                         clock.p1 = ffs((dpll & DPLL_FPA01_P1_POST_DIV_MASK) >>
10762                                DPLL_FPA01_P1_POST_DIV_SHIFT);
10763
10764                 switch (dpll & DPLL_MODE_MASK) {
10765                 case DPLLB_MODE_DAC_SERIAL:
10766                         clock.p2 = dpll & DPLL_DAC_SERIAL_P2_CLOCK_DIV_5 ?
10767                                 5 : 10;
10768                         break;
10769                 case DPLLB_MODE_LVDS:
10770                         clock.p2 = dpll & DPLLB_LVDS_P2_CLOCK_DIV_7 ?
10771                                 7 : 14;
10772                         break;
10773                 default:
10774                         DRM_DEBUG_KMS("Unknown DPLL mode %08x in programmed "
10775                                   "mode\n", (int)(dpll & DPLL_MODE_MASK));
10776                         return;
10777                 }
10778
10779                 if (IS_PINEVIEW(dev))
10780                         port_clock = pnv_calc_dpll_params(refclk, &clock);
10781                 else
10782                         port_clock = i9xx_calc_dpll_params(refclk, &clock);
10783         } else {
10784                 u32 lvds = IS_I830(dev) ? 0 : I915_READ(LVDS);
10785                 bool is_lvds = (pipe == 1) && (lvds & LVDS_PORT_EN);
10786
10787                 if (is_lvds) {
10788                         clock.p1 = ffs((dpll & DPLL_FPA01_P1_POST_DIV_MASK_I830_LVDS) >>
10789                                        DPLL_FPA01_P1_POST_DIV_SHIFT);
10790
10791                         if (lvds & LVDS_CLKB_POWER_UP)
10792                                 clock.p2 = 7;
10793                         else
10794                                 clock.p2 = 14;
10795                 } else {
10796                         if (dpll & PLL_P1_DIVIDE_BY_TWO)
10797                                 clock.p1 = 2;
10798                         else {
10799                                 clock.p1 = ((dpll & DPLL_FPA01_P1_POST_DIV_MASK_I830) >>
10800                                             DPLL_FPA01_P1_POST_DIV_SHIFT) + 2;
10801                         }
10802                         if (dpll & PLL_P2_DIVIDE_BY_4)
10803                                 clock.p2 = 4;
10804                         else
10805                                 clock.p2 = 2;
10806                 }
10807
10808                 port_clock = i9xx_calc_dpll_params(refclk, &clock);
10809         }
10810
10811         /*
10812          * This value includes pixel_multiplier. We will use
10813          * port_clock to compute adjusted_mode.crtc_clock in the
10814          * encoder's get_config() function.
10815          */
10816         pipe_config->port_clock = port_clock;
10817 }
10818
10819 int intel_dotclock_calculate(int link_freq,
10820                              const struct intel_link_m_n *m_n)
10821 {
10822         /*
10823          * The calculation for the data clock is:
10824          * pixel_clock = ((m/n)*(link_clock * nr_lanes))/bpp
10825          * But we want to avoid losing precison if possible, so:
10826          * pixel_clock = ((m * link_clock * nr_lanes)/(n*bpp))
10827          *
10828          * and the link clock is simpler:
10829          * link_clock = (m * link_clock) / n
10830          */
10831
10832         if (!m_n->link_n)
10833                 return 0;
10834
10835         return div_u64((u64)m_n->link_m * link_freq, m_n->link_n);
10836 }
10837
10838 static void ironlake_pch_clock_get(struct intel_crtc *crtc,
10839                                    struct intel_crtc_state *pipe_config)
10840 {
10841         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
10842
10843         /* read out port_clock from the DPLL */
10844         i9xx_crtc_clock_get(crtc, pipe_config);
10845
10846         /*
10847          * In case there is an active pipe without active ports,
10848          * we may need some idea for the dotclock anyway.
10849          * Calculate one based on the FDI configuration.
10850          */
10851         pipe_config->base.adjusted_mode.crtc_clock =
10852                 intel_dotclock_calculate(intel_fdi_link_freq(dev_priv, pipe_config),
10853                                          &pipe_config->fdi_m_n);
10854 }
10855
10856 /** Returns the currently programmed mode of the given pipe. */
10857 struct drm_display_mode *intel_crtc_mode_get(struct drm_device *dev,
10858                                              struct drm_crtc *crtc)
10859 {
10860         struct drm_i915_private *dev_priv = to_i915(dev);
10861         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10862         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
10863         struct drm_display_mode *mode;
10864         struct intel_crtc_state *pipe_config;
10865         int htot = I915_READ(HTOTAL(cpu_transcoder));
10866         int hsync = I915_READ(HSYNC(cpu_transcoder));
10867         int vtot = I915_READ(VTOTAL(cpu_transcoder));
10868         int vsync = I915_READ(VSYNC(cpu_transcoder));
10869         enum pipe pipe = intel_crtc->pipe;
10870
10871         mode = kzalloc(sizeof(*mode), GFP_KERNEL);
10872         if (!mode)
10873                 return NULL;
10874
10875         pipe_config = kzalloc(sizeof(*pipe_config), GFP_KERNEL);
10876         if (!pipe_config) {
10877                 kfree(mode);
10878                 return NULL;
10879         }
10880
10881         /*
10882          * Construct a pipe_config sufficient for getting the clock info
10883          * back out of crtc_clock_get.
10884          *
10885          * Note, if LVDS ever uses a non-1 pixel multiplier, we'll need
10886          * to use a real value here instead.
10887          */
10888         pipe_config->cpu_transcoder = (enum transcoder) pipe;
10889         pipe_config->pixel_multiplier = 1;
10890         pipe_config->dpll_hw_state.dpll = I915_READ(DPLL(pipe));
10891         pipe_config->dpll_hw_state.fp0 = I915_READ(FP0(pipe));
10892         pipe_config->dpll_hw_state.fp1 = I915_READ(FP1(pipe));
10893         i9xx_crtc_clock_get(intel_crtc, pipe_config);
10894
10895         mode->clock = pipe_config->port_clock / pipe_config->pixel_multiplier;
10896         mode->hdisplay = (htot & 0xffff) + 1;
10897         mode->htotal = ((htot & 0xffff0000) >> 16) + 1;
10898         mode->hsync_start = (hsync & 0xffff) + 1;
10899         mode->hsync_end = ((hsync & 0xffff0000) >> 16) + 1;
10900         mode->vdisplay = (vtot & 0xffff) + 1;
10901         mode->vtotal = ((vtot & 0xffff0000) >> 16) + 1;
10902         mode->vsync_start = (vsync & 0xffff) + 1;
10903         mode->vsync_end = ((vsync & 0xffff0000) >> 16) + 1;
10904
10905         drm_mode_set_name(mode);
10906
10907         kfree(pipe_config);
10908
10909         return mode;
10910 }
10911
10912 static void intel_crtc_destroy(struct drm_crtc *crtc)
10913 {
10914         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10915         struct drm_device *dev = crtc->dev;
10916         struct intel_flip_work *work;
10917
10918         spin_lock_irq(&dev->event_lock);
10919         work = intel_crtc->flip_work;
10920         intel_crtc->flip_work = NULL;
10921         spin_unlock_irq(&dev->event_lock);
10922
10923         if (work) {
10924                 cancel_work_sync(&work->mmio_work);
10925                 cancel_work_sync(&work->unpin_work);
10926                 kfree(work);
10927         }
10928
10929         drm_crtc_cleanup(crtc);
10930
10931         kfree(intel_crtc);
10932 }
10933
10934 static void intel_unpin_work_fn(struct work_struct *__work)
10935 {
10936         struct intel_flip_work *work =
10937                 container_of(__work, struct intel_flip_work, unpin_work);
10938         struct intel_crtc *crtc = to_intel_crtc(work->crtc);
10939         struct drm_device *dev = crtc->base.dev;
10940         struct drm_plane *primary = crtc->base.primary;
10941
10942         if (is_mmio_work(work))
10943                 flush_work(&work->mmio_work);
10944
10945         mutex_lock(&dev->struct_mutex);
10946         intel_unpin_fb_obj(work->old_fb, primary->state->rotation);
10947         i915_gem_object_put(work->pending_flip_obj);
10948         mutex_unlock(&dev->struct_mutex);
10949
10950         i915_gem_request_put(work->flip_queued_req);
10951
10952         intel_frontbuffer_flip_complete(to_i915(dev),
10953                                         to_intel_plane(primary)->frontbuffer_bit);
10954         intel_fbc_post_update(crtc);
10955         drm_framebuffer_unreference(work->old_fb);
10956
10957         BUG_ON(atomic_read(&crtc->unpin_work_count) == 0);
10958         atomic_dec(&crtc->unpin_work_count);
10959
10960         kfree(work);
10961 }
10962
10963 /* Is 'a' after or equal to 'b'? */
10964 static bool g4x_flip_count_after_eq(u32 a, u32 b)
10965 {
10966         return !((a - b) & 0x80000000);
10967 }
10968
10969 static bool __pageflip_finished_cs(struct intel_crtc *crtc,
10970                                    struct intel_flip_work *work)
10971 {
10972         struct drm_device *dev = crtc->base.dev;
10973         struct drm_i915_private *dev_priv = to_i915(dev);
10974         unsigned reset_counter;
10975
10976         reset_counter = i915_reset_counter(&dev_priv->gpu_error);
10977         if (crtc->reset_counter != reset_counter)
10978                 return true;
10979
10980         /*
10981          * The relevant registers doen't exist on pre-ctg.
10982          * As the flip done interrupt doesn't trigger for mmio
10983          * flips on gmch platforms, a flip count check isn't
10984          * really needed there. But since ctg has the registers,
10985          * include it in the check anyway.
10986          */
10987         if (INTEL_INFO(dev)->gen < 5 && !IS_G4X(dev))
10988                 return true;
10989
10990         /*
10991          * BDW signals flip done immediately if the plane
10992          * is disabled, even if the plane enable is already
10993          * armed to occur at the next vblank :(
10994          */
10995
10996         /*
10997          * A DSPSURFLIVE check isn't enough in case the mmio and CS flips
10998          * used the same base address. In that case the mmio flip might
10999          * have completed, but the CS hasn't even executed the flip yet.
11000          *
11001          * A flip count check isn't enough as the CS might have updated
11002          * the base address just after start of vblank, but before we
11003          * managed to process the interrupt. This means we'd complete the
11004          * CS flip too soon.
11005          *
11006          * Combining both checks should get us a good enough result. It may
11007          * still happen that the CS flip has been executed, but has not
11008          * yet actually completed. But in case the base address is the same
11009          * anyway, we don't really care.
11010          */
11011         return (I915_READ(DSPSURFLIVE(crtc->plane)) & ~0xfff) ==
11012                 crtc->flip_work->gtt_offset &&
11013                 g4x_flip_count_after_eq(I915_READ(PIPE_FLIPCOUNT_G4X(crtc->pipe)),
11014                                     crtc->flip_work->flip_count);
11015 }
11016
11017 static bool
11018 __pageflip_finished_mmio(struct intel_crtc *crtc,
11019                                struct intel_flip_work *work)
11020 {
11021         /*
11022          * MMIO work completes when vblank is different from
11023          * flip_queued_vblank.
11024          *
11025          * Reset counter value doesn't matter, this is handled by
11026          * i915_wait_request finishing early, so no need to handle
11027          * reset here.
11028          */
11029         return intel_crtc_get_vblank_counter(crtc) != work->flip_queued_vblank;
11030 }
11031
11032
11033 static bool pageflip_finished(struct intel_crtc *crtc,
11034                               struct intel_flip_work *work)
11035 {
11036         if (!atomic_read(&work->pending))
11037                 return false;
11038
11039         smp_rmb();
11040
11041         if (is_mmio_work(work))
11042                 return __pageflip_finished_mmio(crtc, work);
11043         else
11044                 return __pageflip_finished_cs(crtc, work);
11045 }
11046
11047 void intel_finish_page_flip_cs(struct drm_i915_private *dev_priv, int pipe)
11048 {
11049         struct drm_device *dev = &dev_priv->drm;
11050         struct drm_crtc *crtc = dev_priv->pipe_to_crtc_mapping[pipe];
11051         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11052         struct intel_flip_work *work;
11053         unsigned long flags;
11054
11055         /* Ignore early vblank irqs */
11056         if (!crtc)
11057                 return;
11058
11059         /*
11060          * This is called both by irq handlers and the reset code (to complete
11061          * lost pageflips) so needs the full irqsave spinlocks.
11062          */
11063         spin_lock_irqsave(&dev->event_lock, flags);
11064         work = intel_crtc->flip_work;
11065
11066         if (work != NULL &&
11067             !is_mmio_work(work) &&
11068             pageflip_finished(intel_crtc, work))
11069                 page_flip_completed(intel_crtc);
11070
11071         spin_unlock_irqrestore(&dev->event_lock, flags);
11072 }
11073
11074 void intel_finish_page_flip_mmio(struct drm_i915_private *dev_priv, int pipe)
11075 {
11076         struct drm_device *dev = &dev_priv->drm;
11077         struct drm_crtc *crtc = dev_priv->pipe_to_crtc_mapping[pipe];
11078         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11079         struct intel_flip_work *work;
11080         unsigned long flags;
11081
11082         /* Ignore early vblank irqs */
11083         if (!crtc)
11084                 return;
11085
11086         /*
11087          * This is called both by irq handlers and the reset code (to complete
11088          * lost pageflips) so needs the full irqsave spinlocks.
11089          */
11090         spin_lock_irqsave(&dev->event_lock, flags);
11091         work = intel_crtc->flip_work;
11092
11093         if (work != NULL &&
11094             is_mmio_work(work) &&
11095             pageflip_finished(intel_crtc, work))
11096                 page_flip_completed(intel_crtc);
11097
11098         spin_unlock_irqrestore(&dev->event_lock, flags);
11099 }
11100
11101 static inline void intel_mark_page_flip_active(struct intel_crtc *crtc,
11102                                                struct intel_flip_work *work)
11103 {
11104         work->flip_queued_vblank = intel_crtc_get_vblank_counter(crtc);
11105
11106         /* Ensure that the work item is consistent when activating it ... */
11107         smp_mb__before_atomic();
11108         atomic_set(&work->pending, 1);
11109 }
11110
11111 static int intel_gen2_queue_flip(struct drm_device *dev,
11112                                  struct drm_crtc *crtc,
11113                                  struct drm_framebuffer *fb,
11114                                  struct drm_i915_gem_object *obj,
11115                                  struct drm_i915_gem_request *req,
11116                                  uint32_t flags)
11117 {
11118         struct intel_ring *ring = req->ring;
11119         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11120         u32 flip_mask;
11121         int ret;
11122
11123         ret = intel_ring_begin(req, 6);
11124         if (ret)
11125                 return ret;
11126
11127         /* Can't queue multiple flips, so wait for the previous
11128          * one to finish before executing the next.
11129          */
11130         if (intel_crtc->plane)
11131                 flip_mask = MI_WAIT_FOR_PLANE_B_FLIP;
11132         else
11133                 flip_mask = MI_WAIT_FOR_PLANE_A_FLIP;
11134         intel_ring_emit(ring, MI_WAIT_FOR_EVENT | flip_mask);
11135         intel_ring_emit(ring, MI_NOOP);
11136         intel_ring_emit(ring, MI_DISPLAY_FLIP |
11137                         MI_DISPLAY_FLIP_PLANE(intel_crtc->plane));
11138         intel_ring_emit(ring, fb->pitches[0]);
11139         intel_ring_emit(ring, intel_crtc->flip_work->gtt_offset);
11140         intel_ring_emit(ring, 0); /* aux display base address, unused */
11141
11142         return 0;
11143 }
11144
11145 static int intel_gen3_queue_flip(struct drm_device *dev,
11146                                  struct drm_crtc *crtc,
11147                                  struct drm_framebuffer *fb,
11148                                  struct drm_i915_gem_object *obj,
11149                                  struct drm_i915_gem_request *req,
11150                                  uint32_t flags)
11151 {
11152         struct intel_ring *ring = req->ring;
11153         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11154         u32 flip_mask;
11155         int ret;
11156
11157         ret = intel_ring_begin(req, 6);
11158         if (ret)
11159                 return ret;
11160
11161         if (intel_crtc->plane)
11162                 flip_mask = MI_WAIT_FOR_PLANE_B_FLIP;
11163         else
11164                 flip_mask = MI_WAIT_FOR_PLANE_A_FLIP;
11165         intel_ring_emit(ring, MI_WAIT_FOR_EVENT | flip_mask);
11166         intel_ring_emit(ring, MI_NOOP);
11167         intel_ring_emit(ring, MI_DISPLAY_FLIP_I915 |
11168                         MI_DISPLAY_FLIP_PLANE(intel_crtc->plane));
11169         intel_ring_emit(ring, fb->pitches[0]);
11170         intel_ring_emit(ring, intel_crtc->flip_work->gtt_offset);
11171         intel_ring_emit(ring, MI_NOOP);
11172
11173         return 0;
11174 }
11175
11176 static int intel_gen4_queue_flip(struct drm_device *dev,
11177                                  struct drm_crtc *crtc,
11178                                  struct drm_framebuffer *fb,
11179                                  struct drm_i915_gem_object *obj,
11180                                  struct drm_i915_gem_request *req,
11181                                  uint32_t flags)
11182 {
11183         struct intel_ring *ring = req->ring;
11184         struct drm_i915_private *dev_priv = to_i915(dev);
11185         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11186         uint32_t pf, pipesrc;
11187         int ret;
11188
11189         ret = intel_ring_begin(req, 4);
11190         if (ret)
11191                 return ret;
11192
11193         /* i965+ uses the linear or tiled offsets from the
11194          * Display Registers (which do not change across a page-flip)
11195          * so we need only reprogram the base address.
11196          */
11197         intel_ring_emit(ring, MI_DISPLAY_FLIP |
11198                         MI_DISPLAY_FLIP_PLANE(intel_crtc->plane));
11199         intel_ring_emit(ring, fb->pitches[0]);
11200         intel_ring_emit(ring, intel_crtc->flip_work->gtt_offset |
11201                         i915_gem_object_get_tiling(obj));
11202
11203         /* XXX Enabling the panel-fitter across page-flip is so far
11204          * untested on non-native modes, so ignore it for now.
11205          * pf = I915_READ(pipe == 0 ? PFA_CTL_1 : PFB_CTL_1) & PF_ENABLE;
11206          */
11207         pf = 0;
11208         pipesrc = I915_READ(PIPESRC(intel_crtc->pipe)) & 0x0fff0fff;
11209         intel_ring_emit(ring, pf | pipesrc);
11210
11211         return 0;
11212 }
11213
11214 static int intel_gen6_queue_flip(struct drm_device *dev,
11215                                  struct drm_crtc *crtc,
11216                                  struct drm_framebuffer *fb,
11217                                  struct drm_i915_gem_object *obj,
11218                                  struct drm_i915_gem_request *req,
11219                                  uint32_t flags)
11220 {
11221         struct intel_ring *ring = req->ring;
11222         struct drm_i915_private *dev_priv = to_i915(dev);
11223         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11224         uint32_t pf, pipesrc;
11225         int ret;
11226
11227         ret = intel_ring_begin(req, 4);
11228         if (ret)
11229                 return ret;
11230
11231         intel_ring_emit(ring, MI_DISPLAY_FLIP |
11232                         MI_DISPLAY_FLIP_PLANE(intel_crtc->plane));
11233         intel_ring_emit(ring, fb->pitches[0] | i915_gem_object_get_tiling(obj));
11234         intel_ring_emit(ring, intel_crtc->flip_work->gtt_offset);
11235
11236         /* Contrary to the suggestions in the documentation,
11237          * "Enable Panel Fitter" does not seem to be required when page
11238          * flipping with a non-native mode, and worse causes a normal
11239          * modeset to fail.
11240          * pf = I915_READ(PF_CTL(intel_crtc->pipe)) & PF_ENABLE;
11241          */
11242         pf = 0;
11243         pipesrc = I915_READ(PIPESRC(intel_crtc->pipe)) & 0x0fff0fff;
11244         intel_ring_emit(ring, pf | pipesrc);
11245
11246         return 0;
11247 }
11248
11249 static int intel_gen7_queue_flip(struct drm_device *dev,
11250                                  struct drm_crtc *crtc,
11251                                  struct drm_framebuffer *fb,
11252                                  struct drm_i915_gem_object *obj,
11253                                  struct drm_i915_gem_request *req,
11254                                  uint32_t flags)
11255 {
11256         struct intel_ring *ring = req->ring;
11257         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11258         uint32_t plane_bit = 0;
11259         int len, ret;
11260
11261         switch (intel_crtc->plane) {
11262         case PLANE_A:
11263                 plane_bit = MI_DISPLAY_FLIP_IVB_PLANE_A;
11264                 break;
11265         case PLANE_B:
11266                 plane_bit = MI_DISPLAY_FLIP_IVB_PLANE_B;
11267                 break;
11268         case PLANE_C:
11269                 plane_bit = MI_DISPLAY_FLIP_IVB_PLANE_C;
11270                 break;
11271         default:
11272                 WARN_ONCE(1, "unknown plane in flip command\n");
11273                 return -ENODEV;
11274         }
11275
11276         len = 4;
11277         if (req->engine->id == RCS) {
11278                 len += 6;
11279                 /*
11280                  * On Gen 8, SRM is now taking an extra dword to accommodate
11281                  * 48bits addresses, and we need a NOOP for the batch size to
11282                  * stay even.
11283                  */
11284                 if (IS_GEN8(dev))
11285                         len += 2;
11286         }
11287
11288         /*
11289          * BSpec MI_DISPLAY_FLIP for IVB:
11290          * "The full packet must be contained within the same cache line."
11291          *
11292          * Currently the LRI+SRM+MI_DISPLAY_FLIP all fit within the same
11293          * cacheline, if we ever start emitting more commands before
11294          * the MI_DISPLAY_FLIP we may need to first emit everything else,
11295          * then do the cacheline alignment, and finally emit the
11296          * MI_DISPLAY_FLIP.
11297          */
11298         ret = intel_ring_cacheline_align(req);
11299         if (ret)
11300                 return ret;
11301
11302         ret = intel_ring_begin(req, len);
11303         if (ret)
11304                 return ret;
11305
11306         /* Unmask the flip-done completion message. Note that the bspec says that
11307          * we should do this for both the BCS and RCS, and that we must not unmask
11308          * more than one flip event at any time (or ensure that one flip message
11309          * can be sent by waiting for flip-done prior to queueing new flips).
11310          * Experimentation says that BCS works despite DERRMR masking all
11311          * flip-done completion events and that unmasking all planes at once
11312          * for the RCS also doesn't appear to drop events. Setting the DERRMR
11313          * to zero does lead to lockups within MI_DISPLAY_FLIP.
11314          */
11315         if (req->engine->id == RCS) {
11316                 intel_ring_emit(ring, MI_LOAD_REGISTER_IMM(1));
11317                 intel_ring_emit_reg(ring, DERRMR);
11318                 intel_ring_emit(ring, ~(DERRMR_PIPEA_PRI_FLIP_DONE |
11319                                           DERRMR_PIPEB_PRI_FLIP_DONE |
11320                                           DERRMR_PIPEC_PRI_FLIP_DONE));
11321                 if (IS_GEN8(dev))
11322                         intel_ring_emit(ring, MI_STORE_REGISTER_MEM_GEN8 |
11323                                               MI_SRM_LRM_GLOBAL_GTT);
11324                 else
11325                         intel_ring_emit(ring, MI_STORE_REGISTER_MEM |
11326                                               MI_SRM_LRM_GLOBAL_GTT);
11327                 intel_ring_emit_reg(ring, DERRMR);
11328                 intel_ring_emit(ring, req->engine->scratch.gtt_offset + 256);
11329                 if (IS_GEN8(dev)) {
11330                         intel_ring_emit(ring, 0);
11331                         intel_ring_emit(ring, MI_NOOP);
11332                 }
11333         }
11334
11335         intel_ring_emit(ring, MI_DISPLAY_FLIP_I915 | plane_bit);
11336         intel_ring_emit(ring, fb->pitches[0] | i915_gem_object_get_tiling(obj));
11337         intel_ring_emit(ring, intel_crtc->flip_work->gtt_offset);
11338         intel_ring_emit(ring, (MI_NOOP));
11339
11340         return 0;
11341 }
11342
11343 static bool use_mmio_flip(struct intel_engine_cs *engine,
11344                           struct drm_i915_gem_object *obj)
11345 {
11346         struct reservation_object *resv;
11347
11348         /*
11349          * This is not being used for older platforms, because
11350          * non-availability of flip done interrupt forces us to use
11351          * CS flips. Older platforms derive flip done using some clever
11352          * tricks involving the flip_pending status bits and vblank irqs.
11353          * So using MMIO flips there would disrupt this mechanism.
11354          */
11355
11356         if (engine == NULL)
11357                 return true;
11358
11359         if (INTEL_GEN(engine->i915) < 5)
11360                 return false;
11361
11362         if (i915.use_mmio_flip < 0)
11363                 return false;
11364         else if (i915.use_mmio_flip > 0)
11365                 return true;
11366         else if (i915.enable_execlists)
11367                 return true;
11368
11369         resv = i915_gem_object_get_dmabuf_resv(obj);
11370         if (resv && !reservation_object_test_signaled_rcu(resv, false))
11371                 return true;
11372
11373         return engine != i915_gem_active_get_engine(&obj->last_write,
11374                                                     &obj->base.dev->struct_mutex);
11375 }
11376
11377 static void skl_do_mmio_flip(struct intel_crtc *intel_crtc,
11378                              unsigned int rotation,
11379                              struct intel_flip_work *work)
11380 {
11381         struct drm_device *dev = intel_crtc->base.dev;
11382         struct drm_i915_private *dev_priv = to_i915(dev);
11383         struct drm_framebuffer *fb = intel_crtc->base.primary->fb;
11384         const enum pipe pipe = intel_crtc->pipe;
11385         u32 ctl, stride, tile_height;
11386
11387         ctl = I915_READ(PLANE_CTL(pipe, 0));
11388         ctl &= ~PLANE_CTL_TILED_MASK;
11389         switch (fb->modifier[0]) {
11390         case DRM_FORMAT_MOD_NONE:
11391                 break;
11392         case I915_FORMAT_MOD_X_TILED:
11393                 ctl |= PLANE_CTL_TILED_X;
11394                 break;
11395         case I915_FORMAT_MOD_Y_TILED:
11396                 ctl |= PLANE_CTL_TILED_Y;
11397                 break;
11398         case I915_FORMAT_MOD_Yf_TILED:
11399                 ctl |= PLANE_CTL_TILED_YF;
11400                 break;
11401         default:
11402                 MISSING_CASE(fb->modifier[0]);
11403         }
11404
11405         /*
11406          * The stride is either expressed as a multiple of 64 bytes chunks for
11407          * linear buffers or in number of tiles for tiled buffers.
11408          */
11409         if (intel_rotation_90_or_270(rotation)) {
11410                 /* stride = Surface height in tiles */
11411                 tile_height = intel_tile_height(dev_priv, fb->modifier[0], 0);
11412                 stride = DIV_ROUND_UP(fb->height, tile_height);
11413         } else {
11414                 stride = fb->pitches[0] /
11415                         intel_fb_stride_alignment(dev_priv, fb->modifier[0],
11416                                                   fb->pixel_format);
11417         }
11418
11419         /*
11420          * Both PLANE_CTL and PLANE_STRIDE are not updated on vblank but on
11421          * PLANE_SURF updates, the update is then guaranteed to be atomic.
11422          */
11423         I915_WRITE(PLANE_CTL(pipe, 0), ctl);
11424         I915_WRITE(PLANE_STRIDE(pipe, 0), stride);
11425
11426         I915_WRITE(PLANE_SURF(pipe, 0), work->gtt_offset);
11427         POSTING_READ(PLANE_SURF(pipe, 0));
11428 }
11429
11430 static void ilk_do_mmio_flip(struct intel_crtc *intel_crtc,
11431                              struct intel_flip_work *work)
11432 {
11433         struct drm_device *dev = intel_crtc->base.dev;
11434         struct drm_i915_private *dev_priv = to_i915(dev);
11435         struct intel_framebuffer *intel_fb =
11436                 to_intel_framebuffer(intel_crtc->base.primary->fb);
11437         struct drm_i915_gem_object *obj = intel_fb->obj;
11438         i915_reg_t reg = DSPCNTR(intel_crtc->plane);
11439         u32 dspcntr;
11440
11441         dspcntr = I915_READ(reg);
11442
11443         if (i915_gem_object_is_tiled(obj))
11444                 dspcntr |= DISPPLANE_TILED;
11445         else
11446                 dspcntr &= ~DISPPLANE_TILED;
11447
11448         I915_WRITE(reg, dspcntr);
11449
11450         I915_WRITE(DSPSURF(intel_crtc->plane), work->gtt_offset);
11451         POSTING_READ(DSPSURF(intel_crtc->plane));
11452 }
11453
11454 static void intel_mmio_flip_work_func(struct work_struct *w)
11455 {
11456         struct intel_flip_work *work =
11457                 container_of(w, struct intel_flip_work, mmio_work);
11458         struct intel_crtc *crtc = to_intel_crtc(work->crtc);
11459         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
11460         struct intel_framebuffer *intel_fb =
11461                 to_intel_framebuffer(crtc->base.primary->fb);
11462         struct drm_i915_gem_object *obj = intel_fb->obj;
11463         struct reservation_object *resv;
11464
11465         if (work->flip_queued_req)
11466                 WARN_ON(i915_wait_request(work->flip_queued_req,
11467                                           false, NULL,
11468                                           NO_WAITBOOST));
11469
11470         /* For framebuffer backed by dmabuf, wait for fence */
11471         resv = i915_gem_object_get_dmabuf_resv(obj);
11472         if (resv)
11473                 WARN_ON(reservation_object_wait_timeout_rcu(resv, false, false,
11474                                                             MAX_SCHEDULE_TIMEOUT) < 0);
11475
11476         intel_pipe_update_start(crtc);
11477
11478         if (INTEL_GEN(dev_priv) >= 9)
11479                 skl_do_mmio_flip(crtc, work->rotation, work);
11480         else
11481                 /* use_mmio_flip() retricts MMIO flips to ilk+ */
11482                 ilk_do_mmio_flip(crtc, work);
11483
11484         intel_pipe_update_end(crtc, work);
11485 }
11486
11487 static int intel_default_queue_flip(struct drm_device *dev,
11488                                     struct drm_crtc *crtc,
11489                                     struct drm_framebuffer *fb,
11490                                     struct drm_i915_gem_object *obj,
11491                                     struct drm_i915_gem_request *req,
11492                                     uint32_t flags)
11493 {
11494         return -ENODEV;
11495 }
11496
11497 static bool __pageflip_stall_check_cs(struct drm_i915_private *dev_priv,
11498                                       struct intel_crtc *intel_crtc,
11499                                       struct intel_flip_work *work)
11500 {
11501         u32 addr, vblank;
11502
11503         if (!atomic_read(&work->pending))
11504                 return false;
11505
11506         smp_rmb();
11507
11508         vblank = intel_crtc_get_vblank_counter(intel_crtc);
11509         if (work->flip_ready_vblank == 0) {
11510                 if (work->flip_queued_req &&
11511                     !i915_gem_request_completed(work->flip_queued_req))
11512                         return false;
11513
11514                 work->flip_ready_vblank = vblank;
11515         }
11516
11517         if (vblank - work->flip_ready_vblank < 3)
11518                 return false;
11519
11520         /* Potential stall - if we see that the flip has happened,
11521          * assume a missed interrupt. */
11522         if (INTEL_GEN(dev_priv) >= 4)
11523                 addr = I915_HI_DISPBASE(I915_READ(DSPSURF(intel_crtc->plane)));
11524         else
11525                 addr = I915_READ(DSPADDR(intel_crtc->plane));
11526
11527         /* There is a potential issue here with a false positive after a flip
11528          * to the same address. We could address this by checking for a
11529          * non-incrementing frame counter.
11530          */
11531         return addr == work->gtt_offset;
11532 }
11533
11534 void intel_check_page_flip(struct drm_i915_private *dev_priv, int pipe)
11535 {
11536         struct drm_device *dev = &dev_priv->drm;
11537         struct drm_crtc *crtc = dev_priv->pipe_to_crtc_mapping[pipe];
11538         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11539         struct intel_flip_work *work;
11540
11541         WARN_ON(!in_interrupt());
11542
11543         if (crtc == NULL)
11544                 return;
11545
11546         spin_lock(&dev->event_lock);
11547         work = intel_crtc->flip_work;
11548
11549         if (work != NULL && !is_mmio_work(work) &&
11550             __pageflip_stall_check_cs(dev_priv, intel_crtc, work)) {
11551                 WARN_ONCE(1,
11552                           "Kicking stuck page flip: queued at %d, now %d\n",
11553                         work->flip_queued_vblank, intel_crtc_get_vblank_counter(intel_crtc));
11554                 page_flip_completed(intel_crtc);
11555                 work = NULL;
11556         }
11557
11558         if (work != NULL && !is_mmio_work(work) &&
11559             intel_crtc_get_vblank_counter(intel_crtc) - work->flip_queued_vblank > 1)
11560                 intel_queue_rps_boost_for_request(work->flip_queued_req);
11561         spin_unlock(&dev->event_lock);
11562 }
11563
11564 static int intel_crtc_page_flip(struct drm_crtc *crtc,
11565                                 struct drm_framebuffer *fb,
11566                                 struct drm_pending_vblank_event *event,
11567                                 uint32_t page_flip_flags)
11568 {
11569         struct drm_device *dev = crtc->dev;
11570         struct drm_i915_private *dev_priv = to_i915(dev);
11571         struct drm_framebuffer *old_fb = crtc->primary->fb;
11572         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
11573         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11574         struct drm_plane *primary = crtc->primary;
11575         enum pipe pipe = intel_crtc->pipe;
11576         struct intel_flip_work *work;
11577         struct intel_engine_cs *engine;
11578         bool mmio_flip;
11579         struct drm_i915_gem_request *request;
11580         int ret;
11581
11582         /*
11583          * drm_mode_page_flip_ioctl() should already catch this, but double
11584          * check to be safe.  In the future we may enable pageflipping from
11585          * a disabled primary plane.
11586          */
11587         if (WARN_ON(intel_fb_obj(old_fb) == NULL))
11588                 return -EBUSY;
11589
11590         /* Can't change pixel format via MI display flips. */
11591         if (fb->pixel_format != crtc->primary->fb->pixel_format)
11592                 return -EINVAL;
11593
11594         /*
11595          * TILEOFF/LINOFF registers can't be changed via MI display flips.
11596          * Note that pitch changes could also affect these register.
11597          */
11598         if (INTEL_INFO(dev)->gen > 3 &&
11599             (fb->offsets[0] != crtc->primary->fb->offsets[0] ||
11600              fb->pitches[0] != crtc->primary->fb->pitches[0]))
11601                 return -EINVAL;
11602
11603         if (i915_terminally_wedged(&dev_priv->gpu_error))
11604                 goto out_hang;
11605
11606         work = kzalloc(sizeof(*work), GFP_KERNEL);
11607         if (work == NULL)
11608                 return -ENOMEM;
11609
11610         work->event = event;
11611         work->crtc = crtc;
11612         work->old_fb = old_fb;
11613         INIT_WORK(&work->unpin_work, intel_unpin_work_fn);
11614
11615         ret = drm_crtc_vblank_get(crtc);
11616         if (ret)
11617                 goto free_work;
11618
11619         /* We borrow the event spin lock for protecting flip_work */
11620         spin_lock_irq(&dev->event_lock);
11621         if (intel_crtc->flip_work) {
11622                 /* Before declaring the flip queue wedged, check if
11623                  * the hardware completed the operation behind our backs.
11624                  */
11625                 if (pageflip_finished(intel_crtc, intel_crtc->flip_work)) {
11626                         DRM_DEBUG_DRIVER("flip queue: previous flip completed, continuing\n");
11627                         page_flip_completed(intel_crtc);
11628                 } else {
11629                         DRM_DEBUG_DRIVER("flip queue: crtc already busy\n");
11630                         spin_unlock_irq(&dev->event_lock);
11631
11632                         drm_crtc_vblank_put(crtc);
11633                         kfree(work);
11634                         return -EBUSY;
11635                 }
11636         }
11637         intel_crtc->flip_work = work;
11638         spin_unlock_irq(&dev->event_lock);
11639
11640         if (atomic_read(&intel_crtc->unpin_work_count) >= 2)
11641                 flush_workqueue(dev_priv->wq);
11642
11643         /* Reference the objects for the scheduled work. */
11644         drm_framebuffer_reference(work->old_fb);
11645
11646         crtc->primary->fb = fb;
11647         update_state_fb(crtc->primary);
11648
11649         intel_fbc_pre_update(intel_crtc, intel_crtc->config,
11650                              to_intel_plane_state(primary->state));
11651
11652         work->pending_flip_obj = i915_gem_object_get(obj);
11653
11654         ret = i915_mutex_lock_interruptible(dev);
11655         if (ret)
11656                 goto cleanup;
11657
11658         intel_crtc->reset_counter = i915_reset_counter(&dev_priv->gpu_error);
11659         if (__i915_reset_in_progress_or_wedged(intel_crtc->reset_counter)) {
11660                 ret = -EIO;
11661                 goto cleanup;
11662         }
11663
11664         atomic_inc(&intel_crtc->unpin_work_count);
11665
11666         if (INTEL_INFO(dev)->gen >= 5 || IS_G4X(dev))
11667                 work->flip_count = I915_READ(PIPE_FLIPCOUNT_G4X(pipe)) + 1;
11668
11669         if (IS_VALLEYVIEW(dev) || IS_CHERRYVIEW(dev)) {
11670                 engine = &dev_priv->engine[BCS];
11671                 if (i915_gem_object_get_tiling(obj) !=
11672                     i915_gem_object_get_tiling(intel_fb_obj(work->old_fb)))
11673                         /* vlv: DISPLAY_FLIP fails to change tiling */
11674                         engine = NULL;
11675         } else if (IS_IVYBRIDGE(dev) || IS_HASWELL(dev)) {
11676                 engine = &dev_priv->engine[BCS];
11677         } else if (INTEL_INFO(dev)->gen >= 7) {
11678                 engine = i915_gem_active_get_engine(&obj->last_write,
11679                                                     &obj->base.dev->struct_mutex);
11680                 if (engine == NULL || engine->id != RCS)
11681                         engine = &dev_priv->engine[BCS];
11682         } else {
11683                 engine = &dev_priv->engine[RCS];
11684         }
11685
11686         mmio_flip = use_mmio_flip(engine, obj);
11687
11688         ret = intel_pin_and_fence_fb_obj(fb, primary->state->rotation);
11689         if (ret)
11690                 goto cleanup_pending;
11691
11692         work->gtt_offset = intel_plane_obj_offset(to_intel_plane(primary),
11693                                                   obj, 0);
11694         work->gtt_offset += intel_crtc->dspaddr_offset;
11695         work->rotation = crtc->primary->state->rotation;
11696
11697         if (mmio_flip) {
11698                 INIT_WORK(&work->mmio_work, intel_mmio_flip_work_func);
11699
11700                 work->flip_queued_req = i915_gem_active_get(&obj->last_write,
11701                                                             &obj->base.dev->struct_mutex);
11702                 schedule_work(&work->mmio_work);
11703         } else {
11704                 request = i915_gem_request_alloc(engine, engine->last_context);
11705                 if (IS_ERR(request)) {
11706                         ret = PTR_ERR(request);
11707                         goto cleanup_unpin;
11708                 }
11709
11710                 ret = i915_gem_object_sync(obj, request);
11711                 if (ret)
11712                         goto cleanup_request;
11713
11714                 ret = dev_priv->display.queue_flip(dev, crtc, fb, obj, request,
11715                                                    page_flip_flags);
11716                 if (ret)
11717                         goto cleanup_request;
11718
11719                 intel_mark_page_flip_active(intel_crtc, work);
11720
11721                 work->flip_queued_req = i915_gem_request_get(request);
11722                 i915_add_request_no_flush(request);
11723         }
11724
11725         i915_gem_track_fb(intel_fb_obj(old_fb), obj,
11726                           to_intel_plane(primary)->frontbuffer_bit);
11727         mutex_unlock(&dev->struct_mutex);
11728
11729         intel_frontbuffer_flip_prepare(to_i915(dev),
11730                                        to_intel_plane(primary)->frontbuffer_bit);
11731
11732         trace_i915_flip_request(intel_crtc->plane, obj);
11733
11734         return 0;
11735
11736 cleanup_request:
11737         i915_add_request_no_flush(request);
11738 cleanup_unpin:
11739         intel_unpin_fb_obj(fb, crtc->primary->state->rotation);
11740 cleanup_pending:
11741         atomic_dec(&intel_crtc->unpin_work_count);
11742         mutex_unlock(&dev->struct_mutex);
11743 cleanup:
11744         crtc->primary->fb = old_fb;
11745         update_state_fb(crtc->primary);
11746
11747         i915_gem_object_put_unlocked(obj);
11748         drm_framebuffer_unreference(work->old_fb);
11749
11750         spin_lock_irq(&dev->event_lock);
11751         intel_crtc->flip_work = NULL;
11752         spin_unlock_irq(&dev->event_lock);
11753
11754         drm_crtc_vblank_put(crtc);
11755 free_work:
11756         kfree(work);
11757
11758         if (ret == -EIO) {
11759                 struct drm_atomic_state *state;
11760                 struct drm_plane_state *plane_state;
11761
11762 out_hang:
11763                 state = drm_atomic_state_alloc(dev);
11764                 if (!state)
11765                         return -ENOMEM;
11766                 state->acquire_ctx = drm_modeset_legacy_acquire_ctx(crtc);
11767
11768 retry:
11769                 plane_state = drm_atomic_get_plane_state(state, primary);
11770                 ret = PTR_ERR_OR_ZERO(plane_state);
11771                 if (!ret) {
11772                         drm_atomic_set_fb_for_plane(plane_state, fb);
11773
11774                         ret = drm_atomic_set_crtc_for_plane(plane_state, crtc);
11775                         if (!ret)
11776                                 ret = drm_atomic_commit(state);
11777                 }
11778
11779                 if (ret == -EDEADLK) {
11780                         drm_modeset_backoff(state->acquire_ctx);
11781                         drm_atomic_state_clear(state);
11782                         goto retry;
11783                 }
11784
11785                 if (ret)
11786                         drm_atomic_state_free(state);
11787
11788                 if (ret == 0 && event) {
11789                         spin_lock_irq(&dev->event_lock);
11790                         drm_crtc_send_vblank_event(crtc, event);
11791                         spin_unlock_irq(&dev->event_lock);
11792                 }
11793         }
11794         return ret;
11795 }
11796
11797
11798 /**
11799  * intel_wm_need_update - Check whether watermarks need updating
11800  * @plane: drm plane
11801  * @state: new plane state
11802  *
11803  * Check current plane state versus the new one to determine whether
11804  * watermarks need to be recalculated.
11805  *
11806  * Returns true or false.
11807  */
11808 static bool intel_wm_need_update(struct drm_plane *plane,
11809                                  struct drm_plane_state *state)
11810 {
11811         struct intel_plane_state *new = to_intel_plane_state(state);
11812         struct intel_plane_state *cur = to_intel_plane_state(plane->state);
11813
11814         /* Update watermarks on tiling or size changes. */
11815         if (new->base.visible != cur->base.visible)
11816                 return true;
11817
11818         if (!cur->base.fb || !new->base.fb)
11819                 return false;
11820
11821         if (cur->base.fb->modifier[0] != new->base.fb->modifier[0] ||
11822             cur->base.rotation != new->base.rotation ||
11823             drm_rect_width(&new->base.src) != drm_rect_width(&cur->base.src) ||
11824             drm_rect_height(&new->base.src) != drm_rect_height(&cur->base.src) ||
11825             drm_rect_width(&new->base.dst) != drm_rect_width(&cur->base.dst) ||
11826             drm_rect_height(&new->base.dst) != drm_rect_height(&cur->base.dst))
11827                 return true;
11828
11829         return false;
11830 }
11831
11832 static bool needs_scaling(struct intel_plane_state *state)
11833 {
11834         int src_w = drm_rect_width(&state->base.src) >> 16;
11835         int src_h = drm_rect_height(&state->base.src) >> 16;
11836         int dst_w = drm_rect_width(&state->base.dst);
11837         int dst_h = drm_rect_height(&state->base.dst);
11838
11839         return (src_w != dst_w || src_h != dst_h);
11840 }
11841
11842 int intel_plane_atomic_calc_changes(struct drm_crtc_state *crtc_state,
11843                                     struct drm_plane_state *plane_state)
11844 {
11845         struct intel_crtc_state *pipe_config = to_intel_crtc_state(crtc_state);
11846         struct drm_crtc *crtc = crtc_state->crtc;
11847         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11848         struct drm_plane *plane = plane_state->plane;
11849         struct drm_device *dev = crtc->dev;
11850         struct drm_i915_private *dev_priv = to_i915(dev);
11851         struct intel_plane_state *old_plane_state =
11852                 to_intel_plane_state(plane->state);
11853         bool mode_changed = needs_modeset(crtc_state);
11854         bool was_crtc_enabled = crtc->state->active;
11855         bool is_crtc_enabled = crtc_state->active;
11856         bool turn_off, turn_on, visible, was_visible;
11857         struct drm_framebuffer *fb = plane_state->fb;
11858         int ret;
11859
11860         if (INTEL_GEN(dev) >= 9 && plane->type != DRM_PLANE_TYPE_CURSOR) {
11861                 ret = skl_update_scaler_plane(
11862                         to_intel_crtc_state(crtc_state),
11863                         to_intel_plane_state(plane_state));
11864                 if (ret)
11865                         return ret;
11866         }
11867
11868         was_visible = old_plane_state->base.visible;
11869         visible = to_intel_plane_state(plane_state)->base.visible;
11870
11871         if (!was_crtc_enabled && WARN_ON(was_visible))
11872                 was_visible = false;
11873
11874         /*
11875          * Visibility is calculated as if the crtc was on, but
11876          * after scaler setup everything depends on it being off
11877          * when the crtc isn't active.
11878          *
11879          * FIXME this is wrong for watermarks. Watermarks should also
11880          * be computed as if the pipe would be active. Perhaps move
11881          * per-plane wm computation to the .check_plane() hook, and
11882          * only combine the results from all planes in the current place?
11883          */
11884         if (!is_crtc_enabled)
11885                 to_intel_plane_state(plane_state)->base.visible = visible = false;
11886
11887         if (!was_visible && !visible)
11888                 return 0;
11889
11890         if (fb != old_plane_state->base.fb)
11891                 pipe_config->fb_changed = true;
11892
11893         turn_off = was_visible && (!visible || mode_changed);
11894         turn_on = visible && (!was_visible || mode_changed);
11895
11896         DRM_DEBUG_ATOMIC("[CRTC:%d:%s] has [PLANE:%d:%s] with fb %i\n",
11897                          intel_crtc->base.base.id,
11898                          intel_crtc->base.name,
11899                          plane->base.id, plane->name,
11900                          fb ? fb->base.id : -1);
11901
11902         DRM_DEBUG_ATOMIC("[PLANE:%d:%s] visible %i -> %i, off %i, on %i, ms %i\n",
11903                          plane->base.id, plane->name,
11904                          was_visible, visible,
11905                          turn_off, turn_on, mode_changed);
11906
11907         if (turn_on) {
11908                 pipe_config->update_wm_pre = true;
11909
11910                 /* must disable cxsr around plane enable/disable */
11911                 if (plane->type != DRM_PLANE_TYPE_CURSOR)
11912                         pipe_config->disable_cxsr = true;
11913         } else if (turn_off) {
11914                 pipe_config->update_wm_post = true;
11915
11916                 /* must disable cxsr around plane enable/disable */
11917                 if (plane->type != DRM_PLANE_TYPE_CURSOR)
11918                         pipe_config->disable_cxsr = true;
11919         } else if (intel_wm_need_update(plane, plane_state)) {
11920                 /* FIXME bollocks */
11921                 pipe_config->update_wm_pre = true;
11922                 pipe_config->update_wm_post = true;
11923         }
11924
11925         /* Pre-gen9 platforms need two-step watermark updates */
11926         if ((pipe_config->update_wm_pre || pipe_config->update_wm_post) &&
11927             INTEL_INFO(dev)->gen < 9 && dev_priv->display.optimize_watermarks)
11928                 to_intel_crtc_state(crtc_state)->wm.need_postvbl_update = true;
11929
11930         if (visible || was_visible)
11931                 pipe_config->fb_bits |= to_intel_plane(plane)->frontbuffer_bit;
11932
11933         /*
11934          * WaCxSRDisabledForSpriteScaling:ivb
11935          *
11936          * cstate->update_wm was already set above, so this flag will
11937          * take effect when we commit and program watermarks.
11938          */
11939         if (plane->type == DRM_PLANE_TYPE_OVERLAY && IS_IVYBRIDGE(dev) &&
11940             needs_scaling(to_intel_plane_state(plane_state)) &&
11941             !needs_scaling(old_plane_state))
11942                 pipe_config->disable_lp_wm = true;
11943
11944         return 0;
11945 }
11946
11947 static bool encoders_cloneable(const struct intel_encoder *a,
11948                                const struct intel_encoder *b)
11949 {
11950         /* masks could be asymmetric, so check both ways */
11951         return a == b || (a->cloneable & (1 << b->type) &&
11952                           b->cloneable & (1 << a->type));
11953 }
11954
11955 static bool check_single_encoder_cloning(struct drm_atomic_state *state,
11956                                          struct intel_crtc *crtc,
11957                                          struct intel_encoder *encoder)
11958 {
11959         struct intel_encoder *source_encoder;
11960         struct drm_connector *connector;
11961         struct drm_connector_state *connector_state;
11962         int i;
11963
11964         for_each_connector_in_state(state, connector, connector_state, i) {
11965                 if (connector_state->crtc != &crtc->base)
11966                         continue;
11967
11968                 source_encoder =
11969                         to_intel_encoder(connector_state->best_encoder);
11970                 if (!encoders_cloneable(encoder, source_encoder))
11971                         return false;
11972         }
11973
11974         return true;
11975 }
11976
11977 static int intel_crtc_atomic_check(struct drm_crtc *crtc,
11978                                    struct drm_crtc_state *crtc_state)
11979 {
11980         struct drm_device *dev = crtc->dev;
11981         struct drm_i915_private *dev_priv = to_i915(dev);
11982         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11983         struct intel_crtc_state *pipe_config =
11984                 to_intel_crtc_state(crtc_state);
11985         struct drm_atomic_state *state = crtc_state->state;
11986         int ret;
11987         bool mode_changed = needs_modeset(crtc_state);
11988
11989         if (mode_changed && !crtc_state->active)
11990                 pipe_config->update_wm_post = true;
11991
11992         if (mode_changed && crtc_state->enable &&
11993             dev_priv->display.crtc_compute_clock &&
11994             !WARN_ON(pipe_config->shared_dpll)) {
11995                 ret = dev_priv->display.crtc_compute_clock(intel_crtc,
11996                                                            pipe_config);
11997                 if (ret)
11998                         return ret;
11999         }
12000
12001         if (crtc_state->color_mgmt_changed) {
12002                 ret = intel_color_check(crtc, crtc_state);
12003                 if (ret)
12004                         return ret;
12005
12006                 /*
12007                  * Changing color management on Intel hardware is
12008                  * handled as part of planes update.
12009                  */
12010                 crtc_state->planes_changed = true;
12011         }
12012
12013         ret = 0;
12014         if (dev_priv->display.compute_pipe_wm) {
12015                 ret = dev_priv->display.compute_pipe_wm(pipe_config);
12016                 if (ret) {
12017                         DRM_DEBUG_KMS("Target pipe watermarks are invalid\n");
12018                         return ret;
12019                 }
12020         }
12021
12022         if (dev_priv->display.compute_intermediate_wm &&
12023             !to_intel_atomic_state(state)->skip_intermediate_wm) {
12024                 if (WARN_ON(!dev_priv->display.compute_pipe_wm))
12025                         return 0;
12026
12027                 /*
12028                  * Calculate 'intermediate' watermarks that satisfy both the
12029                  * old state and the new state.  We can program these
12030                  * immediately.
12031                  */
12032                 ret = dev_priv->display.compute_intermediate_wm(crtc->dev,
12033                                                                 intel_crtc,
12034                                                                 pipe_config);
12035                 if (ret) {
12036                         DRM_DEBUG_KMS("No valid intermediate pipe watermarks are possible\n");
12037                         return ret;
12038                 }
12039         } else if (dev_priv->display.compute_intermediate_wm) {
12040                 if (HAS_PCH_SPLIT(dev_priv) && INTEL_GEN(dev_priv) < 9)
12041                         pipe_config->wm.ilk.intermediate = pipe_config->wm.ilk.optimal;
12042         }
12043
12044         if (INTEL_INFO(dev)->gen >= 9) {
12045                 if (mode_changed)
12046                         ret = skl_update_scaler_crtc(pipe_config);
12047
12048                 if (!ret)
12049                         ret = intel_atomic_setup_scalers(dev, intel_crtc,
12050                                                          pipe_config);
12051         }
12052
12053         return ret;
12054 }
12055
12056 static const struct drm_crtc_helper_funcs intel_helper_funcs = {
12057         .mode_set_base_atomic = intel_pipe_set_base_atomic,
12058         .atomic_begin = intel_begin_crtc_commit,
12059         .atomic_flush = intel_finish_crtc_commit,
12060         .atomic_check = intel_crtc_atomic_check,
12061 };
12062
12063 static void intel_modeset_update_connector_atomic_state(struct drm_device *dev)
12064 {
12065         struct intel_connector *connector;
12066
12067         for_each_intel_connector(dev, connector) {
12068                 if (connector->base.state->crtc)
12069                         drm_connector_unreference(&connector->base);
12070
12071                 if (connector->base.encoder) {
12072                         connector->base.state->best_encoder =
12073                                 connector->base.encoder;
12074                         connector->base.state->crtc =
12075                                 connector->base.encoder->crtc;
12076
12077                         drm_connector_reference(&connector->base);
12078                 } else {
12079                         connector->base.state->best_encoder = NULL;
12080                         connector->base.state->crtc = NULL;
12081                 }
12082         }
12083 }
12084
12085 static void
12086 connected_sink_compute_bpp(struct intel_connector *connector,
12087                            struct intel_crtc_state *pipe_config)
12088 {
12089         int bpp = pipe_config->pipe_bpp;
12090
12091         DRM_DEBUG_KMS("[CONNECTOR:%d:%s] checking for sink bpp constrains\n",
12092                 connector->base.base.id,
12093                 connector->base.name);
12094
12095         /* Don't use an invalid EDID bpc value */
12096         if (connector->base.display_info.bpc &&
12097             connector->base.display_info.bpc * 3 < bpp) {
12098                 DRM_DEBUG_KMS("clamping display bpp (was %d) to EDID reported max of %d\n",
12099                               bpp, connector->base.display_info.bpc*3);
12100                 pipe_config->pipe_bpp = connector->base.display_info.bpc*3;
12101         }
12102
12103         /* Clamp bpp to 8 on screens without EDID 1.4 */
12104         if (connector->base.display_info.bpc == 0 && bpp > 24) {
12105                 DRM_DEBUG_KMS("clamping display bpp (was %d) to default limit of 24\n",
12106                               bpp);
12107                 pipe_config->pipe_bpp = 24;
12108         }
12109 }
12110
12111 static int
12112 compute_baseline_pipe_bpp(struct intel_crtc *crtc,
12113                           struct intel_crtc_state *pipe_config)
12114 {
12115         struct drm_device *dev = crtc->base.dev;
12116         struct drm_atomic_state *state;
12117         struct drm_connector *connector;
12118         struct drm_connector_state *connector_state;
12119         int bpp, i;
12120
12121         if ((IS_G4X(dev) || IS_VALLEYVIEW(dev) || IS_CHERRYVIEW(dev)))
12122                 bpp = 10*3;
12123         else if (INTEL_INFO(dev)->gen >= 5)
12124                 bpp = 12*3;
12125         else
12126                 bpp = 8*3;
12127
12128
12129         pipe_config->pipe_bpp = bpp;
12130
12131         state = pipe_config->base.state;
12132
12133         /* Clamp display bpp to EDID value */
12134         for_each_connector_in_state(state, connector, connector_state, i) {
12135                 if (connector_state->crtc != &crtc->base)
12136                         continue;
12137
12138                 connected_sink_compute_bpp(to_intel_connector(connector),
12139                                            pipe_config);
12140         }
12141
12142         return bpp;
12143 }
12144
12145 static void intel_dump_crtc_timings(const struct drm_display_mode *mode)
12146 {
12147         DRM_DEBUG_KMS("crtc timings: %d %d %d %d %d %d %d %d %d, "
12148                         "type: 0x%x flags: 0x%x\n",
12149                 mode->crtc_clock,
12150                 mode->crtc_hdisplay, mode->crtc_hsync_start,
12151                 mode->crtc_hsync_end, mode->crtc_htotal,
12152                 mode->crtc_vdisplay, mode->crtc_vsync_start,
12153                 mode->crtc_vsync_end, mode->crtc_vtotal, mode->type, mode->flags);
12154 }
12155
12156 static void intel_dump_pipe_config(struct intel_crtc *crtc,
12157                                    struct intel_crtc_state *pipe_config,
12158                                    const char *context)
12159 {
12160         struct drm_device *dev = crtc->base.dev;
12161         struct drm_plane *plane;
12162         struct intel_plane *intel_plane;
12163         struct intel_plane_state *state;
12164         struct drm_framebuffer *fb;
12165
12166         DRM_DEBUG_KMS("[CRTC:%d:%s]%s config %p for pipe %c\n",
12167                       crtc->base.base.id, crtc->base.name,
12168                       context, pipe_config, pipe_name(crtc->pipe));
12169
12170         DRM_DEBUG_KMS("cpu_transcoder: %s\n", transcoder_name(pipe_config->cpu_transcoder));
12171         DRM_DEBUG_KMS("pipe bpp: %i, dithering: %i\n",
12172                       pipe_config->pipe_bpp, pipe_config->dither);
12173         DRM_DEBUG_KMS("fdi/pch: %i, lanes: %i, gmch_m: %u, gmch_n: %u, link_m: %u, link_n: %u, tu: %u\n",
12174                       pipe_config->has_pch_encoder,
12175                       pipe_config->fdi_lanes,
12176                       pipe_config->fdi_m_n.gmch_m, pipe_config->fdi_m_n.gmch_n,
12177                       pipe_config->fdi_m_n.link_m, pipe_config->fdi_m_n.link_n,
12178                       pipe_config->fdi_m_n.tu);
12179         DRM_DEBUG_KMS("dp: %i, lanes: %i, gmch_m: %u, gmch_n: %u, link_m: %u, link_n: %u, tu: %u\n",
12180                       intel_crtc_has_dp_encoder(pipe_config),
12181                       pipe_config->lane_count,
12182                       pipe_config->dp_m_n.gmch_m, pipe_config->dp_m_n.gmch_n,
12183                       pipe_config->dp_m_n.link_m, pipe_config->dp_m_n.link_n,
12184                       pipe_config->dp_m_n.tu);
12185
12186         DRM_DEBUG_KMS("dp: %i, lanes: %i, gmch_m2: %u, gmch_n2: %u, link_m2: %u, link_n2: %u, tu2: %u\n",
12187                       intel_crtc_has_dp_encoder(pipe_config),
12188                       pipe_config->lane_count,
12189                       pipe_config->dp_m2_n2.gmch_m,
12190                       pipe_config->dp_m2_n2.gmch_n,
12191                       pipe_config->dp_m2_n2.link_m,
12192                       pipe_config->dp_m2_n2.link_n,
12193                       pipe_config->dp_m2_n2.tu);
12194
12195         DRM_DEBUG_KMS("audio: %i, infoframes: %i\n",
12196                       pipe_config->has_audio,
12197                       pipe_config->has_infoframe);
12198
12199         DRM_DEBUG_KMS("requested mode:\n");
12200         drm_mode_debug_printmodeline(&pipe_config->base.mode);
12201         DRM_DEBUG_KMS("adjusted mode:\n");
12202         drm_mode_debug_printmodeline(&pipe_config->base.adjusted_mode);
12203         intel_dump_crtc_timings(&pipe_config->base.adjusted_mode);
12204         DRM_DEBUG_KMS("port clock: %d\n", pipe_config->port_clock);
12205         DRM_DEBUG_KMS("pipe src size: %dx%d\n",
12206                       pipe_config->pipe_src_w, pipe_config->pipe_src_h);
12207         DRM_DEBUG_KMS("num_scalers: %d, scaler_users: 0x%x, scaler_id: %d\n",
12208                       crtc->num_scalers,
12209                       pipe_config->scaler_state.scaler_users,
12210                       pipe_config->scaler_state.scaler_id);
12211         DRM_DEBUG_KMS("gmch pfit: control: 0x%08x, ratios: 0x%08x, lvds border: 0x%08x\n",
12212                       pipe_config->gmch_pfit.control,
12213                       pipe_config->gmch_pfit.pgm_ratios,
12214                       pipe_config->gmch_pfit.lvds_border_bits);
12215         DRM_DEBUG_KMS("pch pfit: pos: 0x%08x, size: 0x%08x, %s\n",
12216                       pipe_config->pch_pfit.pos,
12217                       pipe_config->pch_pfit.size,
12218                       pipe_config->pch_pfit.enabled ? "enabled" : "disabled");
12219         DRM_DEBUG_KMS("ips: %i\n", pipe_config->ips_enabled);
12220         DRM_DEBUG_KMS("double wide: %i\n", pipe_config->double_wide);
12221
12222         if (IS_BROXTON(dev)) {
12223                 DRM_DEBUG_KMS("ddi_pll_sel: %u; dpll_hw_state: ebb0: 0x%x, ebb4: 0x%x,"
12224                               "pll0: 0x%x, pll1: 0x%x, pll2: 0x%x, pll3: 0x%x, "
12225                               "pll6: 0x%x, pll8: 0x%x, pll9: 0x%x, pll10: 0x%x, pcsdw12: 0x%x\n",
12226                               pipe_config->ddi_pll_sel,
12227                               pipe_config->dpll_hw_state.ebb0,
12228                               pipe_config->dpll_hw_state.ebb4,
12229                               pipe_config->dpll_hw_state.pll0,
12230                               pipe_config->dpll_hw_state.pll1,
12231                               pipe_config->dpll_hw_state.pll2,
12232                               pipe_config->dpll_hw_state.pll3,
12233                               pipe_config->dpll_hw_state.pll6,
12234                               pipe_config->dpll_hw_state.pll8,
12235                               pipe_config->dpll_hw_state.pll9,
12236                               pipe_config->dpll_hw_state.pll10,
12237                               pipe_config->dpll_hw_state.pcsdw12);
12238         } else if (IS_SKYLAKE(dev) || IS_KABYLAKE(dev)) {
12239                 DRM_DEBUG_KMS("ddi_pll_sel: %u; dpll_hw_state: "
12240                               "ctrl1: 0x%x, cfgcr1: 0x%x, cfgcr2: 0x%x\n",
12241                               pipe_config->ddi_pll_sel,
12242                               pipe_config->dpll_hw_state.ctrl1,
12243                               pipe_config->dpll_hw_state.cfgcr1,
12244                               pipe_config->dpll_hw_state.cfgcr2);
12245         } else if (HAS_DDI(dev)) {
12246                 DRM_DEBUG_KMS("ddi_pll_sel: 0x%x; dpll_hw_state: wrpll: 0x%x spll: 0x%x\n",
12247                               pipe_config->ddi_pll_sel,
12248                               pipe_config->dpll_hw_state.wrpll,
12249                               pipe_config->dpll_hw_state.spll);
12250         } else {
12251                 DRM_DEBUG_KMS("dpll_hw_state: dpll: 0x%x, dpll_md: 0x%x, "
12252                               "fp0: 0x%x, fp1: 0x%x\n",
12253                               pipe_config->dpll_hw_state.dpll,
12254                               pipe_config->dpll_hw_state.dpll_md,
12255                               pipe_config->dpll_hw_state.fp0,
12256                               pipe_config->dpll_hw_state.fp1);
12257         }
12258
12259         DRM_DEBUG_KMS("planes on this crtc\n");
12260         list_for_each_entry(plane, &dev->mode_config.plane_list, head) {
12261                 intel_plane = to_intel_plane(plane);
12262                 if (intel_plane->pipe != crtc->pipe)
12263                         continue;
12264
12265                 state = to_intel_plane_state(plane->state);
12266                 fb = state->base.fb;
12267                 if (!fb) {
12268                         DRM_DEBUG_KMS("[PLANE:%d:%s] disabled, scaler_id = %d\n",
12269                                       plane->base.id, plane->name, state->scaler_id);
12270                         continue;
12271                 }
12272
12273                 DRM_DEBUG_KMS("[PLANE:%d:%s] enabled",
12274                               plane->base.id, plane->name);
12275                 DRM_DEBUG_KMS("\tFB:%d, fb = %ux%u format = %s",
12276                               fb->base.id, fb->width, fb->height,
12277                               drm_get_format_name(fb->pixel_format));
12278                 DRM_DEBUG_KMS("\tscaler:%d src %dx%d+%d+%d dst %dx%d+%d+%d\n",
12279                               state->scaler_id,
12280                               state->base.src.x1 >> 16,
12281                               state->base.src.y1 >> 16,
12282                               drm_rect_width(&state->base.src) >> 16,
12283                               drm_rect_height(&state->base.src) >> 16,
12284                               state->base.dst.x1, state->base.dst.y1,
12285                               drm_rect_width(&state->base.dst),
12286                               drm_rect_height(&state->base.dst));
12287         }
12288 }
12289
12290 static bool check_digital_port_conflicts(struct drm_atomic_state *state)
12291 {
12292         struct drm_device *dev = state->dev;
12293         struct drm_connector *connector;
12294         unsigned int used_ports = 0;
12295         unsigned int used_mst_ports = 0;
12296
12297         /*
12298          * Walk the connector list instead of the encoder
12299          * list to detect the problem on ddi platforms
12300          * where there's just one encoder per digital port.
12301          */
12302         drm_for_each_connector(connector, dev) {
12303                 struct drm_connector_state *connector_state;
12304                 struct intel_encoder *encoder;
12305
12306                 connector_state = drm_atomic_get_existing_connector_state(state, connector);
12307                 if (!connector_state)
12308                         connector_state = connector->state;
12309
12310                 if (!connector_state->best_encoder)
12311                         continue;
12312
12313                 encoder = to_intel_encoder(connector_state->best_encoder);
12314
12315                 WARN_ON(!connector_state->crtc);
12316
12317                 switch (encoder->type) {
12318                         unsigned int port_mask;
12319                 case INTEL_OUTPUT_UNKNOWN:
12320                         if (WARN_ON(!HAS_DDI(dev)))
12321                                 break;
12322                 case INTEL_OUTPUT_DP:
12323                 case INTEL_OUTPUT_HDMI:
12324                 case INTEL_OUTPUT_EDP:
12325                         port_mask = 1 << enc_to_dig_port(&encoder->base)->port;
12326
12327                         /* the same port mustn't appear more than once */
12328                         if (used_ports & port_mask)
12329                                 return false;
12330
12331                         used_ports |= port_mask;
12332                         break;
12333                 case INTEL_OUTPUT_DP_MST:
12334                         used_mst_ports |=
12335                                 1 << enc_to_mst(&encoder->base)->primary->port;
12336                         break;
12337                 default:
12338                         break;
12339                 }
12340         }
12341
12342         /* can't mix MST and SST/HDMI on the same port */
12343         if (used_ports & used_mst_ports)
12344                 return false;
12345
12346         return true;
12347 }
12348
12349 static void
12350 clear_intel_crtc_state(struct intel_crtc_state *crtc_state)
12351 {
12352         struct drm_crtc_state tmp_state;
12353         struct intel_crtc_scaler_state scaler_state;
12354         struct intel_dpll_hw_state dpll_hw_state;
12355         struct intel_shared_dpll *shared_dpll;
12356         uint32_t ddi_pll_sel;
12357         bool force_thru;
12358
12359         /* FIXME: before the switch to atomic started, a new pipe_config was
12360          * kzalloc'd. Code that depends on any field being zero should be
12361          * fixed, so that the crtc_state can be safely duplicated. For now,
12362          * only fields that are know to not cause problems are preserved. */
12363
12364         tmp_state = crtc_state->base;
12365         scaler_state = crtc_state->scaler_state;
12366         shared_dpll = crtc_state->shared_dpll;
12367         dpll_hw_state = crtc_state->dpll_hw_state;
12368         ddi_pll_sel = crtc_state->ddi_pll_sel;
12369         force_thru = crtc_state->pch_pfit.force_thru;
12370
12371         memset(crtc_state, 0, sizeof *crtc_state);
12372
12373         crtc_state->base = tmp_state;
12374         crtc_state->scaler_state = scaler_state;
12375         crtc_state->shared_dpll = shared_dpll;
12376         crtc_state->dpll_hw_state = dpll_hw_state;
12377         crtc_state->ddi_pll_sel = ddi_pll_sel;
12378         crtc_state->pch_pfit.force_thru = force_thru;
12379 }
12380
12381 static int
12382 intel_modeset_pipe_config(struct drm_crtc *crtc,
12383                           struct intel_crtc_state *pipe_config)
12384 {
12385         struct drm_atomic_state *state = pipe_config->base.state;
12386         struct intel_encoder *encoder;
12387         struct drm_connector *connector;
12388         struct drm_connector_state *connector_state;
12389         int base_bpp, ret = -EINVAL;
12390         int i;
12391         bool retry = true;
12392
12393         clear_intel_crtc_state(pipe_config);
12394
12395         pipe_config->cpu_transcoder =
12396                 (enum transcoder) to_intel_crtc(crtc)->pipe;
12397
12398         /*
12399          * Sanitize sync polarity flags based on requested ones. If neither
12400          * positive or negative polarity is requested, treat this as meaning
12401          * negative polarity.
12402          */
12403         if (!(pipe_config->base.adjusted_mode.flags &
12404               (DRM_MODE_FLAG_PHSYNC | DRM_MODE_FLAG_NHSYNC)))
12405                 pipe_config->base.adjusted_mode.flags |= DRM_MODE_FLAG_NHSYNC;
12406
12407         if (!(pipe_config->base.adjusted_mode.flags &
12408               (DRM_MODE_FLAG_PVSYNC | DRM_MODE_FLAG_NVSYNC)))
12409                 pipe_config->base.adjusted_mode.flags |= DRM_MODE_FLAG_NVSYNC;
12410
12411         base_bpp = compute_baseline_pipe_bpp(to_intel_crtc(crtc),
12412                                              pipe_config);
12413         if (base_bpp < 0)
12414                 goto fail;
12415
12416         /*
12417          * Determine the real pipe dimensions. Note that stereo modes can
12418          * increase the actual pipe size due to the frame doubling and
12419          * insertion of additional space for blanks between the frame. This
12420          * is stored in the crtc timings. We use the requested mode to do this
12421          * computation to clearly distinguish it from the adjusted mode, which
12422          * can be changed by the connectors in the below retry loop.
12423          */
12424         drm_crtc_get_hv_timing(&pipe_config->base.mode,
12425                                &pipe_config->pipe_src_w,
12426                                &pipe_config->pipe_src_h);
12427
12428         for_each_connector_in_state(state, connector, connector_state, i) {
12429                 if (connector_state->crtc != crtc)
12430                         continue;
12431
12432                 encoder = to_intel_encoder(connector_state->best_encoder);
12433
12434                 if (!check_single_encoder_cloning(state, to_intel_crtc(crtc), encoder)) {
12435                         DRM_DEBUG_KMS("rejecting invalid cloning configuration\n");
12436                         goto fail;
12437                 }
12438
12439                 /*
12440                  * Determine output_types before calling the .compute_config()
12441                  * hooks so that the hooks can use this information safely.
12442                  */
12443                 pipe_config->output_types |= 1 << encoder->type;
12444         }
12445
12446 encoder_retry:
12447         /* Ensure the port clock defaults are reset when retrying. */
12448         pipe_config->port_clock = 0;
12449         pipe_config->pixel_multiplier = 1;
12450
12451         /* Fill in default crtc timings, allow encoders to overwrite them. */
12452         drm_mode_set_crtcinfo(&pipe_config->base.adjusted_mode,
12453                               CRTC_STEREO_DOUBLE);
12454
12455         /* Pass our mode to the connectors and the CRTC to give them a chance to
12456          * adjust it according to limitations or connector properties, and also
12457          * a chance to reject the mode entirely.
12458          */
12459         for_each_connector_in_state(state, connector, connector_state, i) {
12460                 if (connector_state->crtc != crtc)
12461                         continue;
12462
12463                 encoder = to_intel_encoder(connector_state->best_encoder);
12464
12465                 if (!(encoder->compute_config(encoder, pipe_config))) {
12466                         DRM_DEBUG_KMS("Encoder config failure\n");
12467                         goto fail;
12468                 }
12469         }
12470
12471         /* Set default port clock if not overwritten by the encoder. Needs to be
12472          * done afterwards in case the encoder adjusts the mode. */
12473         if (!pipe_config->port_clock)
12474                 pipe_config->port_clock = pipe_config->base.adjusted_mode.crtc_clock
12475                         * pipe_config->pixel_multiplier;
12476
12477         ret = intel_crtc_compute_config(to_intel_crtc(crtc), pipe_config);
12478         if (ret < 0) {
12479                 DRM_DEBUG_KMS("CRTC fixup failed\n");
12480                 goto fail;
12481         }
12482
12483         if (ret == RETRY) {
12484                 if (WARN(!retry, "loop in pipe configuration computation\n")) {
12485                         ret = -EINVAL;
12486                         goto fail;
12487                 }
12488
12489                 DRM_DEBUG_KMS("CRTC bw constrained, retrying\n");
12490                 retry = false;
12491                 goto encoder_retry;
12492         }
12493
12494         /* Dithering seems to not pass-through bits correctly when it should, so
12495          * only enable it on 6bpc panels. */
12496         pipe_config->dither = pipe_config->pipe_bpp == 6*3;
12497         DRM_DEBUG_KMS("hw max bpp: %i, pipe bpp: %i, dithering: %i\n",
12498                       base_bpp, pipe_config->pipe_bpp, pipe_config->dither);
12499
12500 fail:
12501         return ret;
12502 }
12503
12504 static void
12505 intel_modeset_update_crtc_state(struct drm_atomic_state *state)
12506 {
12507         struct drm_crtc *crtc;
12508         struct drm_crtc_state *crtc_state;
12509         int i;
12510
12511         /* Double check state. */
12512         for_each_crtc_in_state(state, crtc, crtc_state, i) {
12513                 to_intel_crtc(crtc)->config = to_intel_crtc_state(crtc->state);
12514
12515                 /* Update hwmode for vblank functions */
12516                 if (crtc->state->active)
12517                         crtc->hwmode = crtc->state->adjusted_mode;
12518                 else
12519                         crtc->hwmode.crtc_clock = 0;
12520
12521                 /*
12522                  * Update legacy state to satisfy fbc code. This can
12523                  * be removed when fbc uses the atomic state.
12524                  */
12525                 if (drm_atomic_get_existing_plane_state(state, crtc->primary)) {
12526                         struct drm_plane_state *plane_state = crtc->primary->state;
12527
12528                         crtc->primary->fb = plane_state->fb;
12529                         crtc->x = plane_state->src_x >> 16;
12530                         crtc->y = plane_state->src_y >> 16;
12531                 }
12532         }
12533 }
12534
12535 static bool intel_fuzzy_clock_check(int clock1, int clock2)
12536 {
12537         int diff;
12538
12539         if (clock1 == clock2)
12540                 return true;
12541
12542         if (!clock1 || !clock2)
12543                 return false;
12544
12545         diff = abs(clock1 - clock2);
12546
12547         if (((((diff + clock1 + clock2) * 100)) / (clock1 + clock2)) < 105)
12548                 return true;
12549
12550         return false;
12551 }
12552
12553 #define for_each_intel_crtc_masked(dev, mask, intel_crtc) \
12554         list_for_each_entry((intel_crtc), \
12555                             &(dev)->mode_config.crtc_list, \
12556                             base.head) \
12557                 for_each_if (mask & (1 <<(intel_crtc)->pipe))
12558
12559 static bool
12560 intel_compare_m_n(unsigned int m, unsigned int n,
12561                   unsigned int m2, unsigned int n2,
12562                   bool exact)
12563 {
12564         if (m == m2 && n == n2)
12565                 return true;
12566
12567         if (exact || !m || !n || !m2 || !n2)
12568                 return false;
12569
12570         BUILD_BUG_ON(DATA_LINK_M_N_MASK > INT_MAX);
12571
12572         if (n > n2) {
12573                 while (n > n2) {
12574                         m2 <<= 1;
12575                         n2 <<= 1;
12576                 }
12577         } else if (n < n2) {
12578                 while (n < n2) {
12579                         m <<= 1;
12580                         n <<= 1;
12581                 }
12582         }
12583
12584         if (n != n2)
12585                 return false;
12586
12587         return intel_fuzzy_clock_check(m, m2);
12588 }
12589
12590 static bool
12591 intel_compare_link_m_n(const struct intel_link_m_n *m_n,
12592                        struct intel_link_m_n *m2_n2,
12593                        bool adjust)
12594 {
12595         if (m_n->tu == m2_n2->tu &&
12596             intel_compare_m_n(m_n->gmch_m, m_n->gmch_n,
12597                               m2_n2->gmch_m, m2_n2->gmch_n, !adjust) &&
12598             intel_compare_m_n(m_n->link_m, m_n->link_n,
12599                               m2_n2->link_m, m2_n2->link_n, !adjust)) {
12600                 if (adjust)
12601                         *m2_n2 = *m_n;
12602
12603                 return true;
12604         }
12605
12606         return false;
12607 }
12608
12609 static bool
12610 intel_pipe_config_compare(struct drm_device *dev,
12611                           struct intel_crtc_state *current_config,
12612                           struct intel_crtc_state *pipe_config,
12613                           bool adjust)
12614 {
12615         bool ret = true;
12616
12617 #define INTEL_ERR_OR_DBG_KMS(fmt, ...) \
12618         do { \
12619                 if (!adjust) \
12620                         DRM_ERROR(fmt, ##__VA_ARGS__); \
12621                 else \
12622                         DRM_DEBUG_KMS(fmt, ##__VA_ARGS__); \
12623         } while (0)
12624
12625 #define PIPE_CONF_CHECK_X(name) \
12626         if (current_config->name != pipe_config->name) { \
12627                 INTEL_ERR_OR_DBG_KMS("mismatch in " #name " " \
12628                           "(expected 0x%08x, found 0x%08x)\n", \
12629                           current_config->name, \
12630                           pipe_config->name); \
12631                 ret = false; \
12632         }
12633
12634 #define PIPE_CONF_CHECK_I(name) \
12635         if (current_config->name != pipe_config->name) { \
12636                 INTEL_ERR_OR_DBG_KMS("mismatch in " #name " " \
12637                           "(expected %i, found %i)\n", \
12638                           current_config->name, \
12639                           pipe_config->name); \
12640                 ret = false; \
12641         }
12642
12643 #define PIPE_CONF_CHECK_P(name) \
12644         if (current_config->name != pipe_config->name) { \
12645                 INTEL_ERR_OR_DBG_KMS("mismatch in " #name " " \
12646                           "(expected %p, found %p)\n", \
12647                           current_config->name, \
12648                           pipe_config->name); \
12649                 ret = false; \
12650         }
12651
12652 #define PIPE_CONF_CHECK_M_N(name) \
12653         if (!intel_compare_link_m_n(&current_config->name, \
12654                                     &pipe_config->name,\
12655                                     adjust)) { \
12656                 INTEL_ERR_OR_DBG_KMS("mismatch in " #name " " \
12657                           "(expected tu %i gmch %i/%i link %i/%i, " \
12658                           "found tu %i, gmch %i/%i link %i/%i)\n", \
12659                           current_config->name.tu, \
12660                           current_config->name.gmch_m, \
12661                           current_config->name.gmch_n, \
12662                           current_config->name.link_m, \
12663                           current_config->name.link_n, \
12664                           pipe_config->name.tu, \
12665                           pipe_config->name.gmch_m, \
12666                           pipe_config->name.gmch_n, \
12667                           pipe_config->name.link_m, \
12668                           pipe_config->name.link_n); \
12669                 ret = false; \
12670         }
12671
12672 /* This is required for BDW+ where there is only one set of registers for
12673  * switching between high and low RR.
12674  * This macro can be used whenever a comparison has to be made between one
12675  * hw state and multiple sw state variables.
12676  */
12677 #define PIPE_CONF_CHECK_M_N_ALT(name, alt_name) \
12678         if (!intel_compare_link_m_n(&current_config->name, \
12679                                     &pipe_config->name, adjust) && \
12680             !intel_compare_link_m_n(&current_config->alt_name, \
12681                                     &pipe_config->name, adjust)) { \
12682                 INTEL_ERR_OR_DBG_KMS("mismatch in " #name " " \
12683                           "(expected tu %i gmch %i/%i link %i/%i, " \
12684                           "or tu %i gmch %i/%i link %i/%i, " \
12685                           "found tu %i, gmch %i/%i link %i/%i)\n", \
12686                           current_config->name.tu, \
12687                           current_config->name.gmch_m, \
12688                           current_config->name.gmch_n, \
12689                           current_config->name.link_m, \
12690                           current_config->name.link_n, \
12691                           current_config->alt_name.tu, \
12692                           current_config->alt_name.gmch_m, \
12693                           current_config->alt_name.gmch_n, \
12694                           current_config->alt_name.link_m, \
12695                           current_config->alt_name.link_n, \
12696                           pipe_config->name.tu, \
12697                           pipe_config->name.gmch_m, \
12698                           pipe_config->name.gmch_n, \
12699                           pipe_config->name.link_m, \
12700                           pipe_config->name.link_n); \
12701                 ret = false; \
12702         }
12703
12704 #define PIPE_CONF_CHECK_FLAGS(name, mask)       \
12705         if ((current_config->name ^ pipe_config->name) & (mask)) { \
12706                 INTEL_ERR_OR_DBG_KMS("mismatch in " #name "(" #mask ") " \
12707                           "(expected %i, found %i)\n", \
12708                           current_config->name & (mask), \
12709                           pipe_config->name & (mask)); \
12710                 ret = false; \
12711         }
12712
12713 #define PIPE_CONF_CHECK_CLOCK_FUZZY(name) \
12714         if (!intel_fuzzy_clock_check(current_config->name, pipe_config->name)) { \
12715                 INTEL_ERR_OR_DBG_KMS("mismatch in " #name " " \
12716                           "(expected %i, found %i)\n", \
12717                           current_config->name, \
12718                           pipe_config->name); \
12719                 ret = false; \
12720         }
12721
12722 #define PIPE_CONF_QUIRK(quirk)  \
12723         ((current_config->quirks | pipe_config->quirks) & (quirk))
12724
12725         PIPE_CONF_CHECK_I(cpu_transcoder);
12726
12727         PIPE_CONF_CHECK_I(has_pch_encoder);
12728         PIPE_CONF_CHECK_I(fdi_lanes);
12729         PIPE_CONF_CHECK_M_N(fdi_m_n);
12730
12731         PIPE_CONF_CHECK_I(lane_count);
12732         PIPE_CONF_CHECK_X(lane_lat_optim_mask);
12733
12734         if (INTEL_INFO(dev)->gen < 8) {
12735                 PIPE_CONF_CHECK_M_N(dp_m_n);
12736
12737                 if (current_config->has_drrs)
12738                         PIPE_CONF_CHECK_M_N(dp_m2_n2);
12739         } else
12740                 PIPE_CONF_CHECK_M_N_ALT(dp_m_n, dp_m2_n2);
12741
12742         PIPE_CONF_CHECK_X(output_types);
12743
12744         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hdisplay);
12745         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_htotal);
12746         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hblank_start);
12747         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hblank_end);
12748         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hsync_start);
12749         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hsync_end);
12750
12751         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vdisplay);
12752         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vtotal);
12753         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vblank_start);
12754         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vblank_end);
12755         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vsync_start);
12756         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vsync_end);
12757
12758         PIPE_CONF_CHECK_I(pixel_multiplier);
12759         PIPE_CONF_CHECK_I(has_hdmi_sink);
12760         if ((INTEL_INFO(dev)->gen < 8 && !IS_HASWELL(dev)) ||
12761             IS_VALLEYVIEW(dev) || IS_CHERRYVIEW(dev))
12762                 PIPE_CONF_CHECK_I(limited_color_range);
12763         PIPE_CONF_CHECK_I(has_infoframe);
12764
12765         PIPE_CONF_CHECK_I(has_audio);
12766
12767         PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
12768                               DRM_MODE_FLAG_INTERLACE);
12769
12770         if (!PIPE_CONF_QUIRK(PIPE_CONFIG_QUIRK_MODE_SYNC_FLAGS)) {
12771                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
12772                                       DRM_MODE_FLAG_PHSYNC);
12773                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
12774                                       DRM_MODE_FLAG_NHSYNC);
12775                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
12776                                       DRM_MODE_FLAG_PVSYNC);
12777                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
12778                                       DRM_MODE_FLAG_NVSYNC);
12779         }
12780
12781         PIPE_CONF_CHECK_X(gmch_pfit.control);
12782         /* pfit ratios are autocomputed by the hw on gen4+ */
12783         if (INTEL_INFO(dev)->gen < 4)
12784                 PIPE_CONF_CHECK_X(gmch_pfit.pgm_ratios);
12785         PIPE_CONF_CHECK_X(gmch_pfit.lvds_border_bits);
12786
12787         if (!adjust) {
12788                 PIPE_CONF_CHECK_I(pipe_src_w);
12789                 PIPE_CONF_CHECK_I(pipe_src_h);
12790
12791                 PIPE_CONF_CHECK_I(pch_pfit.enabled);
12792                 if (current_config->pch_pfit.enabled) {
12793                         PIPE_CONF_CHECK_X(pch_pfit.pos);
12794                         PIPE_CONF_CHECK_X(pch_pfit.size);
12795                 }
12796
12797                 PIPE_CONF_CHECK_I(scaler_state.scaler_id);
12798         }
12799
12800         /* BDW+ don't expose a synchronous way to read the state */
12801         if (IS_HASWELL(dev))
12802                 PIPE_CONF_CHECK_I(ips_enabled);
12803
12804         PIPE_CONF_CHECK_I(double_wide);
12805
12806         PIPE_CONF_CHECK_X(ddi_pll_sel);
12807
12808         PIPE_CONF_CHECK_P(shared_dpll);
12809         PIPE_CONF_CHECK_X(dpll_hw_state.dpll);
12810         PIPE_CONF_CHECK_X(dpll_hw_state.dpll_md);
12811         PIPE_CONF_CHECK_X(dpll_hw_state.fp0);
12812         PIPE_CONF_CHECK_X(dpll_hw_state.fp1);
12813         PIPE_CONF_CHECK_X(dpll_hw_state.wrpll);
12814         PIPE_CONF_CHECK_X(dpll_hw_state.spll);
12815         PIPE_CONF_CHECK_X(dpll_hw_state.ctrl1);
12816         PIPE_CONF_CHECK_X(dpll_hw_state.cfgcr1);
12817         PIPE_CONF_CHECK_X(dpll_hw_state.cfgcr2);
12818
12819         PIPE_CONF_CHECK_X(dsi_pll.ctrl);
12820         PIPE_CONF_CHECK_X(dsi_pll.div);
12821
12822         if (IS_G4X(dev) || INTEL_INFO(dev)->gen >= 5)
12823                 PIPE_CONF_CHECK_I(pipe_bpp);
12824
12825         PIPE_CONF_CHECK_CLOCK_FUZZY(base.adjusted_mode.crtc_clock);
12826         PIPE_CONF_CHECK_CLOCK_FUZZY(port_clock);
12827
12828 #undef PIPE_CONF_CHECK_X
12829 #undef PIPE_CONF_CHECK_I
12830 #undef PIPE_CONF_CHECK_P
12831 #undef PIPE_CONF_CHECK_FLAGS
12832 #undef PIPE_CONF_CHECK_CLOCK_FUZZY
12833 #undef PIPE_CONF_QUIRK
12834 #undef INTEL_ERR_OR_DBG_KMS
12835
12836         return ret;
12837 }
12838
12839 static void intel_pipe_config_sanity_check(struct drm_i915_private *dev_priv,
12840                                            const struct intel_crtc_state *pipe_config)
12841 {
12842         if (pipe_config->has_pch_encoder) {
12843                 int fdi_dotclock = intel_dotclock_calculate(intel_fdi_link_freq(dev_priv, pipe_config),
12844                                                             &pipe_config->fdi_m_n);
12845                 int dotclock = pipe_config->base.adjusted_mode.crtc_clock;
12846
12847                 /*
12848                  * FDI already provided one idea for the dotclock.
12849                  * Yell if the encoder disagrees.
12850                  */
12851                 WARN(!intel_fuzzy_clock_check(fdi_dotclock, dotclock),
12852                      "FDI dotclock and encoder dotclock mismatch, fdi: %i, encoder: %i\n",
12853                      fdi_dotclock, dotclock);
12854         }
12855 }
12856
12857 static void verify_wm_state(struct drm_crtc *crtc,
12858                             struct drm_crtc_state *new_state)
12859 {
12860         struct drm_device *dev = crtc->dev;
12861         struct drm_i915_private *dev_priv = to_i915(dev);
12862         struct skl_ddb_allocation hw_ddb, *sw_ddb;
12863         struct skl_ddb_entry *hw_entry, *sw_entry;
12864         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
12865         const enum pipe pipe = intel_crtc->pipe;
12866         int plane;
12867
12868         if (INTEL_INFO(dev)->gen < 9 || !new_state->active)
12869                 return;
12870
12871         skl_ddb_get_hw_state(dev_priv, &hw_ddb);
12872         sw_ddb = &dev_priv->wm.skl_hw.ddb;
12873
12874         /* planes */
12875         for_each_plane(dev_priv, pipe, plane) {
12876                 hw_entry = &hw_ddb.plane[pipe][plane];
12877                 sw_entry = &sw_ddb->plane[pipe][plane];
12878
12879                 if (skl_ddb_entry_equal(hw_entry, sw_entry))
12880                         continue;
12881
12882                 DRM_ERROR("mismatch in DDB state pipe %c plane %d "
12883                           "(expected (%u,%u), found (%u,%u))\n",
12884                           pipe_name(pipe), plane + 1,
12885                           sw_entry->start, sw_entry->end,
12886                           hw_entry->start, hw_entry->end);
12887         }
12888
12889         /* cursor */
12890         hw_entry = &hw_ddb.plane[pipe][PLANE_CURSOR];
12891         sw_entry = &sw_ddb->plane[pipe][PLANE_CURSOR];
12892
12893         if (!skl_ddb_entry_equal(hw_entry, sw_entry)) {
12894                 DRM_ERROR("mismatch in DDB state pipe %c cursor "
12895                           "(expected (%u,%u), found (%u,%u))\n",
12896                           pipe_name(pipe),
12897                           sw_entry->start, sw_entry->end,
12898                           hw_entry->start, hw_entry->end);
12899         }
12900 }
12901
12902 static void
12903 verify_connector_state(struct drm_device *dev, struct drm_crtc *crtc)
12904 {
12905         struct drm_connector *connector;
12906
12907         drm_for_each_connector(connector, dev) {
12908                 struct drm_encoder *encoder = connector->encoder;
12909                 struct drm_connector_state *state = connector->state;
12910
12911                 if (state->crtc != crtc)
12912                         continue;
12913
12914                 intel_connector_verify_state(to_intel_connector(connector));
12915
12916                 I915_STATE_WARN(state->best_encoder != encoder,
12917                      "connector's atomic encoder doesn't match legacy encoder\n");
12918         }
12919 }
12920
12921 static void
12922 verify_encoder_state(struct drm_device *dev)
12923 {
12924         struct intel_encoder *encoder;
12925         struct intel_connector *connector;
12926
12927         for_each_intel_encoder(dev, encoder) {
12928                 bool enabled = false;
12929                 enum pipe pipe;
12930
12931                 DRM_DEBUG_KMS("[ENCODER:%d:%s]\n",
12932                               encoder->base.base.id,
12933                               encoder->base.name);
12934
12935                 for_each_intel_connector(dev, connector) {
12936                         if (connector->base.state->best_encoder != &encoder->base)
12937                                 continue;
12938                         enabled = true;
12939
12940                         I915_STATE_WARN(connector->base.state->crtc !=
12941                                         encoder->base.crtc,
12942                              "connector's crtc doesn't match encoder crtc\n");
12943                 }
12944
12945                 I915_STATE_WARN(!!encoder->base.crtc != enabled,
12946                      "encoder's enabled state mismatch "
12947                      "(expected %i, found %i)\n",
12948                      !!encoder->base.crtc, enabled);
12949
12950                 if (!encoder->base.crtc) {
12951                         bool active;
12952
12953                         active = encoder->get_hw_state(encoder, &pipe);
12954                         I915_STATE_WARN(active,
12955                              "encoder detached but still enabled on pipe %c.\n",
12956                              pipe_name(pipe));
12957                 }
12958         }
12959 }
12960
12961 static void
12962 verify_crtc_state(struct drm_crtc *crtc,
12963                   struct drm_crtc_state *old_crtc_state,
12964                   struct drm_crtc_state *new_crtc_state)
12965 {
12966         struct drm_device *dev = crtc->dev;
12967         struct drm_i915_private *dev_priv = to_i915(dev);
12968         struct intel_encoder *encoder;
12969         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
12970         struct intel_crtc_state *pipe_config, *sw_config;
12971         struct drm_atomic_state *old_state;
12972         bool active;
12973
12974         old_state = old_crtc_state->state;
12975         __drm_atomic_helper_crtc_destroy_state(old_crtc_state);
12976         pipe_config = to_intel_crtc_state(old_crtc_state);
12977         memset(pipe_config, 0, sizeof(*pipe_config));
12978         pipe_config->base.crtc = crtc;
12979         pipe_config->base.state = old_state;
12980
12981         DRM_DEBUG_KMS("[CRTC:%d:%s]\n", crtc->base.id, crtc->name);
12982
12983         active = dev_priv->display.get_pipe_config(intel_crtc, pipe_config);
12984
12985         /* hw state is inconsistent with the pipe quirk */
12986         if ((intel_crtc->pipe == PIPE_A && dev_priv->quirks & QUIRK_PIPEA_FORCE) ||
12987             (intel_crtc->pipe == PIPE_B && dev_priv->quirks & QUIRK_PIPEB_FORCE))
12988                 active = new_crtc_state->active;
12989
12990         I915_STATE_WARN(new_crtc_state->active != active,
12991              "crtc active state doesn't match with hw state "
12992              "(expected %i, found %i)\n", new_crtc_state->active, active);
12993
12994         I915_STATE_WARN(intel_crtc->active != new_crtc_state->active,
12995              "transitional active state does not match atomic hw state "
12996              "(expected %i, found %i)\n", new_crtc_state->active, intel_crtc->active);
12997
12998         for_each_encoder_on_crtc(dev, crtc, encoder) {
12999                 enum pipe pipe;
13000
13001                 active = encoder->get_hw_state(encoder, &pipe);
13002                 I915_STATE_WARN(active != new_crtc_state->active,
13003                         "[ENCODER:%i] active %i with crtc active %i\n",
13004                         encoder->base.base.id, active, new_crtc_state->active);
13005
13006                 I915_STATE_WARN(active && intel_crtc->pipe != pipe,
13007                                 "Encoder connected to wrong pipe %c\n",
13008                                 pipe_name(pipe));
13009
13010                 if (active) {
13011                         pipe_config->output_types |= 1 << encoder->type;
13012                         encoder->get_config(encoder, pipe_config);
13013                 }
13014         }
13015
13016         if (!new_crtc_state->active)
13017                 return;
13018
13019         intel_pipe_config_sanity_check(dev_priv, pipe_config);
13020
13021         sw_config = to_intel_crtc_state(crtc->state);
13022         if (!intel_pipe_config_compare(dev, sw_config,
13023                                        pipe_config, false)) {
13024                 I915_STATE_WARN(1, "pipe state doesn't match!\n");
13025                 intel_dump_pipe_config(intel_crtc, pipe_config,
13026                                        "[hw state]");
13027                 intel_dump_pipe_config(intel_crtc, sw_config,
13028                                        "[sw state]");
13029         }
13030 }
13031
13032 static void
13033 verify_single_dpll_state(struct drm_i915_private *dev_priv,
13034                          struct intel_shared_dpll *pll,
13035                          struct drm_crtc *crtc,
13036                          struct drm_crtc_state *new_state)
13037 {
13038         struct intel_dpll_hw_state dpll_hw_state;
13039         unsigned crtc_mask;
13040         bool active;
13041
13042         memset(&dpll_hw_state, 0, sizeof(dpll_hw_state));
13043
13044         DRM_DEBUG_KMS("%s\n", pll->name);
13045
13046         active = pll->funcs.get_hw_state(dev_priv, pll, &dpll_hw_state);
13047
13048         if (!(pll->flags & INTEL_DPLL_ALWAYS_ON)) {
13049                 I915_STATE_WARN(!pll->on && pll->active_mask,
13050                      "pll in active use but not on in sw tracking\n");
13051                 I915_STATE_WARN(pll->on && !pll->active_mask,
13052                      "pll is on but not used by any active crtc\n");
13053                 I915_STATE_WARN(pll->on != active,
13054                      "pll on state mismatch (expected %i, found %i)\n",
13055                      pll->on, active);
13056         }
13057
13058         if (!crtc) {
13059                 I915_STATE_WARN(pll->active_mask & ~pll->config.crtc_mask,
13060                                 "more active pll users than references: %x vs %x\n",
13061                                 pll->active_mask, pll->config.crtc_mask);
13062
13063                 return;
13064         }
13065
13066         crtc_mask = 1 << drm_crtc_index(crtc);
13067
13068         if (new_state->active)
13069                 I915_STATE_WARN(!(pll->active_mask & crtc_mask),
13070                                 "pll active mismatch (expected pipe %c in active mask 0x%02x)\n",
13071                                 pipe_name(drm_crtc_index(crtc)), pll->active_mask);
13072         else
13073                 I915_STATE_WARN(pll->active_mask & crtc_mask,
13074                                 "pll active mismatch (didn't expect pipe %c in active mask 0x%02x)\n",
13075                                 pipe_name(drm_crtc_index(crtc)), pll->active_mask);
13076
13077         I915_STATE_WARN(!(pll->config.crtc_mask & crtc_mask),
13078                         "pll enabled crtcs mismatch (expected 0x%x in 0x%02x)\n",
13079                         crtc_mask, pll->config.crtc_mask);
13080
13081         I915_STATE_WARN(pll->on && memcmp(&pll->config.hw_state,
13082                                           &dpll_hw_state,
13083                                           sizeof(dpll_hw_state)),
13084                         "pll hw state mismatch\n");
13085 }
13086
13087 static void
13088 verify_shared_dpll_state(struct drm_device *dev, struct drm_crtc *crtc,
13089                          struct drm_crtc_state *old_crtc_state,
13090                          struct drm_crtc_state *new_crtc_state)
13091 {
13092         struct drm_i915_private *dev_priv = to_i915(dev);
13093         struct intel_crtc_state *old_state = to_intel_crtc_state(old_crtc_state);
13094         struct intel_crtc_state *new_state = to_intel_crtc_state(new_crtc_state);
13095
13096         if (new_state->shared_dpll)
13097                 verify_single_dpll_state(dev_priv, new_state->shared_dpll, crtc, new_crtc_state);
13098
13099         if (old_state->shared_dpll &&
13100             old_state->shared_dpll != new_state->shared_dpll) {
13101                 unsigned crtc_mask = 1 << drm_crtc_index(crtc);
13102                 struct intel_shared_dpll *pll = old_state->shared_dpll;
13103
13104                 I915_STATE_WARN(pll->active_mask & crtc_mask,
13105                                 "pll active mismatch (didn't expect pipe %c in active mask)\n",
13106                                 pipe_name(drm_crtc_index(crtc)));
13107                 I915_STATE_WARN(pll->config.crtc_mask & crtc_mask,
13108                                 "pll enabled crtcs mismatch (found %x in enabled mask)\n",
13109                                 pipe_name(drm_crtc_index(crtc)));
13110         }
13111 }
13112
13113 static void
13114 intel_modeset_verify_crtc(struct drm_crtc *crtc,
13115                          struct drm_crtc_state *old_state,
13116                          struct drm_crtc_state *new_state)
13117 {
13118         if (!needs_modeset(new_state) &&
13119             !to_intel_crtc_state(new_state)->update_pipe)
13120                 return;
13121
13122         verify_wm_state(crtc, new_state);
13123         verify_connector_state(crtc->dev, crtc);
13124         verify_crtc_state(crtc, old_state, new_state);
13125         verify_shared_dpll_state(crtc->dev, crtc, old_state, new_state);
13126 }
13127
13128 static void
13129 verify_disabled_dpll_state(struct drm_device *dev)
13130 {
13131         struct drm_i915_private *dev_priv = to_i915(dev);
13132         int i;
13133
13134         for (i = 0; i < dev_priv->num_shared_dpll; i++)
13135                 verify_single_dpll_state(dev_priv, &dev_priv->shared_dplls[i], NULL, NULL);
13136 }
13137
13138 static void
13139 intel_modeset_verify_disabled(struct drm_device *dev)
13140 {
13141         verify_encoder_state(dev);
13142         verify_connector_state(dev, NULL);
13143         verify_disabled_dpll_state(dev);
13144 }
13145
13146 static void update_scanline_offset(struct intel_crtc *crtc)
13147 {
13148         struct drm_device *dev = crtc->base.dev;
13149
13150         /*
13151          * The scanline counter increments at the leading edge of hsync.
13152          *
13153          * On most platforms it starts counting from vtotal-1 on the
13154          * first active line. That means the scanline counter value is
13155          * always one less than what we would expect. Ie. just after
13156          * start of vblank, which also occurs at start of hsync (on the
13157          * last active line), the scanline counter will read vblank_start-1.
13158          *
13159          * On gen2 the scanline counter starts counting from 1 instead
13160          * of vtotal-1, so we have to subtract one (or rather add vtotal-1
13161          * to keep the value positive), instead of adding one.
13162          *
13163          * On HSW+ the behaviour of the scanline counter depends on the output
13164          * type. For DP ports it behaves like most other platforms, but on HDMI
13165          * there's an extra 1 line difference. So we need to add two instead of
13166          * one to the value.
13167          */
13168         if (IS_GEN2(dev)) {
13169                 const struct drm_display_mode *adjusted_mode = &crtc->config->base.adjusted_mode;
13170                 int vtotal;
13171
13172                 vtotal = adjusted_mode->crtc_vtotal;
13173                 if (adjusted_mode->flags & DRM_MODE_FLAG_INTERLACE)
13174                         vtotal /= 2;
13175
13176                 crtc->scanline_offset = vtotal - 1;
13177         } else if (HAS_DDI(dev) &&
13178                    intel_crtc_has_type(crtc->config, INTEL_OUTPUT_HDMI)) {
13179                 crtc->scanline_offset = 2;
13180         } else
13181                 crtc->scanline_offset = 1;
13182 }
13183
13184 static void intel_modeset_clear_plls(struct drm_atomic_state *state)
13185 {
13186         struct drm_device *dev = state->dev;
13187         struct drm_i915_private *dev_priv = to_i915(dev);
13188         struct intel_shared_dpll_config *shared_dpll = NULL;
13189         struct drm_crtc *crtc;
13190         struct drm_crtc_state *crtc_state;
13191         int i;
13192
13193         if (!dev_priv->display.crtc_compute_clock)
13194                 return;
13195
13196         for_each_crtc_in_state(state, crtc, crtc_state, i) {
13197                 struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
13198                 struct intel_shared_dpll *old_dpll =
13199                         to_intel_crtc_state(crtc->state)->shared_dpll;
13200
13201                 if (!needs_modeset(crtc_state))
13202                         continue;
13203
13204                 to_intel_crtc_state(crtc_state)->shared_dpll = NULL;
13205
13206                 if (!old_dpll)
13207                         continue;
13208
13209                 if (!shared_dpll)
13210                         shared_dpll = intel_atomic_get_shared_dpll_state(state);
13211
13212                 intel_shared_dpll_config_put(shared_dpll, old_dpll, intel_crtc);
13213         }
13214 }
13215
13216 /*
13217  * This implements the workaround described in the "notes" section of the mode
13218  * set sequence documentation. When going from no pipes or single pipe to
13219  * multiple pipes, and planes are enabled after the pipe, we need to wait at
13220  * least 2 vblanks on the first pipe before enabling planes on the second pipe.
13221  */
13222 static int haswell_mode_set_planes_workaround(struct drm_atomic_state *state)
13223 {
13224         struct drm_crtc_state *crtc_state;
13225         struct intel_crtc *intel_crtc;
13226         struct drm_crtc *crtc;
13227         struct intel_crtc_state *first_crtc_state = NULL;
13228         struct intel_crtc_state *other_crtc_state = NULL;
13229         enum pipe first_pipe = INVALID_PIPE, enabled_pipe = INVALID_PIPE;
13230         int i;
13231
13232         /* look at all crtc's that are going to be enabled in during modeset */
13233         for_each_crtc_in_state(state, crtc, crtc_state, i) {
13234                 intel_crtc = to_intel_crtc(crtc);
13235
13236                 if (!crtc_state->active || !needs_modeset(crtc_state))
13237                         continue;
13238
13239                 if (first_crtc_state) {
13240                         other_crtc_state = to_intel_crtc_state(crtc_state);
13241                         break;
13242                 } else {
13243                         first_crtc_state = to_intel_crtc_state(crtc_state);
13244                         first_pipe = intel_crtc->pipe;
13245                 }
13246         }
13247
13248         /* No workaround needed? */
13249         if (!first_crtc_state)
13250                 return 0;
13251
13252         /* w/a possibly needed, check how many crtc's are already enabled. */
13253         for_each_intel_crtc(state->dev, intel_crtc) {
13254                 struct intel_crtc_state *pipe_config;
13255
13256                 pipe_config = intel_atomic_get_crtc_state(state, intel_crtc);
13257                 if (IS_ERR(pipe_config))
13258                         return PTR_ERR(pipe_config);
13259
13260                 pipe_config->hsw_workaround_pipe = INVALID_PIPE;
13261
13262                 if (!pipe_config->base.active ||
13263                     needs_modeset(&pipe_config->base))
13264                         continue;
13265
13266                 /* 2 or more enabled crtcs means no need for w/a */
13267                 if (enabled_pipe != INVALID_PIPE)
13268                         return 0;
13269
13270                 enabled_pipe = intel_crtc->pipe;
13271         }
13272
13273         if (enabled_pipe != INVALID_PIPE)
13274                 first_crtc_state->hsw_workaround_pipe = enabled_pipe;
13275         else if (other_crtc_state)
13276                 other_crtc_state->hsw_workaround_pipe = first_pipe;
13277
13278         return 0;
13279 }
13280
13281 static int intel_modeset_all_pipes(struct drm_atomic_state *state)
13282 {
13283         struct drm_crtc *crtc;
13284         struct drm_crtc_state *crtc_state;
13285         int ret = 0;
13286
13287         /* add all active pipes to the state */
13288         for_each_crtc(state->dev, crtc) {
13289                 crtc_state = drm_atomic_get_crtc_state(state, crtc);
13290                 if (IS_ERR(crtc_state))
13291                         return PTR_ERR(crtc_state);
13292
13293                 if (!crtc_state->active || needs_modeset(crtc_state))
13294                         continue;
13295
13296                 crtc_state->mode_changed = true;
13297
13298                 ret = drm_atomic_add_affected_connectors(state, crtc);
13299                 if (ret)
13300                         break;
13301
13302                 ret = drm_atomic_add_affected_planes(state, crtc);
13303                 if (ret)
13304                         break;
13305         }
13306
13307         return ret;
13308 }
13309
13310 static int intel_modeset_checks(struct drm_atomic_state *state)
13311 {
13312         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
13313         struct drm_i915_private *dev_priv = to_i915(state->dev);
13314         struct drm_crtc *crtc;
13315         struct drm_crtc_state *crtc_state;
13316         int ret = 0, i;
13317
13318         if (!check_digital_port_conflicts(state)) {
13319                 DRM_DEBUG_KMS("rejecting conflicting digital port configuration\n");
13320                 return -EINVAL;
13321         }
13322
13323         intel_state->modeset = true;
13324         intel_state->active_crtcs = dev_priv->active_crtcs;
13325
13326         for_each_crtc_in_state(state, crtc, crtc_state, i) {
13327                 if (crtc_state->active)
13328                         intel_state->active_crtcs |= 1 << i;
13329                 else
13330                         intel_state->active_crtcs &= ~(1 << i);
13331
13332                 if (crtc_state->active != crtc->state->active)
13333                         intel_state->active_pipe_changes |= drm_crtc_mask(crtc);
13334         }
13335
13336         /*
13337          * See if the config requires any additional preparation, e.g.
13338          * to adjust global state with pipes off.  We need to do this
13339          * here so we can get the modeset_pipe updated config for the new
13340          * mode set on this crtc.  For other crtcs we need to use the
13341          * adjusted_mode bits in the crtc directly.
13342          */
13343         if (dev_priv->display.modeset_calc_cdclk) {
13344                 if (!intel_state->cdclk_pll_vco)
13345                         intel_state->cdclk_pll_vco = dev_priv->cdclk_pll.vco;
13346                 if (!intel_state->cdclk_pll_vco)
13347                         intel_state->cdclk_pll_vco = dev_priv->skl_preferred_vco_freq;
13348
13349                 ret = dev_priv->display.modeset_calc_cdclk(state);
13350                 if (ret < 0)
13351                         return ret;
13352
13353                 if (intel_state->dev_cdclk != dev_priv->cdclk_freq ||
13354                     intel_state->cdclk_pll_vco != dev_priv->cdclk_pll.vco)
13355                         ret = intel_modeset_all_pipes(state);
13356
13357                 if (ret < 0)
13358                         return ret;
13359
13360                 DRM_DEBUG_KMS("New cdclk calculated to be atomic %u, actual %u\n",
13361                               intel_state->cdclk, intel_state->dev_cdclk);
13362         } else
13363                 to_intel_atomic_state(state)->cdclk = dev_priv->atomic_cdclk_freq;
13364
13365         intel_modeset_clear_plls(state);
13366
13367         if (IS_HASWELL(dev_priv))
13368                 return haswell_mode_set_planes_workaround(state);
13369
13370         return 0;
13371 }
13372
13373 /*
13374  * Handle calculation of various watermark data at the end of the atomic check
13375  * phase.  The code here should be run after the per-crtc and per-plane 'check'
13376  * handlers to ensure that all derived state has been updated.
13377  */
13378 static int calc_watermark_data(struct drm_atomic_state *state)
13379 {
13380         struct drm_device *dev = state->dev;
13381         struct drm_i915_private *dev_priv = to_i915(dev);
13382
13383         /* Is there platform-specific watermark information to calculate? */
13384         if (dev_priv->display.compute_global_watermarks)
13385                 return dev_priv->display.compute_global_watermarks(state);
13386
13387         return 0;
13388 }
13389
13390 /**
13391  * intel_atomic_check - validate state object
13392  * @dev: drm device
13393  * @state: state to validate
13394  */
13395 static int intel_atomic_check(struct drm_device *dev,
13396                               struct drm_atomic_state *state)
13397 {
13398         struct drm_i915_private *dev_priv = to_i915(dev);
13399         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
13400         struct drm_crtc *crtc;
13401         struct drm_crtc_state *crtc_state;
13402         int ret, i;
13403         bool any_ms = false;
13404
13405         ret = drm_atomic_helper_check_modeset(dev, state);
13406         if (ret)
13407                 return ret;
13408
13409         for_each_crtc_in_state(state, crtc, crtc_state, i) {
13410                 struct intel_crtc_state *pipe_config =
13411                         to_intel_crtc_state(crtc_state);
13412
13413                 /* Catch I915_MODE_FLAG_INHERITED */
13414                 if (crtc_state->mode.private_flags != crtc->state->mode.private_flags)
13415                         crtc_state->mode_changed = true;
13416
13417                 if (!needs_modeset(crtc_state))
13418                         continue;
13419
13420                 if (!crtc_state->enable) {
13421                         any_ms = true;
13422                         continue;
13423                 }
13424
13425                 /* FIXME: For only active_changed we shouldn't need to do any
13426                  * state recomputation at all. */
13427
13428                 ret = drm_atomic_add_affected_connectors(state, crtc);
13429                 if (ret)
13430                         return ret;
13431
13432                 ret = intel_modeset_pipe_config(crtc, pipe_config);
13433                 if (ret) {
13434                         intel_dump_pipe_config(to_intel_crtc(crtc),
13435                                                pipe_config, "[failed]");
13436                         return ret;
13437                 }
13438
13439                 if (i915.fastboot &&
13440                     intel_pipe_config_compare(dev,
13441                                         to_intel_crtc_state(crtc->state),
13442                                         pipe_config, true)) {
13443                         crtc_state->mode_changed = false;
13444                         to_intel_crtc_state(crtc_state)->update_pipe = true;
13445                 }
13446
13447                 if (needs_modeset(crtc_state))
13448                         any_ms = true;
13449
13450                 ret = drm_atomic_add_affected_planes(state, crtc);
13451                 if (ret)
13452                         return ret;
13453
13454                 intel_dump_pipe_config(to_intel_crtc(crtc), pipe_config,
13455                                        needs_modeset(crtc_state) ?
13456                                        "[modeset]" : "[fastset]");
13457         }
13458
13459         if (any_ms) {
13460                 ret = intel_modeset_checks(state);
13461
13462                 if (ret)
13463                         return ret;
13464         } else
13465                 intel_state->cdclk = dev_priv->cdclk_freq;
13466
13467         ret = drm_atomic_helper_check_planes(dev, state);
13468         if (ret)
13469                 return ret;
13470
13471         intel_fbc_choose_crtc(dev_priv, state);
13472         return calc_watermark_data(state);
13473 }
13474
13475 static int intel_atomic_prepare_commit(struct drm_device *dev,
13476                                        struct drm_atomic_state *state,
13477                                        bool nonblock)
13478 {
13479         struct drm_i915_private *dev_priv = to_i915(dev);
13480         struct drm_plane_state *plane_state;
13481         struct drm_crtc_state *crtc_state;
13482         struct drm_plane *plane;
13483         struct drm_crtc *crtc;
13484         int i, ret;
13485
13486         for_each_crtc_in_state(state, crtc, crtc_state, i) {
13487                 if (state->legacy_cursor_update)
13488                         continue;
13489
13490                 ret = intel_crtc_wait_for_pending_flips(crtc);
13491                 if (ret)
13492                         return ret;
13493
13494                 if (atomic_read(&to_intel_crtc(crtc)->unpin_work_count) >= 2)
13495                         flush_workqueue(dev_priv->wq);
13496         }
13497
13498         ret = mutex_lock_interruptible(&dev->struct_mutex);
13499         if (ret)
13500                 return ret;
13501
13502         ret = drm_atomic_helper_prepare_planes(dev, state);
13503         mutex_unlock(&dev->struct_mutex);
13504
13505         if (!ret && !nonblock) {
13506                 for_each_plane_in_state(state, plane, plane_state, i) {
13507                         struct intel_plane_state *intel_plane_state =
13508                                 to_intel_plane_state(plane_state);
13509
13510                         if (!intel_plane_state->wait_req)
13511                                 continue;
13512
13513                         ret = i915_wait_request(intel_plane_state->wait_req,
13514                                                 true, NULL, NULL);
13515                         if (ret) {
13516                                 /* Any hang should be swallowed by the wait */
13517                                 WARN_ON(ret == -EIO);
13518                                 mutex_lock(&dev->struct_mutex);
13519                                 drm_atomic_helper_cleanup_planes(dev, state);
13520                                 mutex_unlock(&dev->struct_mutex);
13521                                 break;
13522                         }
13523                 }
13524         }
13525
13526         return ret;
13527 }
13528
13529 u32 intel_crtc_get_vblank_counter(struct intel_crtc *crtc)
13530 {
13531         struct drm_device *dev = crtc->base.dev;
13532
13533         if (!dev->max_vblank_count)
13534                 return drm_accurate_vblank_count(&crtc->base);
13535
13536         return dev->driver->get_vblank_counter(dev, crtc->pipe);
13537 }
13538
13539 static void intel_atomic_wait_for_vblanks(struct drm_device *dev,
13540                                           struct drm_i915_private *dev_priv,
13541                                           unsigned crtc_mask)
13542 {
13543         unsigned last_vblank_count[I915_MAX_PIPES];
13544         enum pipe pipe;
13545         int ret;
13546
13547         if (!crtc_mask)
13548                 return;
13549
13550         for_each_pipe(dev_priv, pipe) {
13551                 struct drm_crtc *crtc = dev_priv->pipe_to_crtc_mapping[pipe];
13552
13553                 if (!((1 << pipe) & crtc_mask))
13554                         continue;
13555
13556                 ret = drm_crtc_vblank_get(crtc);
13557                 if (WARN_ON(ret != 0)) {
13558                         crtc_mask &= ~(1 << pipe);
13559                         continue;
13560                 }
13561
13562                 last_vblank_count[pipe] = drm_crtc_vblank_count(crtc);
13563         }
13564
13565         for_each_pipe(dev_priv, pipe) {
13566                 struct drm_crtc *crtc = dev_priv->pipe_to_crtc_mapping[pipe];
13567                 long lret;
13568
13569                 if (!((1 << pipe) & crtc_mask))
13570                         continue;
13571
13572                 lret = wait_event_timeout(dev->vblank[pipe].queue,
13573                                 last_vblank_count[pipe] !=
13574                                         drm_crtc_vblank_count(crtc),
13575                                 msecs_to_jiffies(50));
13576
13577                 WARN(!lret, "pipe %c vblank wait timed out\n", pipe_name(pipe));
13578
13579                 drm_crtc_vblank_put(crtc);
13580         }
13581 }
13582
13583 static bool needs_vblank_wait(struct intel_crtc_state *crtc_state)
13584 {
13585         /* fb updated, need to unpin old fb */
13586         if (crtc_state->fb_changed)
13587                 return true;
13588
13589         /* wm changes, need vblank before final wm's */
13590         if (crtc_state->update_wm_post)
13591                 return true;
13592
13593         /*
13594          * cxsr is re-enabled after vblank.
13595          * This is already handled by crtc_state->update_wm_post,
13596          * but added for clarity.
13597          */
13598         if (crtc_state->disable_cxsr)
13599                 return true;
13600
13601         return false;
13602 }
13603
13604 static void intel_atomic_commit_tail(struct drm_atomic_state *state)
13605 {
13606         struct drm_device *dev = state->dev;
13607         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
13608         struct drm_i915_private *dev_priv = to_i915(dev);
13609         struct drm_crtc_state *old_crtc_state;
13610         struct drm_crtc *crtc;
13611         struct intel_crtc_state *intel_cstate;
13612         struct drm_plane *plane;
13613         struct drm_plane_state *plane_state;
13614         bool hw_check = intel_state->modeset;
13615         unsigned long put_domains[I915_MAX_PIPES] = {};
13616         unsigned crtc_vblank_mask = 0;
13617         int i, ret;
13618
13619         for_each_plane_in_state(state, plane, plane_state, i) {
13620                 struct intel_plane_state *intel_plane_state =
13621                         to_intel_plane_state(plane_state);
13622
13623                 if (!intel_plane_state->wait_req)
13624                         continue;
13625
13626                 ret = i915_wait_request(intel_plane_state->wait_req,
13627                                         true, NULL, NULL);
13628                 /* EIO should be eaten, and we can't get interrupted in the
13629                  * worker, and blocking commits have waited already. */
13630                 WARN_ON(ret);
13631         }
13632
13633         drm_atomic_helper_wait_for_dependencies(state);
13634
13635         if (intel_state->modeset) {
13636                 memcpy(dev_priv->min_pixclk, intel_state->min_pixclk,
13637                        sizeof(intel_state->min_pixclk));
13638                 dev_priv->active_crtcs = intel_state->active_crtcs;
13639                 dev_priv->atomic_cdclk_freq = intel_state->cdclk;
13640
13641                 intel_display_power_get(dev_priv, POWER_DOMAIN_MODESET);
13642         }
13643
13644         for_each_crtc_in_state(state, crtc, old_crtc_state, i) {
13645                 struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
13646
13647                 if (needs_modeset(crtc->state) ||
13648                     to_intel_crtc_state(crtc->state)->update_pipe) {
13649                         hw_check = true;
13650
13651                         put_domains[to_intel_crtc(crtc)->pipe] =
13652                                 modeset_get_crtc_power_domains(crtc,
13653                                         to_intel_crtc_state(crtc->state));
13654                 }
13655
13656                 if (!needs_modeset(crtc->state))
13657                         continue;
13658
13659                 intel_pre_plane_update(to_intel_crtc_state(old_crtc_state));
13660
13661                 if (old_crtc_state->active) {
13662                         intel_crtc_disable_planes(crtc, old_crtc_state->plane_mask);
13663                         dev_priv->display.crtc_disable(crtc);
13664                         intel_crtc->active = false;
13665                         intel_fbc_disable(intel_crtc);
13666                         intel_disable_shared_dpll(intel_crtc);
13667
13668                         /*
13669                          * Underruns don't always raise
13670                          * interrupts, so check manually.
13671                          */
13672                         intel_check_cpu_fifo_underruns(dev_priv);
13673                         intel_check_pch_fifo_underruns(dev_priv);
13674
13675                         if (!crtc->state->active)
13676                                 intel_update_watermarks(crtc);
13677                 }
13678         }
13679
13680         /* Only after disabling all output pipelines that will be changed can we
13681          * update the the output configuration. */
13682         intel_modeset_update_crtc_state(state);
13683
13684         if (intel_state->modeset) {
13685                 drm_atomic_helper_update_legacy_modeset_state(state->dev, state);
13686
13687                 if (dev_priv->display.modeset_commit_cdclk &&
13688                     (intel_state->dev_cdclk != dev_priv->cdclk_freq ||
13689                      intel_state->cdclk_pll_vco != dev_priv->cdclk_pll.vco))
13690                         dev_priv->display.modeset_commit_cdclk(state);
13691
13692                 intel_modeset_verify_disabled(dev);
13693         }
13694
13695         /* Now enable the clocks, plane, pipe, and connectors that we set up. */
13696         for_each_crtc_in_state(state, crtc, old_crtc_state, i) {
13697                 struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
13698                 bool modeset = needs_modeset(crtc->state);
13699                 struct intel_crtc_state *pipe_config =
13700                         to_intel_crtc_state(crtc->state);
13701
13702                 if (modeset && crtc->state->active) {
13703                         update_scanline_offset(to_intel_crtc(crtc));
13704                         dev_priv->display.crtc_enable(crtc);
13705                 }
13706
13707                 /* Complete events for now disable pipes here. */
13708                 if (modeset && !crtc->state->active && crtc->state->event) {
13709                         spin_lock_irq(&dev->event_lock);
13710                         drm_crtc_send_vblank_event(crtc, crtc->state->event);
13711                         spin_unlock_irq(&dev->event_lock);
13712
13713                         crtc->state->event = NULL;
13714                 }
13715
13716                 if (!modeset)
13717                         intel_pre_plane_update(to_intel_crtc_state(old_crtc_state));
13718
13719                 if (crtc->state->active &&
13720                     drm_atomic_get_existing_plane_state(state, crtc->primary))
13721                         intel_fbc_enable(intel_crtc, pipe_config, to_intel_plane_state(crtc->primary->state));
13722
13723                 if (crtc->state->active)
13724                         drm_atomic_helper_commit_planes_on_crtc(old_crtc_state);
13725
13726                 if (pipe_config->base.active && needs_vblank_wait(pipe_config))
13727                         crtc_vblank_mask |= 1 << i;
13728         }
13729
13730         /* FIXME: We should call drm_atomic_helper_commit_hw_done() here
13731          * already, but still need the state for the delayed optimization. To
13732          * fix this:
13733          * - wrap the optimization/post_plane_update stuff into a per-crtc work.
13734          * - schedule that vblank worker _before_ calling hw_done
13735          * - at the start of commit_tail, cancel it _synchrously
13736          * - switch over to the vblank wait helper in the core after that since
13737          *   we don't need out special handling any more.
13738          */
13739         if (!state->legacy_cursor_update)
13740                 intel_atomic_wait_for_vblanks(dev, dev_priv, crtc_vblank_mask);
13741
13742         /*
13743          * Now that the vblank has passed, we can go ahead and program the
13744          * optimal watermarks on platforms that need two-step watermark
13745          * programming.
13746          *
13747          * TODO: Move this (and other cleanup) to an async worker eventually.
13748          */
13749         for_each_crtc_in_state(state, crtc, old_crtc_state, i) {
13750                 intel_cstate = to_intel_crtc_state(crtc->state);
13751
13752                 if (dev_priv->display.optimize_watermarks)
13753                         dev_priv->display.optimize_watermarks(intel_cstate);
13754         }
13755
13756         for_each_crtc_in_state(state, crtc, old_crtc_state, i) {
13757                 intel_post_plane_update(to_intel_crtc_state(old_crtc_state));
13758
13759                 if (put_domains[i])
13760                         modeset_put_power_domains(dev_priv, put_domains[i]);
13761
13762                 intel_modeset_verify_crtc(crtc, old_crtc_state, crtc->state);
13763         }
13764
13765         drm_atomic_helper_commit_hw_done(state);
13766
13767         if (intel_state->modeset)
13768                 intel_display_power_put(dev_priv, POWER_DOMAIN_MODESET);
13769
13770         mutex_lock(&dev->struct_mutex);
13771         drm_atomic_helper_cleanup_planes(dev, state);
13772         mutex_unlock(&dev->struct_mutex);
13773
13774         drm_atomic_helper_commit_cleanup_done(state);
13775
13776         drm_atomic_state_free(state);
13777
13778         /* As one of the primary mmio accessors, KMS has a high likelihood
13779          * of triggering bugs in unclaimed access. After we finish
13780          * modesetting, see if an error has been flagged, and if so
13781          * enable debugging for the next modeset - and hope we catch
13782          * the culprit.
13783          *
13784          * XXX note that we assume display power is on at this point.
13785          * This might hold true now but we need to add pm helper to check
13786          * unclaimed only when the hardware is on, as atomic commits
13787          * can happen also when the device is completely off.
13788          */
13789         intel_uncore_arm_unclaimed_mmio_detection(dev_priv);
13790 }
13791
13792 static void intel_atomic_commit_work(struct work_struct *work)
13793 {
13794         struct drm_atomic_state *state = container_of(work,
13795                                                       struct drm_atomic_state,
13796                                                       commit_work);
13797         intel_atomic_commit_tail(state);
13798 }
13799
13800 static void intel_atomic_track_fbs(struct drm_atomic_state *state)
13801 {
13802         struct drm_plane_state *old_plane_state;
13803         struct drm_plane *plane;
13804         int i;
13805
13806         for_each_plane_in_state(state, plane, old_plane_state, i)
13807                 i915_gem_track_fb(intel_fb_obj(old_plane_state->fb),
13808                                   intel_fb_obj(plane->state->fb),
13809                                   to_intel_plane(plane)->frontbuffer_bit);
13810 }
13811
13812 /**
13813  * intel_atomic_commit - commit validated state object
13814  * @dev: DRM device
13815  * @state: the top-level driver state object
13816  * @nonblock: nonblocking commit
13817  *
13818  * This function commits a top-level state object that has been validated
13819  * with drm_atomic_helper_check().
13820  *
13821  * FIXME:  Atomic modeset support for i915 is not yet complete.  At the moment
13822  * nonblocking commits are only safe for pure plane updates. Everything else
13823  * should work though.
13824  *
13825  * RETURNS
13826  * Zero for success or -errno.
13827  */
13828 static int intel_atomic_commit(struct drm_device *dev,
13829                                struct drm_atomic_state *state,
13830                                bool nonblock)
13831 {
13832         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
13833         struct drm_i915_private *dev_priv = to_i915(dev);
13834         int ret = 0;
13835
13836         if (intel_state->modeset && nonblock) {
13837                 DRM_DEBUG_KMS("nonblocking commit for modeset not yet implemented.\n");
13838                 return -EINVAL;
13839         }
13840
13841         ret = drm_atomic_helper_setup_commit(state, nonblock);
13842         if (ret)
13843                 return ret;
13844
13845         INIT_WORK(&state->commit_work, intel_atomic_commit_work);
13846
13847         ret = intel_atomic_prepare_commit(dev, state, nonblock);
13848         if (ret) {
13849                 DRM_DEBUG_ATOMIC("Preparing state failed with %i\n", ret);
13850                 return ret;
13851         }
13852
13853         drm_atomic_helper_swap_state(state, true);
13854         dev_priv->wm.distrust_bios_wm = false;
13855         dev_priv->wm.skl_results = intel_state->wm_results;
13856         intel_shared_dpll_commit(state);
13857         intel_atomic_track_fbs(state);
13858
13859         if (nonblock)
13860                 queue_work(system_unbound_wq, &state->commit_work);
13861         else
13862                 intel_atomic_commit_tail(state);
13863
13864         return 0;
13865 }
13866
13867 void intel_crtc_restore_mode(struct drm_crtc *crtc)
13868 {
13869         struct drm_device *dev = crtc->dev;
13870         struct drm_atomic_state *state;
13871         struct drm_crtc_state *crtc_state;
13872         int ret;
13873
13874         state = drm_atomic_state_alloc(dev);
13875         if (!state) {
13876                 DRM_DEBUG_KMS("[CRTC:%d:%s] crtc restore failed, out of memory",
13877                               crtc->base.id, crtc->name);
13878                 return;
13879         }
13880
13881         state->acquire_ctx = drm_modeset_legacy_acquire_ctx(crtc);
13882
13883 retry:
13884         crtc_state = drm_atomic_get_crtc_state(state, crtc);
13885         ret = PTR_ERR_OR_ZERO(crtc_state);
13886         if (!ret) {
13887                 if (!crtc_state->active)
13888                         goto out;
13889
13890                 crtc_state->mode_changed = true;
13891                 ret = drm_atomic_commit(state);
13892         }
13893
13894         if (ret == -EDEADLK) {
13895                 drm_atomic_state_clear(state);
13896                 drm_modeset_backoff(state->acquire_ctx);
13897                 goto retry;
13898         }
13899
13900         if (ret)
13901 out:
13902                 drm_atomic_state_free(state);
13903 }
13904
13905 #undef for_each_intel_crtc_masked
13906
13907 /*
13908  * FIXME: Remove this once i915 is fully DRIVER_ATOMIC by calling
13909  *        drm_atomic_helper_legacy_gamma_set() directly.
13910  */
13911 static int intel_atomic_legacy_gamma_set(struct drm_crtc *crtc,
13912                                          u16 *red, u16 *green, u16 *blue,
13913                                          uint32_t size)
13914 {
13915         struct drm_device *dev = crtc->dev;
13916         struct drm_mode_config *config = &dev->mode_config;
13917         struct drm_crtc_state *state;
13918         int ret;
13919
13920         ret = drm_atomic_helper_legacy_gamma_set(crtc, red, green, blue, size);
13921         if (ret)
13922                 return ret;
13923
13924         /*
13925          * Make sure we update the legacy properties so this works when
13926          * atomic is not enabled.
13927          */
13928
13929         state = crtc->state;
13930
13931         drm_object_property_set_value(&crtc->base,
13932                                       config->degamma_lut_property,
13933                                       (state->degamma_lut) ?
13934                                       state->degamma_lut->base.id : 0);
13935
13936         drm_object_property_set_value(&crtc->base,
13937                                       config->ctm_property,
13938                                       (state->ctm) ?
13939                                       state->ctm->base.id : 0);
13940
13941         drm_object_property_set_value(&crtc->base,
13942                                       config->gamma_lut_property,
13943                                       (state->gamma_lut) ?
13944                                       state->gamma_lut->base.id : 0);
13945
13946         return 0;
13947 }
13948
13949 static const struct drm_crtc_funcs intel_crtc_funcs = {
13950         .gamma_set = intel_atomic_legacy_gamma_set,
13951         .set_config = drm_atomic_helper_set_config,
13952         .set_property = drm_atomic_helper_crtc_set_property,
13953         .destroy = intel_crtc_destroy,
13954         .page_flip = intel_crtc_page_flip,
13955         .atomic_duplicate_state = intel_crtc_duplicate_state,
13956         .atomic_destroy_state = intel_crtc_destroy_state,
13957 };
13958
13959 /**
13960  * intel_prepare_plane_fb - Prepare fb for usage on plane
13961  * @plane: drm plane to prepare for
13962  * @fb: framebuffer to prepare for presentation
13963  *
13964  * Prepares a framebuffer for usage on a display plane.  Generally this
13965  * involves pinning the underlying object and updating the frontbuffer tracking
13966  * bits.  Some older platforms need special physical address handling for
13967  * cursor planes.
13968  *
13969  * Must be called with struct_mutex held.
13970  *
13971  * Returns 0 on success, negative error code on failure.
13972  */
13973 int
13974 intel_prepare_plane_fb(struct drm_plane *plane,
13975                        const struct drm_plane_state *new_state)
13976 {
13977         struct drm_device *dev = plane->dev;
13978         struct drm_framebuffer *fb = new_state->fb;
13979         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
13980         struct drm_i915_gem_object *old_obj = intel_fb_obj(plane->state->fb);
13981         struct reservation_object *resv;
13982         int ret = 0;
13983
13984         if (!obj && !old_obj)
13985                 return 0;
13986
13987         if (old_obj) {
13988                 struct drm_crtc_state *crtc_state =
13989                         drm_atomic_get_existing_crtc_state(new_state->state, plane->state->crtc);
13990
13991                 /* Big Hammer, we also need to ensure that any pending
13992                  * MI_WAIT_FOR_EVENT inside a user batch buffer on the
13993                  * current scanout is retired before unpinning the old
13994                  * framebuffer. Note that we rely on userspace rendering
13995                  * into the buffer attached to the pipe they are waiting
13996                  * on. If not, userspace generates a GPU hang with IPEHR
13997                  * point to the MI_WAIT_FOR_EVENT.
13998                  *
13999                  * This should only fail upon a hung GPU, in which case we
14000                  * can safely continue.
14001                  */
14002                 if (needs_modeset(crtc_state))
14003                         ret = i915_gem_object_wait_rendering(old_obj, true);
14004                 if (ret) {
14005                         /* GPU hangs should have been swallowed by the wait */
14006                         WARN_ON(ret == -EIO);
14007                         return ret;
14008                 }
14009         }
14010
14011         if (!obj)
14012                 return 0;
14013
14014         /* For framebuffer backed by dmabuf, wait for fence */
14015         resv = i915_gem_object_get_dmabuf_resv(obj);
14016         if (resv) {
14017                 long lret;
14018
14019                 lret = reservation_object_wait_timeout_rcu(resv, false, true,
14020                                                            MAX_SCHEDULE_TIMEOUT);
14021                 if (lret == -ERESTARTSYS)
14022                         return lret;
14023
14024                 WARN(lret < 0, "waiting returns %li\n", lret);
14025         }
14026
14027         if (plane->type == DRM_PLANE_TYPE_CURSOR &&
14028             INTEL_INFO(dev)->cursor_needs_physical) {
14029                 int align = IS_I830(dev) ? 16 * 1024 : 256;
14030                 ret = i915_gem_object_attach_phys(obj, align);
14031                 if (ret)
14032                         DRM_DEBUG_KMS("failed to attach phys object\n");
14033         } else {
14034                 ret = intel_pin_and_fence_fb_obj(fb, new_state->rotation);
14035         }
14036
14037         if (ret == 0) {
14038                 to_intel_plane_state(new_state)->wait_req =
14039                         i915_gem_active_get(&obj->last_write,
14040                                             &obj->base.dev->struct_mutex);
14041         }
14042
14043         return ret;
14044 }
14045
14046 /**
14047  * intel_cleanup_plane_fb - Cleans up an fb after plane use
14048  * @plane: drm plane to clean up for
14049  * @fb: old framebuffer that was on plane
14050  *
14051  * Cleans up a framebuffer that has just been removed from a plane.
14052  *
14053  * Must be called with struct_mutex held.
14054  */
14055 void
14056 intel_cleanup_plane_fb(struct drm_plane *plane,
14057                        const struct drm_plane_state *old_state)
14058 {
14059         struct drm_device *dev = plane->dev;
14060         struct intel_plane_state *old_intel_state;
14061         struct intel_plane_state *intel_state = to_intel_plane_state(plane->state);
14062         struct drm_i915_gem_object *old_obj = intel_fb_obj(old_state->fb);
14063         struct drm_i915_gem_object *obj = intel_fb_obj(plane->state->fb);
14064
14065         old_intel_state = to_intel_plane_state(old_state);
14066
14067         if (!obj && !old_obj)
14068                 return;
14069
14070         if (old_obj && (plane->type != DRM_PLANE_TYPE_CURSOR ||
14071             !INTEL_INFO(dev)->cursor_needs_physical))
14072                 intel_unpin_fb_obj(old_state->fb, old_state->rotation);
14073
14074         i915_gem_request_assign(&intel_state->wait_req, NULL);
14075         i915_gem_request_assign(&old_intel_state->wait_req, NULL);
14076 }
14077
14078 int
14079 skl_max_scale(struct intel_crtc *intel_crtc, struct intel_crtc_state *crtc_state)
14080 {
14081         int max_scale;
14082         int crtc_clock, cdclk;
14083
14084         if (!intel_crtc || !crtc_state->base.enable)
14085                 return DRM_PLANE_HELPER_NO_SCALING;
14086
14087         crtc_clock = crtc_state->base.adjusted_mode.crtc_clock;
14088         cdclk = to_intel_atomic_state(crtc_state->base.state)->cdclk;
14089
14090         if (WARN_ON_ONCE(!crtc_clock || cdclk < crtc_clock))
14091                 return DRM_PLANE_HELPER_NO_SCALING;
14092
14093         /*
14094          * skl max scale is lower of:
14095          *    close to 3 but not 3, -1 is for that purpose
14096          *            or
14097          *    cdclk/crtc_clock
14098          */
14099         max_scale = min((1 << 16) * 3 - 1, (1 << 8) * ((cdclk << 8) / crtc_clock));
14100
14101         return max_scale;
14102 }
14103
14104 static int
14105 intel_check_primary_plane(struct drm_plane *plane,
14106                           struct intel_crtc_state *crtc_state,
14107                           struct intel_plane_state *state)
14108 {
14109         struct drm_crtc *crtc = state->base.crtc;
14110         int min_scale = DRM_PLANE_HELPER_NO_SCALING;
14111         int max_scale = DRM_PLANE_HELPER_NO_SCALING;
14112         bool can_position = false;
14113
14114         if (INTEL_INFO(plane->dev)->gen >= 9) {
14115                 /* use scaler when colorkey is not required */
14116                 if (state->ckey.flags == I915_SET_COLORKEY_NONE) {
14117                         min_scale = 1;
14118                         max_scale = skl_max_scale(to_intel_crtc(crtc), crtc_state);
14119                 }
14120                 can_position = true;
14121         }
14122
14123         return drm_plane_helper_check_state(&state->base,
14124                                             &state->clip,
14125                                             min_scale, max_scale,
14126                                             can_position, true);
14127 }
14128
14129 static void intel_begin_crtc_commit(struct drm_crtc *crtc,
14130                                     struct drm_crtc_state *old_crtc_state)
14131 {
14132         struct drm_device *dev = crtc->dev;
14133         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
14134         struct intel_crtc_state *old_intel_state =
14135                 to_intel_crtc_state(old_crtc_state);
14136         bool modeset = needs_modeset(crtc->state);
14137
14138         /* Perform vblank evasion around commit operation */
14139         intel_pipe_update_start(intel_crtc);
14140
14141         if (modeset)
14142                 return;
14143
14144         if (crtc->state->color_mgmt_changed || to_intel_crtc_state(crtc->state)->update_pipe) {
14145                 intel_color_set_csc(crtc->state);
14146                 intel_color_load_luts(crtc->state);
14147         }
14148
14149         if (to_intel_crtc_state(crtc->state)->update_pipe)
14150                 intel_update_pipe_config(intel_crtc, old_intel_state);
14151         else if (INTEL_INFO(dev)->gen >= 9)
14152                 skl_detach_scalers(intel_crtc);
14153 }
14154
14155 static void intel_finish_crtc_commit(struct drm_crtc *crtc,
14156                                      struct drm_crtc_state *old_crtc_state)
14157 {
14158         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
14159
14160         intel_pipe_update_end(intel_crtc, NULL);
14161 }
14162
14163 /**
14164  * intel_plane_destroy - destroy a plane
14165  * @plane: plane to destroy
14166  *
14167  * Common destruction function for all types of planes (primary, cursor,
14168  * sprite).
14169  */
14170 void intel_plane_destroy(struct drm_plane *plane)
14171 {
14172         if (!plane)
14173                 return;
14174
14175         drm_plane_cleanup(plane);
14176         kfree(to_intel_plane(plane));
14177 }
14178
14179 const struct drm_plane_funcs intel_plane_funcs = {
14180         .update_plane = drm_atomic_helper_update_plane,
14181         .disable_plane = drm_atomic_helper_disable_plane,
14182         .destroy = intel_plane_destroy,
14183         .set_property = drm_atomic_helper_plane_set_property,
14184         .atomic_get_property = intel_plane_atomic_get_property,
14185         .atomic_set_property = intel_plane_atomic_set_property,
14186         .atomic_duplicate_state = intel_plane_duplicate_state,
14187         .atomic_destroy_state = intel_plane_destroy_state,
14188
14189 };
14190
14191 static struct drm_plane *intel_primary_plane_create(struct drm_device *dev,
14192                                                     int pipe)
14193 {
14194         struct intel_plane *primary = NULL;
14195         struct intel_plane_state *state = NULL;
14196         const uint32_t *intel_primary_formats;
14197         unsigned int num_formats;
14198         int ret;
14199
14200         primary = kzalloc(sizeof(*primary), GFP_KERNEL);
14201         if (!primary)
14202                 goto fail;
14203
14204         state = intel_create_plane_state(&primary->base);
14205         if (!state)
14206                 goto fail;
14207         primary->base.state = &state->base;
14208
14209         primary->can_scale = false;
14210         primary->max_downscale = 1;
14211         if (INTEL_INFO(dev)->gen >= 9) {
14212                 primary->can_scale = true;
14213                 state->scaler_id = -1;
14214         }
14215         primary->pipe = pipe;
14216         primary->plane = pipe;
14217         primary->frontbuffer_bit = INTEL_FRONTBUFFER_PRIMARY(pipe);
14218         primary->check_plane = intel_check_primary_plane;
14219         if (HAS_FBC(dev) && INTEL_INFO(dev)->gen < 4)
14220                 primary->plane = !pipe;
14221
14222         if (INTEL_INFO(dev)->gen >= 9) {
14223                 intel_primary_formats = skl_primary_formats;
14224                 num_formats = ARRAY_SIZE(skl_primary_formats);
14225
14226                 primary->update_plane = skylake_update_primary_plane;
14227                 primary->disable_plane = skylake_disable_primary_plane;
14228         } else if (HAS_PCH_SPLIT(dev)) {
14229                 intel_primary_formats = i965_primary_formats;
14230                 num_formats = ARRAY_SIZE(i965_primary_formats);
14231
14232                 primary->update_plane = ironlake_update_primary_plane;
14233                 primary->disable_plane = i9xx_disable_primary_plane;
14234         } else if (INTEL_INFO(dev)->gen >= 4) {
14235                 intel_primary_formats = i965_primary_formats;
14236                 num_formats = ARRAY_SIZE(i965_primary_formats);
14237
14238                 primary->update_plane = i9xx_update_primary_plane;
14239                 primary->disable_plane = i9xx_disable_primary_plane;
14240         } else {
14241                 intel_primary_formats = i8xx_primary_formats;
14242                 num_formats = ARRAY_SIZE(i8xx_primary_formats);
14243
14244                 primary->update_plane = i9xx_update_primary_plane;
14245                 primary->disable_plane = i9xx_disable_primary_plane;
14246         }
14247
14248         if (INTEL_INFO(dev)->gen >= 9)
14249                 ret = drm_universal_plane_init(dev, &primary->base, 0,
14250                                                &intel_plane_funcs,
14251                                                intel_primary_formats, num_formats,
14252                                                DRM_PLANE_TYPE_PRIMARY,
14253                                                "plane 1%c", pipe_name(pipe));
14254         else if (INTEL_INFO(dev)->gen >= 5 || IS_G4X(dev))
14255                 ret = drm_universal_plane_init(dev, &primary->base, 0,
14256                                                &intel_plane_funcs,
14257                                                intel_primary_formats, num_formats,
14258                                                DRM_PLANE_TYPE_PRIMARY,
14259                                                "primary %c", pipe_name(pipe));
14260         else
14261                 ret = drm_universal_plane_init(dev, &primary->base, 0,
14262                                                &intel_plane_funcs,
14263                                                intel_primary_formats, num_formats,
14264                                                DRM_PLANE_TYPE_PRIMARY,
14265                                                "plane %c", plane_name(primary->plane));
14266         if (ret)
14267                 goto fail;
14268
14269         if (INTEL_INFO(dev)->gen >= 4)
14270                 intel_create_rotation_property(dev, primary);
14271
14272         drm_plane_helper_add(&primary->base, &intel_plane_helper_funcs);
14273
14274         return &primary->base;
14275
14276 fail:
14277         kfree(state);
14278         kfree(primary);
14279
14280         return NULL;
14281 }
14282
14283 void intel_create_rotation_property(struct drm_device *dev, struct intel_plane *plane)
14284 {
14285         if (!dev->mode_config.rotation_property) {
14286                 unsigned long flags = DRM_ROTATE_0 |
14287                         DRM_ROTATE_180;
14288
14289                 if (INTEL_INFO(dev)->gen >= 9)
14290                         flags |= DRM_ROTATE_90 | DRM_ROTATE_270;
14291
14292                 dev->mode_config.rotation_property =
14293                         drm_mode_create_rotation_property(dev, flags);
14294         }
14295         if (dev->mode_config.rotation_property)
14296                 drm_object_attach_property(&plane->base.base,
14297                                 dev->mode_config.rotation_property,
14298                                 plane->base.state->rotation);
14299 }
14300
14301 static int
14302 intel_check_cursor_plane(struct drm_plane *plane,
14303                          struct intel_crtc_state *crtc_state,
14304                          struct intel_plane_state *state)
14305 {
14306         struct drm_framebuffer *fb = state->base.fb;
14307         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
14308         enum pipe pipe = to_intel_plane(plane)->pipe;
14309         unsigned stride;
14310         int ret;
14311
14312         ret = drm_plane_helper_check_state(&state->base,
14313                                            &state->clip,
14314                                            DRM_PLANE_HELPER_NO_SCALING,
14315                                            DRM_PLANE_HELPER_NO_SCALING,
14316                                            true, true);
14317         if (ret)
14318                 return ret;
14319
14320         /* if we want to turn off the cursor ignore width and height */
14321         if (!obj)
14322                 return 0;
14323
14324         /* Check for which cursor types we support */
14325         if (!cursor_size_ok(plane->dev, state->base.crtc_w, state->base.crtc_h)) {
14326                 DRM_DEBUG("Cursor dimension %dx%d not supported\n",
14327                           state->base.crtc_w, state->base.crtc_h);
14328                 return -EINVAL;
14329         }
14330
14331         stride = roundup_pow_of_two(state->base.crtc_w) * 4;
14332         if (obj->base.size < stride * state->base.crtc_h) {
14333                 DRM_DEBUG_KMS("buffer is too small\n");
14334                 return -ENOMEM;
14335         }
14336
14337         if (fb->modifier[0] != DRM_FORMAT_MOD_NONE) {
14338                 DRM_DEBUG_KMS("cursor cannot be tiled\n");
14339                 return -EINVAL;
14340         }
14341
14342         /*
14343          * There's something wrong with the cursor on CHV pipe C.
14344          * If it straddles the left edge of the screen then
14345          * moving it away from the edge or disabling it often
14346          * results in a pipe underrun, and often that can lead to
14347          * dead pipe (constant underrun reported, and it scans
14348          * out just a solid color). To recover from that, the
14349          * display power well must be turned off and on again.
14350          * Refuse the put the cursor into that compromised position.
14351          */
14352         if (IS_CHERRYVIEW(plane->dev) && pipe == PIPE_C &&
14353             state->base.visible && state->base.crtc_x < 0) {
14354                 DRM_DEBUG_KMS("CHV cursor C not allowed to straddle the left screen edge\n");
14355                 return -EINVAL;
14356         }
14357
14358         return 0;
14359 }
14360
14361 static void
14362 intel_disable_cursor_plane(struct drm_plane *plane,
14363                            struct drm_crtc *crtc)
14364 {
14365         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
14366
14367         intel_crtc->cursor_addr = 0;
14368         intel_crtc_update_cursor(crtc, NULL);
14369 }
14370
14371 static void
14372 intel_update_cursor_plane(struct drm_plane *plane,
14373                           const struct intel_crtc_state *crtc_state,
14374                           const struct intel_plane_state *state)
14375 {
14376         struct drm_crtc *crtc = crtc_state->base.crtc;
14377         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
14378         struct drm_device *dev = plane->dev;
14379         struct drm_i915_gem_object *obj = intel_fb_obj(state->base.fb);
14380         uint32_t addr;
14381
14382         if (!obj)
14383                 addr = 0;
14384         else if (!INTEL_INFO(dev)->cursor_needs_physical)
14385                 addr = i915_gem_obj_ggtt_offset(obj);
14386         else
14387                 addr = obj->phys_handle->busaddr;
14388
14389         intel_crtc->cursor_addr = addr;
14390         intel_crtc_update_cursor(crtc, state);
14391 }
14392
14393 static struct drm_plane *intel_cursor_plane_create(struct drm_device *dev,
14394                                                    int pipe)
14395 {
14396         struct intel_plane *cursor = NULL;
14397         struct intel_plane_state *state = NULL;
14398         int ret;
14399
14400         cursor = kzalloc(sizeof(*cursor), GFP_KERNEL);
14401         if (!cursor)
14402                 goto fail;
14403
14404         state = intel_create_plane_state(&cursor->base);
14405         if (!state)
14406                 goto fail;
14407         cursor->base.state = &state->base;
14408
14409         cursor->can_scale = false;
14410         cursor->max_downscale = 1;
14411         cursor->pipe = pipe;
14412         cursor->plane = pipe;
14413         cursor->frontbuffer_bit = INTEL_FRONTBUFFER_CURSOR(pipe);
14414         cursor->check_plane = intel_check_cursor_plane;
14415         cursor->update_plane = intel_update_cursor_plane;
14416         cursor->disable_plane = intel_disable_cursor_plane;
14417
14418         ret = drm_universal_plane_init(dev, &cursor->base, 0,
14419                                        &intel_plane_funcs,
14420                                        intel_cursor_formats,
14421                                        ARRAY_SIZE(intel_cursor_formats),
14422                                        DRM_PLANE_TYPE_CURSOR,
14423                                        "cursor %c", pipe_name(pipe));
14424         if (ret)
14425                 goto fail;
14426
14427         if (INTEL_INFO(dev)->gen >= 4) {
14428                 if (!dev->mode_config.rotation_property)
14429                         dev->mode_config.rotation_property =
14430                                 drm_mode_create_rotation_property(dev,
14431                                                         DRM_ROTATE_0 |
14432                                                         DRM_ROTATE_180);
14433                 if (dev->mode_config.rotation_property)
14434                         drm_object_attach_property(&cursor->base.base,
14435                                 dev->mode_config.rotation_property,
14436                                 state->base.rotation);
14437         }
14438
14439         if (INTEL_INFO(dev)->gen >=9)
14440                 state->scaler_id = -1;
14441
14442         drm_plane_helper_add(&cursor->base, &intel_plane_helper_funcs);
14443
14444         return &cursor->base;
14445
14446 fail:
14447         kfree(state);
14448         kfree(cursor);
14449
14450         return NULL;
14451 }
14452
14453 static void skl_init_scalers(struct drm_device *dev, struct intel_crtc *intel_crtc,
14454         struct intel_crtc_state *crtc_state)
14455 {
14456         int i;
14457         struct intel_scaler *intel_scaler;
14458         struct intel_crtc_scaler_state *scaler_state = &crtc_state->scaler_state;
14459
14460         for (i = 0; i < intel_crtc->num_scalers; i++) {
14461                 intel_scaler = &scaler_state->scalers[i];
14462                 intel_scaler->in_use = 0;
14463                 intel_scaler->mode = PS_SCALER_MODE_DYN;
14464         }
14465
14466         scaler_state->scaler_id = -1;
14467 }
14468
14469 static void intel_crtc_init(struct drm_device *dev, int pipe)
14470 {
14471         struct drm_i915_private *dev_priv = to_i915(dev);
14472         struct intel_crtc *intel_crtc;
14473         struct intel_crtc_state *crtc_state = NULL;
14474         struct drm_plane *primary = NULL;
14475         struct drm_plane *cursor = NULL;
14476         int ret;
14477
14478         intel_crtc = kzalloc(sizeof(*intel_crtc), GFP_KERNEL);
14479         if (intel_crtc == NULL)
14480                 return;
14481
14482         crtc_state = kzalloc(sizeof(*crtc_state), GFP_KERNEL);
14483         if (!crtc_state)
14484                 goto fail;
14485         intel_crtc->config = crtc_state;
14486         intel_crtc->base.state = &crtc_state->base;
14487         crtc_state->base.crtc = &intel_crtc->base;
14488
14489         /* initialize shared scalers */
14490         if (INTEL_INFO(dev)->gen >= 9) {
14491                 if (pipe == PIPE_C)
14492                         intel_crtc->num_scalers = 1;
14493                 else
14494                         intel_crtc->num_scalers = SKL_NUM_SCALERS;
14495
14496                 skl_init_scalers(dev, intel_crtc, crtc_state);
14497         }
14498
14499         primary = intel_primary_plane_create(dev, pipe);
14500         if (!primary)
14501                 goto fail;
14502
14503         cursor = intel_cursor_plane_create(dev, pipe);
14504         if (!cursor)
14505                 goto fail;
14506
14507         ret = drm_crtc_init_with_planes(dev, &intel_crtc->base, primary,
14508                                         cursor, &intel_crtc_funcs,
14509                                         "pipe %c", pipe_name(pipe));
14510         if (ret)
14511                 goto fail;
14512
14513         /*
14514          * On gen2/3 only plane A can do fbc, but the panel fitter and lvds port
14515          * is hooked to pipe B. Hence we want plane A feeding pipe B.
14516          */
14517         intel_crtc->pipe = pipe;
14518         intel_crtc->plane = pipe;
14519         if (HAS_FBC(dev) && INTEL_INFO(dev)->gen < 4) {
14520                 DRM_DEBUG_KMS("swapping pipes & planes for FBC\n");
14521                 intel_crtc->plane = !pipe;
14522         }
14523
14524         intel_crtc->cursor_base = ~0;
14525         intel_crtc->cursor_cntl = ~0;
14526         intel_crtc->cursor_size = ~0;
14527
14528         intel_crtc->wm.cxsr_allowed = true;
14529
14530         BUG_ON(pipe >= ARRAY_SIZE(dev_priv->plane_to_crtc_mapping) ||
14531                dev_priv->plane_to_crtc_mapping[intel_crtc->plane] != NULL);
14532         dev_priv->plane_to_crtc_mapping[intel_crtc->plane] = &intel_crtc->base;
14533         dev_priv->pipe_to_crtc_mapping[intel_crtc->pipe] = &intel_crtc->base;
14534
14535         drm_crtc_helper_add(&intel_crtc->base, &intel_helper_funcs);
14536
14537         intel_color_init(&intel_crtc->base);
14538
14539         WARN_ON(drm_crtc_index(&intel_crtc->base) != intel_crtc->pipe);
14540         return;
14541
14542 fail:
14543         intel_plane_destroy(primary);
14544         intel_plane_destroy(cursor);
14545         kfree(crtc_state);
14546         kfree(intel_crtc);
14547 }
14548
14549 enum pipe intel_get_pipe_from_connector(struct intel_connector *connector)
14550 {
14551         struct drm_encoder *encoder = connector->base.encoder;
14552         struct drm_device *dev = connector->base.dev;
14553
14554         WARN_ON(!drm_modeset_is_locked(&dev->mode_config.connection_mutex));
14555
14556         if (!encoder || WARN_ON(!encoder->crtc))
14557                 return INVALID_PIPE;
14558
14559         return to_intel_crtc(encoder->crtc)->pipe;
14560 }
14561
14562 int intel_get_pipe_from_crtc_id(struct drm_device *dev, void *data,
14563                                 struct drm_file *file)
14564 {
14565         struct drm_i915_get_pipe_from_crtc_id *pipe_from_crtc_id = data;
14566         struct drm_crtc *drmmode_crtc;
14567         struct intel_crtc *crtc;
14568
14569         drmmode_crtc = drm_crtc_find(dev, pipe_from_crtc_id->crtc_id);
14570         if (!drmmode_crtc)
14571                 return -ENOENT;
14572
14573         crtc = to_intel_crtc(drmmode_crtc);
14574         pipe_from_crtc_id->pipe = crtc->pipe;
14575
14576         return 0;
14577 }
14578
14579 static int intel_encoder_clones(struct intel_encoder *encoder)
14580 {
14581         struct drm_device *dev = encoder->base.dev;
14582         struct intel_encoder *source_encoder;
14583         int index_mask = 0;
14584         int entry = 0;
14585
14586         for_each_intel_encoder(dev, source_encoder) {
14587                 if (encoders_cloneable(encoder, source_encoder))
14588                         index_mask |= (1 << entry);
14589
14590                 entry++;
14591         }
14592
14593         return index_mask;
14594 }
14595
14596 static bool has_edp_a(struct drm_device *dev)
14597 {
14598         struct drm_i915_private *dev_priv = to_i915(dev);
14599
14600         if (!IS_MOBILE(dev))
14601                 return false;
14602
14603         if ((I915_READ(DP_A) & DP_DETECTED) == 0)
14604                 return false;
14605
14606         if (IS_GEN5(dev) && (I915_READ(FUSE_STRAP) & ILK_eDP_A_DISABLE))
14607                 return false;
14608
14609         return true;
14610 }
14611
14612 static bool intel_crt_present(struct drm_device *dev)
14613 {
14614         struct drm_i915_private *dev_priv = to_i915(dev);
14615
14616         if (INTEL_INFO(dev)->gen >= 9)
14617                 return false;
14618
14619         if (IS_HSW_ULT(dev) || IS_BDW_ULT(dev))
14620                 return false;
14621
14622         if (IS_CHERRYVIEW(dev))
14623                 return false;
14624
14625         if (HAS_PCH_LPT_H(dev) && I915_READ(SFUSE_STRAP) & SFUSE_STRAP_CRT_DISABLED)
14626                 return false;
14627
14628         /* DDI E can't be used if DDI A requires 4 lanes */
14629         if (HAS_DDI(dev) && I915_READ(DDI_BUF_CTL(PORT_A)) & DDI_A_4_LANES)
14630                 return false;
14631
14632         if (!dev_priv->vbt.int_crt_support)
14633                 return false;
14634
14635         return true;
14636 }
14637
14638 static void intel_setup_outputs(struct drm_device *dev)
14639 {
14640         struct drm_i915_private *dev_priv = to_i915(dev);
14641         struct intel_encoder *encoder;
14642         bool dpd_is_edp = false;
14643
14644         /*
14645          * intel_edp_init_connector() depends on this completing first, to
14646          * prevent the registeration of both eDP and LVDS and the incorrect
14647          * sharing of the PPS.
14648          */
14649         intel_lvds_init(dev);
14650
14651         if (intel_crt_present(dev))
14652                 intel_crt_init(dev);
14653
14654         if (IS_BROXTON(dev)) {
14655                 /*
14656                  * FIXME: Broxton doesn't support port detection via the
14657                  * DDI_BUF_CTL_A or SFUSE_STRAP registers, find another way to
14658                  * detect the ports.
14659                  */
14660                 intel_ddi_init(dev, PORT_A);
14661                 intel_ddi_init(dev, PORT_B);
14662                 intel_ddi_init(dev, PORT_C);
14663
14664                 intel_dsi_init(dev);
14665         } else if (HAS_DDI(dev)) {
14666                 int found;
14667
14668                 /*
14669                  * Haswell uses DDI functions to detect digital outputs.
14670                  * On SKL pre-D0 the strap isn't connected, so we assume
14671                  * it's there.
14672                  */
14673                 found = I915_READ(DDI_BUF_CTL(PORT_A)) & DDI_INIT_DISPLAY_DETECTED;
14674                 /* WaIgnoreDDIAStrap: skl */
14675                 if (found || IS_SKYLAKE(dev) || IS_KABYLAKE(dev))
14676                         intel_ddi_init(dev, PORT_A);
14677
14678                 /* DDI B, C and D detection is indicated by the SFUSE_STRAP
14679                  * register */
14680                 found = I915_READ(SFUSE_STRAP);
14681
14682                 if (found & SFUSE_STRAP_DDIB_DETECTED)
14683                         intel_ddi_init(dev, PORT_B);
14684                 if (found & SFUSE_STRAP_DDIC_DETECTED)
14685                         intel_ddi_init(dev, PORT_C);
14686                 if (found & SFUSE_STRAP_DDID_DETECTED)
14687                         intel_ddi_init(dev, PORT_D);
14688                 /*
14689                  * On SKL we don't have a way to detect DDI-E so we rely on VBT.
14690                  */
14691                 if ((IS_SKYLAKE(dev) || IS_KABYLAKE(dev)) &&
14692                     (dev_priv->vbt.ddi_port_info[PORT_E].supports_dp ||
14693                      dev_priv->vbt.ddi_port_info[PORT_E].supports_dvi ||
14694                      dev_priv->vbt.ddi_port_info[PORT_E].supports_hdmi))
14695                         intel_ddi_init(dev, PORT_E);
14696
14697         } else if (HAS_PCH_SPLIT(dev)) {
14698                 int found;
14699                 dpd_is_edp = intel_dp_is_edp(dev, PORT_D);
14700
14701                 if (has_edp_a(dev))
14702                         intel_dp_init(dev, DP_A, PORT_A);
14703
14704                 if (I915_READ(PCH_HDMIB) & SDVO_DETECTED) {
14705                         /* PCH SDVOB multiplex with HDMIB */
14706                         found = intel_sdvo_init(dev, PCH_SDVOB, PORT_B);
14707                         if (!found)
14708                                 intel_hdmi_init(dev, PCH_HDMIB, PORT_B);
14709                         if (!found && (I915_READ(PCH_DP_B) & DP_DETECTED))
14710                                 intel_dp_init(dev, PCH_DP_B, PORT_B);
14711                 }
14712
14713                 if (I915_READ(PCH_HDMIC) & SDVO_DETECTED)
14714                         intel_hdmi_init(dev, PCH_HDMIC, PORT_C);
14715
14716                 if (!dpd_is_edp && I915_READ(PCH_HDMID) & SDVO_DETECTED)
14717                         intel_hdmi_init(dev, PCH_HDMID, PORT_D);
14718
14719                 if (I915_READ(PCH_DP_C) & DP_DETECTED)
14720                         intel_dp_init(dev, PCH_DP_C, PORT_C);
14721
14722                 if (I915_READ(PCH_DP_D) & DP_DETECTED)
14723                         intel_dp_init(dev, PCH_DP_D, PORT_D);
14724         } else if (IS_VALLEYVIEW(dev) || IS_CHERRYVIEW(dev)) {
14725                 bool has_edp, has_port;
14726
14727                 /*
14728                  * The DP_DETECTED bit is the latched state of the DDC
14729                  * SDA pin at boot. However since eDP doesn't require DDC
14730                  * (no way to plug in a DP->HDMI dongle) the DDC pins for
14731                  * eDP ports may have been muxed to an alternate function.
14732                  * Thus we can't rely on the DP_DETECTED bit alone to detect
14733                  * eDP ports. Consult the VBT as well as DP_DETECTED to
14734                  * detect eDP ports.
14735                  *
14736                  * Sadly the straps seem to be missing sometimes even for HDMI
14737                  * ports (eg. on Voyo V3 - CHT x7-Z8700), so check both strap
14738                  * and VBT for the presence of the port. Additionally we can't
14739                  * trust the port type the VBT declares as we've seen at least
14740                  * HDMI ports that the VBT claim are DP or eDP.
14741                  */
14742                 has_edp = intel_dp_is_edp(dev, PORT_B);
14743                 has_port = intel_bios_is_port_present(dev_priv, PORT_B);
14744                 if (I915_READ(VLV_DP_B) & DP_DETECTED || has_port)
14745                         has_edp &= intel_dp_init(dev, VLV_DP_B, PORT_B);
14746                 if ((I915_READ(VLV_HDMIB) & SDVO_DETECTED || has_port) && !has_edp)
14747                         intel_hdmi_init(dev, VLV_HDMIB, PORT_B);
14748
14749                 has_edp = intel_dp_is_edp(dev, PORT_C);
14750                 has_port = intel_bios_is_port_present(dev_priv, PORT_C);
14751                 if (I915_READ(VLV_DP_C) & DP_DETECTED || has_port)
14752                         has_edp &= intel_dp_init(dev, VLV_DP_C, PORT_C);
14753                 if ((I915_READ(VLV_HDMIC) & SDVO_DETECTED || has_port) && !has_edp)
14754                         intel_hdmi_init(dev, VLV_HDMIC, PORT_C);
14755
14756                 if (IS_CHERRYVIEW(dev)) {
14757                         /*
14758                          * eDP not supported on port D,
14759                          * so no need to worry about it
14760                          */
14761                         has_port = intel_bios_is_port_present(dev_priv, PORT_D);
14762                         if (I915_READ(CHV_DP_D) & DP_DETECTED || has_port)
14763                                 intel_dp_init(dev, CHV_DP_D, PORT_D);
14764                         if (I915_READ(CHV_HDMID) & SDVO_DETECTED || has_port)
14765                                 intel_hdmi_init(dev, CHV_HDMID, PORT_D);
14766                 }
14767
14768                 intel_dsi_init(dev);
14769         } else if (!IS_GEN2(dev) && !IS_PINEVIEW(dev)) {
14770                 bool found = false;
14771
14772                 if (I915_READ(GEN3_SDVOB) & SDVO_DETECTED) {
14773                         DRM_DEBUG_KMS("probing SDVOB\n");
14774                         found = intel_sdvo_init(dev, GEN3_SDVOB, PORT_B);
14775                         if (!found && IS_G4X(dev)) {
14776                                 DRM_DEBUG_KMS("probing HDMI on SDVOB\n");
14777                                 intel_hdmi_init(dev, GEN4_HDMIB, PORT_B);
14778                         }
14779
14780                         if (!found && IS_G4X(dev))
14781                                 intel_dp_init(dev, DP_B, PORT_B);
14782                 }
14783
14784                 /* Before G4X SDVOC doesn't have its own detect register */
14785
14786                 if (I915_READ(GEN3_SDVOB) & SDVO_DETECTED) {
14787                         DRM_DEBUG_KMS("probing SDVOC\n");
14788                         found = intel_sdvo_init(dev, GEN3_SDVOC, PORT_C);
14789                 }
14790
14791                 if (!found && (I915_READ(GEN3_SDVOC) & SDVO_DETECTED)) {
14792
14793                         if (IS_G4X(dev)) {
14794                                 DRM_DEBUG_KMS("probing HDMI on SDVOC\n");
14795                                 intel_hdmi_init(dev, GEN4_HDMIC, PORT_C);
14796                         }
14797                         if (IS_G4X(dev))
14798                                 intel_dp_init(dev, DP_C, PORT_C);
14799                 }
14800
14801                 if (IS_G4X(dev) &&
14802                     (I915_READ(DP_D) & DP_DETECTED))
14803                         intel_dp_init(dev, DP_D, PORT_D);
14804         } else if (IS_GEN2(dev))
14805                 intel_dvo_init(dev);
14806
14807         if (SUPPORTS_TV(dev))
14808                 intel_tv_init(dev);
14809
14810         intel_psr_init(dev);
14811
14812         for_each_intel_encoder(dev, encoder) {
14813                 encoder->base.possible_crtcs = encoder->crtc_mask;
14814                 encoder->base.possible_clones =
14815                         intel_encoder_clones(encoder);
14816         }
14817
14818         intel_init_pch_refclk(dev);
14819
14820         drm_helper_move_panel_connectors_to_head(dev);
14821 }
14822
14823 static void intel_user_framebuffer_destroy(struct drm_framebuffer *fb)
14824 {
14825         struct drm_device *dev = fb->dev;
14826         struct intel_framebuffer *intel_fb = to_intel_framebuffer(fb);
14827
14828         drm_framebuffer_cleanup(fb);
14829         mutex_lock(&dev->struct_mutex);
14830         WARN_ON(!intel_fb->obj->framebuffer_references--);
14831         i915_gem_object_put(intel_fb->obj);
14832         mutex_unlock(&dev->struct_mutex);
14833         kfree(intel_fb);
14834 }
14835
14836 static int intel_user_framebuffer_create_handle(struct drm_framebuffer *fb,
14837                                                 struct drm_file *file,
14838                                                 unsigned int *handle)
14839 {
14840         struct intel_framebuffer *intel_fb = to_intel_framebuffer(fb);
14841         struct drm_i915_gem_object *obj = intel_fb->obj;
14842
14843         if (obj->userptr.mm) {
14844                 DRM_DEBUG("attempting to use a userptr for a framebuffer, denied\n");
14845                 return -EINVAL;
14846         }
14847
14848         return drm_gem_handle_create(file, &obj->base, handle);
14849 }
14850
14851 static int intel_user_framebuffer_dirty(struct drm_framebuffer *fb,
14852                                         struct drm_file *file,
14853                                         unsigned flags, unsigned color,
14854                                         struct drm_clip_rect *clips,
14855                                         unsigned num_clips)
14856 {
14857         struct drm_device *dev = fb->dev;
14858         struct intel_framebuffer *intel_fb = to_intel_framebuffer(fb);
14859         struct drm_i915_gem_object *obj = intel_fb->obj;
14860
14861         mutex_lock(&dev->struct_mutex);
14862         intel_fb_obj_flush(obj, false, ORIGIN_DIRTYFB);
14863         mutex_unlock(&dev->struct_mutex);
14864
14865         return 0;
14866 }
14867
14868 static const struct drm_framebuffer_funcs intel_fb_funcs = {
14869         .destroy = intel_user_framebuffer_destroy,
14870         .create_handle = intel_user_framebuffer_create_handle,
14871         .dirty = intel_user_framebuffer_dirty,
14872 };
14873
14874 static
14875 u32 intel_fb_pitch_limit(struct drm_device *dev, uint64_t fb_modifier,
14876                          uint32_t pixel_format)
14877 {
14878         u32 gen = INTEL_INFO(dev)->gen;
14879
14880         if (gen >= 9) {
14881                 int cpp = drm_format_plane_cpp(pixel_format, 0);
14882
14883                 /* "The stride in bytes must not exceed the of the size of 8K
14884                  *  pixels and 32K bytes."
14885                  */
14886                 return min(8192 * cpp, 32768);
14887         } else if (gen >= 5 && !IS_VALLEYVIEW(dev) && !IS_CHERRYVIEW(dev)) {
14888                 return 32*1024;
14889         } else if (gen >= 4) {
14890                 if (fb_modifier == I915_FORMAT_MOD_X_TILED)
14891                         return 16*1024;
14892                 else
14893                         return 32*1024;
14894         } else if (gen >= 3) {
14895                 if (fb_modifier == I915_FORMAT_MOD_X_TILED)
14896                         return 8*1024;
14897                 else
14898                         return 16*1024;
14899         } else {
14900                 /* XXX DSPC is limited to 4k tiled */
14901                 return 8*1024;
14902         }
14903 }
14904
14905 static int intel_framebuffer_init(struct drm_device *dev,
14906                                   struct intel_framebuffer *intel_fb,
14907                                   struct drm_mode_fb_cmd2 *mode_cmd,
14908                                   struct drm_i915_gem_object *obj)
14909 {
14910         struct drm_i915_private *dev_priv = to_i915(dev);
14911         unsigned int aligned_height;
14912         int ret;
14913         u32 pitch_limit, stride_alignment;
14914
14915         WARN_ON(!mutex_is_locked(&dev->struct_mutex));
14916
14917         if (mode_cmd->flags & DRM_MODE_FB_MODIFIERS) {
14918                 /* Enforce that fb modifier and tiling mode match, but only for
14919                  * X-tiled. This is needed for FBC. */
14920                 if (!!(i915_gem_object_get_tiling(obj) == I915_TILING_X) !=
14921                     !!(mode_cmd->modifier[0] == I915_FORMAT_MOD_X_TILED)) {
14922                         DRM_DEBUG("tiling_mode doesn't match fb modifier\n");
14923                         return -EINVAL;
14924                 }
14925         } else {
14926                 if (i915_gem_object_get_tiling(obj) == I915_TILING_X)
14927                         mode_cmd->modifier[0] = I915_FORMAT_MOD_X_TILED;
14928                 else if (i915_gem_object_get_tiling(obj) == I915_TILING_Y) {
14929                         DRM_DEBUG("No Y tiling for legacy addfb\n");
14930                         return -EINVAL;
14931                 }
14932         }
14933
14934         /* Passed in modifier sanity checking. */
14935         switch (mode_cmd->modifier[0]) {
14936         case I915_FORMAT_MOD_Y_TILED:
14937         case I915_FORMAT_MOD_Yf_TILED:
14938                 if (INTEL_INFO(dev)->gen < 9) {
14939                         DRM_DEBUG("Unsupported tiling 0x%llx!\n",
14940                                   mode_cmd->modifier[0]);
14941                         return -EINVAL;
14942                 }
14943         case DRM_FORMAT_MOD_NONE:
14944         case I915_FORMAT_MOD_X_TILED:
14945                 break;
14946         default:
14947                 DRM_DEBUG("Unsupported fb modifier 0x%llx!\n",
14948                           mode_cmd->modifier[0]);
14949                 return -EINVAL;
14950         }
14951
14952         stride_alignment = intel_fb_stride_alignment(dev_priv,
14953                                                      mode_cmd->modifier[0],
14954                                                      mode_cmd->pixel_format);
14955         if (mode_cmd->pitches[0] & (stride_alignment - 1)) {
14956                 DRM_DEBUG("pitch (%d) must be at least %u byte aligned\n",
14957                           mode_cmd->pitches[0], stride_alignment);
14958                 return -EINVAL;
14959         }
14960
14961         pitch_limit = intel_fb_pitch_limit(dev, mode_cmd->modifier[0],
14962                                            mode_cmd->pixel_format);
14963         if (mode_cmd->pitches[0] > pitch_limit) {
14964                 DRM_DEBUG("%s pitch (%u) must be at less than %d\n",
14965                           mode_cmd->modifier[0] != DRM_FORMAT_MOD_NONE ?
14966                           "tiled" : "linear",
14967                           mode_cmd->pitches[0], pitch_limit);
14968                 return -EINVAL;
14969         }
14970
14971         if (mode_cmd->modifier[0] == I915_FORMAT_MOD_X_TILED &&
14972             mode_cmd->pitches[0] != i915_gem_object_get_stride(obj)) {
14973                 DRM_DEBUG("pitch (%d) must match tiling stride (%d)\n",
14974                           mode_cmd->pitches[0],
14975                           i915_gem_object_get_stride(obj));
14976                 return -EINVAL;
14977         }
14978
14979         /* Reject formats not supported by any plane early. */
14980         switch (mode_cmd->pixel_format) {
14981         case DRM_FORMAT_C8:
14982         case DRM_FORMAT_RGB565:
14983         case DRM_FORMAT_XRGB8888:
14984         case DRM_FORMAT_ARGB8888:
14985                 break;
14986         case DRM_FORMAT_XRGB1555:
14987                 if (INTEL_INFO(dev)->gen > 3) {
14988                         DRM_DEBUG("unsupported pixel format: %s\n",
14989                                   drm_get_format_name(mode_cmd->pixel_format));
14990                         return -EINVAL;
14991                 }
14992                 break;
14993         case DRM_FORMAT_ABGR8888:
14994                 if (!IS_VALLEYVIEW(dev) && !IS_CHERRYVIEW(dev) &&
14995                     INTEL_INFO(dev)->gen < 9) {
14996                         DRM_DEBUG("unsupported pixel format: %s\n",
14997                                   drm_get_format_name(mode_cmd->pixel_format));
14998                         return -EINVAL;
14999                 }
15000                 break;
15001         case DRM_FORMAT_XBGR8888:
15002         case DRM_FORMAT_XRGB2101010:
15003         case DRM_FORMAT_XBGR2101010:
15004                 if (INTEL_INFO(dev)->gen < 4) {
15005                         DRM_DEBUG("unsupported pixel format: %s\n",
15006                                   drm_get_format_name(mode_cmd->pixel_format));
15007                         return -EINVAL;
15008                 }
15009                 break;
15010         case DRM_FORMAT_ABGR2101010:
15011                 if (!IS_VALLEYVIEW(dev) && !IS_CHERRYVIEW(dev)) {
15012                         DRM_DEBUG("unsupported pixel format: %s\n",
15013                                   drm_get_format_name(mode_cmd->pixel_format));
15014                         return -EINVAL;
15015                 }
15016                 break;
15017         case DRM_FORMAT_YUYV:
15018         case DRM_FORMAT_UYVY:
15019         case DRM_FORMAT_YVYU:
15020         case DRM_FORMAT_VYUY:
15021                 if (INTEL_INFO(dev)->gen < 5) {
15022                         DRM_DEBUG("unsupported pixel format: %s\n",
15023                                   drm_get_format_name(mode_cmd->pixel_format));
15024                         return -EINVAL;
15025                 }
15026                 break;
15027         default:
15028                 DRM_DEBUG("unsupported pixel format: %s\n",
15029                           drm_get_format_name(mode_cmd->pixel_format));
15030                 return -EINVAL;
15031         }
15032
15033         /* FIXME need to adjust LINOFF/TILEOFF accordingly. */
15034         if (mode_cmd->offsets[0] != 0)
15035                 return -EINVAL;
15036
15037         aligned_height = intel_fb_align_height(dev, mode_cmd->height,
15038                                                mode_cmd->pixel_format,
15039                                                mode_cmd->modifier[0]);
15040         /* FIXME drm helper for size checks (especially planar formats)? */
15041         if (obj->base.size < aligned_height * mode_cmd->pitches[0])
15042                 return -EINVAL;
15043
15044         drm_helper_mode_fill_fb_struct(&intel_fb->base, mode_cmd);
15045         intel_fb->obj = obj;
15046
15047         intel_fill_fb_info(dev_priv, &intel_fb->base);
15048
15049         ret = drm_framebuffer_init(dev, &intel_fb->base, &intel_fb_funcs);
15050         if (ret) {
15051                 DRM_ERROR("framebuffer init failed %d\n", ret);
15052                 return ret;
15053         }
15054
15055         intel_fb->obj->framebuffer_references++;
15056
15057         return 0;
15058 }
15059
15060 static struct drm_framebuffer *
15061 intel_user_framebuffer_create(struct drm_device *dev,
15062                               struct drm_file *filp,
15063                               const struct drm_mode_fb_cmd2 *user_mode_cmd)
15064 {
15065         struct drm_framebuffer *fb;
15066         struct drm_i915_gem_object *obj;
15067         struct drm_mode_fb_cmd2 mode_cmd = *user_mode_cmd;
15068
15069         obj = i915_gem_object_lookup(filp, mode_cmd.handles[0]);
15070         if (!obj)
15071                 return ERR_PTR(-ENOENT);
15072
15073         fb = intel_framebuffer_create(dev, &mode_cmd, obj);
15074         if (IS_ERR(fb))
15075                 i915_gem_object_put_unlocked(obj);
15076
15077         return fb;
15078 }
15079
15080 #ifndef CONFIG_DRM_FBDEV_EMULATION
15081 static inline void intel_fbdev_output_poll_changed(struct drm_device *dev)
15082 {
15083 }
15084 #endif
15085
15086 static const struct drm_mode_config_funcs intel_mode_funcs = {
15087         .fb_create = intel_user_framebuffer_create,
15088         .output_poll_changed = intel_fbdev_output_poll_changed,
15089         .atomic_check = intel_atomic_check,
15090         .atomic_commit = intel_atomic_commit,
15091         .atomic_state_alloc = intel_atomic_state_alloc,
15092         .atomic_state_clear = intel_atomic_state_clear,
15093 };
15094
15095 /**
15096  * intel_init_display_hooks - initialize the display modesetting hooks
15097  * @dev_priv: device private
15098  */
15099 void intel_init_display_hooks(struct drm_i915_private *dev_priv)
15100 {
15101         if (INTEL_INFO(dev_priv)->gen >= 9) {
15102                 dev_priv->display.get_pipe_config = haswell_get_pipe_config;
15103                 dev_priv->display.get_initial_plane_config =
15104                         skylake_get_initial_plane_config;
15105                 dev_priv->display.crtc_compute_clock =
15106                         haswell_crtc_compute_clock;
15107                 dev_priv->display.crtc_enable = haswell_crtc_enable;
15108                 dev_priv->display.crtc_disable = haswell_crtc_disable;
15109         } else if (HAS_DDI(dev_priv)) {
15110                 dev_priv->display.get_pipe_config = haswell_get_pipe_config;
15111                 dev_priv->display.get_initial_plane_config =
15112                         ironlake_get_initial_plane_config;
15113                 dev_priv->display.crtc_compute_clock =
15114                         haswell_crtc_compute_clock;
15115                 dev_priv->display.crtc_enable = haswell_crtc_enable;
15116                 dev_priv->display.crtc_disable = haswell_crtc_disable;
15117         } else if (HAS_PCH_SPLIT(dev_priv)) {
15118                 dev_priv->display.get_pipe_config = ironlake_get_pipe_config;
15119                 dev_priv->display.get_initial_plane_config =
15120                         ironlake_get_initial_plane_config;
15121                 dev_priv->display.crtc_compute_clock =
15122                         ironlake_crtc_compute_clock;
15123                 dev_priv->display.crtc_enable = ironlake_crtc_enable;
15124                 dev_priv->display.crtc_disable = ironlake_crtc_disable;
15125         } else if (IS_CHERRYVIEW(dev_priv)) {
15126                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
15127                 dev_priv->display.get_initial_plane_config =
15128                         i9xx_get_initial_plane_config;
15129                 dev_priv->display.crtc_compute_clock = chv_crtc_compute_clock;
15130                 dev_priv->display.crtc_enable = valleyview_crtc_enable;
15131                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
15132         } else if (IS_VALLEYVIEW(dev_priv)) {
15133                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
15134                 dev_priv->display.get_initial_plane_config =
15135                         i9xx_get_initial_plane_config;
15136                 dev_priv->display.crtc_compute_clock = vlv_crtc_compute_clock;
15137                 dev_priv->display.crtc_enable = valleyview_crtc_enable;
15138                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
15139         } else if (IS_G4X(dev_priv)) {
15140                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
15141                 dev_priv->display.get_initial_plane_config =
15142                         i9xx_get_initial_plane_config;
15143                 dev_priv->display.crtc_compute_clock = g4x_crtc_compute_clock;
15144                 dev_priv->display.crtc_enable = i9xx_crtc_enable;
15145                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
15146         } else if (IS_PINEVIEW(dev_priv)) {
15147                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
15148                 dev_priv->display.get_initial_plane_config =
15149                         i9xx_get_initial_plane_config;
15150                 dev_priv->display.crtc_compute_clock = pnv_crtc_compute_clock;
15151                 dev_priv->display.crtc_enable = i9xx_crtc_enable;
15152                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
15153         } else if (!IS_GEN2(dev_priv)) {
15154                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
15155                 dev_priv->display.get_initial_plane_config =
15156                         i9xx_get_initial_plane_config;
15157                 dev_priv->display.crtc_compute_clock = i9xx_crtc_compute_clock;
15158                 dev_priv->display.crtc_enable = i9xx_crtc_enable;
15159                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
15160         } else {
15161                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
15162                 dev_priv->display.get_initial_plane_config =
15163                         i9xx_get_initial_plane_config;
15164                 dev_priv->display.crtc_compute_clock = i8xx_crtc_compute_clock;
15165                 dev_priv->display.crtc_enable = i9xx_crtc_enable;
15166                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
15167         }
15168
15169         /* Returns the core display clock speed */
15170         if (IS_SKYLAKE(dev_priv) || IS_KABYLAKE(dev_priv))
15171                 dev_priv->display.get_display_clock_speed =
15172                         skylake_get_display_clock_speed;
15173         else if (IS_BROXTON(dev_priv))
15174                 dev_priv->display.get_display_clock_speed =
15175                         broxton_get_display_clock_speed;
15176         else if (IS_BROADWELL(dev_priv))
15177                 dev_priv->display.get_display_clock_speed =
15178                         broadwell_get_display_clock_speed;
15179         else if (IS_HASWELL(dev_priv))
15180                 dev_priv->display.get_display_clock_speed =
15181                         haswell_get_display_clock_speed;
15182         else if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
15183                 dev_priv->display.get_display_clock_speed =
15184                         valleyview_get_display_clock_speed;
15185         else if (IS_GEN5(dev_priv))
15186                 dev_priv->display.get_display_clock_speed =
15187                         ilk_get_display_clock_speed;
15188         else if (IS_I945G(dev_priv) || IS_BROADWATER(dev_priv) ||
15189                  IS_GEN6(dev_priv) || IS_IVYBRIDGE(dev_priv))
15190                 dev_priv->display.get_display_clock_speed =
15191                         i945_get_display_clock_speed;
15192         else if (IS_GM45(dev_priv))
15193                 dev_priv->display.get_display_clock_speed =
15194                         gm45_get_display_clock_speed;
15195         else if (IS_CRESTLINE(dev_priv))
15196                 dev_priv->display.get_display_clock_speed =
15197                         i965gm_get_display_clock_speed;
15198         else if (IS_PINEVIEW(dev_priv))
15199                 dev_priv->display.get_display_clock_speed =
15200                         pnv_get_display_clock_speed;
15201         else if (IS_G33(dev_priv) || IS_G4X(dev_priv))
15202                 dev_priv->display.get_display_clock_speed =
15203                         g33_get_display_clock_speed;
15204         else if (IS_I915G(dev_priv))
15205                 dev_priv->display.get_display_clock_speed =
15206                         i915_get_display_clock_speed;
15207         else if (IS_I945GM(dev_priv) || IS_845G(dev_priv))
15208                 dev_priv->display.get_display_clock_speed =
15209                         i9xx_misc_get_display_clock_speed;
15210         else if (IS_I915GM(dev_priv))
15211                 dev_priv->display.get_display_clock_speed =
15212                         i915gm_get_display_clock_speed;
15213         else if (IS_I865G(dev_priv))
15214                 dev_priv->display.get_display_clock_speed =
15215                         i865_get_display_clock_speed;
15216         else if (IS_I85X(dev_priv))
15217                 dev_priv->display.get_display_clock_speed =
15218                         i85x_get_display_clock_speed;
15219         else { /* 830 */
15220                 WARN(!IS_I830(dev_priv), "Unknown platform. Assuming 133 MHz CDCLK\n");
15221                 dev_priv->display.get_display_clock_speed =
15222                         i830_get_display_clock_speed;
15223         }
15224
15225         if (IS_GEN5(dev_priv)) {
15226                 dev_priv->display.fdi_link_train = ironlake_fdi_link_train;
15227         } else if (IS_GEN6(dev_priv)) {
15228                 dev_priv->display.fdi_link_train = gen6_fdi_link_train;
15229         } else if (IS_IVYBRIDGE(dev_priv)) {
15230                 /* FIXME: detect B0+ stepping and use auto training */
15231                 dev_priv->display.fdi_link_train = ivb_manual_fdi_link_train;
15232         } else if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv)) {
15233                 dev_priv->display.fdi_link_train = hsw_fdi_link_train;
15234         }
15235
15236         if (IS_BROADWELL(dev_priv)) {
15237                 dev_priv->display.modeset_commit_cdclk =
15238                         broadwell_modeset_commit_cdclk;
15239                 dev_priv->display.modeset_calc_cdclk =
15240                         broadwell_modeset_calc_cdclk;
15241         } else if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv)) {
15242                 dev_priv->display.modeset_commit_cdclk =
15243                         valleyview_modeset_commit_cdclk;
15244                 dev_priv->display.modeset_calc_cdclk =
15245                         valleyview_modeset_calc_cdclk;
15246         } else if (IS_BROXTON(dev_priv)) {
15247                 dev_priv->display.modeset_commit_cdclk =
15248                         bxt_modeset_commit_cdclk;
15249                 dev_priv->display.modeset_calc_cdclk =
15250                         bxt_modeset_calc_cdclk;
15251         } else if (IS_SKYLAKE(dev_priv) || IS_KABYLAKE(dev_priv)) {
15252                 dev_priv->display.modeset_commit_cdclk =
15253                         skl_modeset_commit_cdclk;
15254                 dev_priv->display.modeset_calc_cdclk =
15255                         skl_modeset_calc_cdclk;
15256         }
15257
15258         switch (INTEL_INFO(dev_priv)->gen) {
15259         case 2:
15260                 dev_priv->display.queue_flip = intel_gen2_queue_flip;
15261                 break;
15262
15263         case 3:
15264                 dev_priv->display.queue_flip = intel_gen3_queue_flip;
15265                 break;
15266
15267         case 4:
15268         case 5:
15269                 dev_priv->display.queue_flip = intel_gen4_queue_flip;
15270                 break;
15271
15272         case 6:
15273                 dev_priv->display.queue_flip = intel_gen6_queue_flip;
15274                 break;
15275         case 7:
15276         case 8: /* FIXME(BDW): Check that the gen8 RCS flip works. */
15277                 dev_priv->display.queue_flip = intel_gen7_queue_flip;
15278                 break;
15279         case 9:
15280                 /* Drop through - unsupported since execlist only. */
15281         default:
15282                 /* Default just returns -ENODEV to indicate unsupported */
15283                 dev_priv->display.queue_flip = intel_default_queue_flip;
15284         }
15285 }
15286
15287 /*
15288  * Some BIOSes insist on assuming the GPU's pipe A is enabled at suspend,
15289  * resume, or other times.  This quirk makes sure that's the case for
15290  * affected systems.
15291  */
15292 static void quirk_pipea_force(struct drm_device *dev)
15293 {
15294         struct drm_i915_private *dev_priv = to_i915(dev);
15295
15296         dev_priv->quirks |= QUIRK_PIPEA_FORCE;
15297         DRM_INFO("applying pipe a force quirk\n");
15298 }
15299
15300 static void quirk_pipeb_force(struct drm_device *dev)
15301 {
15302         struct drm_i915_private *dev_priv = to_i915(dev);
15303
15304         dev_priv->quirks |= QUIRK_PIPEB_FORCE;
15305         DRM_INFO("applying pipe b force quirk\n");
15306 }
15307
15308 /*
15309  * Some machines (Lenovo U160) do not work with SSC on LVDS for some reason
15310  */
15311 static void quirk_ssc_force_disable(struct drm_device *dev)
15312 {
15313         struct drm_i915_private *dev_priv = to_i915(dev);
15314         dev_priv->quirks |= QUIRK_LVDS_SSC_DISABLE;
15315         DRM_INFO("applying lvds SSC disable quirk\n");
15316 }
15317
15318 /*
15319  * A machine (e.g. Acer Aspire 5734Z) may need to invert the panel backlight
15320  * brightness value
15321  */
15322 static void quirk_invert_brightness(struct drm_device *dev)
15323 {
15324         struct drm_i915_private *dev_priv = to_i915(dev);
15325         dev_priv->quirks |= QUIRK_INVERT_BRIGHTNESS;
15326         DRM_INFO("applying inverted panel brightness quirk\n");
15327 }
15328
15329 /* Some VBT's incorrectly indicate no backlight is present */
15330 static void quirk_backlight_present(struct drm_device *dev)
15331 {
15332         struct drm_i915_private *dev_priv = to_i915(dev);
15333         dev_priv->quirks |= QUIRK_BACKLIGHT_PRESENT;
15334         DRM_INFO("applying backlight present quirk\n");
15335 }
15336
15337 struct intel_quirk {
15338         int device;
15339         int subsystem_vendor;
15340         int subsystem_device;
15341         void (*hook)(struct drm_device *dev);
15342 };
15343
15344 /* For systems that don't have a meaningful PCI subdevice/subvendor ID */
15345 struct intel_dmi_quirk {
15346         void (*hook)(struct drm_device *dev);
15347         const struct dmi_system_id (*dmi_id_list)[];
15348 };
15349
15350 static int intel_dmi_reverse_brightness(const struct dmi_system_id *id)
15351 {
15352         DRM_INFO("Backlight polarity reversed on %s\n", id->ident);
15353         return 1;
15354 }
15355
15356 static const struct intel_dmi_quirk intel_dmi_quirks[] = {
15357         {
15358                 .dmi_id_list = &(const struct dmi_system_id[]) {
15359                         {
15360                                 .callback = intel_dmi_reverse_brightness,
15361                                 .ident = "NCR Corporation",
15362                                 .matches = {DMI_MATCH(DMI_SYS_VENDOR, "NCR Corporation"),
15363                                             DMI_MATCH(DMI_PRODUCT_NAME, ""),
15364                                 },
15365                         },
15366                         { }  /* terminating entry */
15367                 },
15368                 .hook = quirk_invert_brightness,
15369         },
15370 };
15371
15372 static struct intel_quirk intel_quirks[] = {
15373         /* Toshiba Protege R-205, S-209 needs pipe A force quirk */
15374         { 0x2592, 0x1179, 0x0001, quirk_pipea_force },
15375
15376         /* ThinkPad T60 needs pipe A force quirk (bug #16494) */
15377         { 0x2782, 0x17aa, 0x201a, quirk_pipea_force },
15378
15379         /* 830 needs to leave pipe A & dpll A up */
15380         { 0x3577, PCI_ANY_ID, PCI_ANY_ID, quirk_pipea_force },
15381
15382         /* 830 needs to leave pipe B & dpll B up */
15383         { 0x3577, PCI_ANY_ID, PCI_ANY_ID, quirk_pipeb_force },
15384
15385         /* Lenovo U160 cannot use SSC on LVDS */
15386         { 0x0046, 0x17aa, 0x3920, quirk_ssc_force_disable },
15387
15388         /* Sony Vaio Y cannot use SSC on LVDS */
15389         { 0x0046, 0x104d, 0x9076, quirk_ssc_force_disable },
15390
15391         /* Acer Aspire 5734Z must invert backlight brightness */
15392         { 0x2a42, 0x1025, 0x0459, quirk_invert_brightness },
15393
15394         /* Acer/eMachines G725 */
15395         { 0x2a42, 0x1025, 0x0210, quirk_invert_brightness },
15396
15397         /* Acer/eMachines e725 */
15398         { 0x2a42, 0x1025, 0x0212, quirk_invert_brightness },
15399
15400         /* Acer/Packard Bell NCL20 */
15401         { 0x2a42, 0x1025, 0x034b, quirk_invert_brightness },
15402
15403         /* Acer Aspire 4736Z */
15404         { 0x2a42, 0x1025, 0x0260, quirk_invert_brightness },
15405
15406         /* Acer Aspire 5336 */
15407         { 0x2a42, 0x1025, 0x048a, quirk_invert_brightness },
15408
15409         /* Acer C720 and C720P Chromebooks (Celeron 2955U) have backlights */
15410         { 0x0a06, 0x1025, 0x0a11, quirk_backlight_present },
15411
15412         /* Acer C720 Chromebook (Core i3 4005U) */
15413         { 0x0a16, 0x1025, 0x0a11, quirk_backlight_present },
15414
15415         /* Apple Macbook 2,1 (Core 2 T7400) */
15416         { 0x27a2, 0x8086, 0x7270, quirk_backlight_present },
15417
15418         /* Apple Macbook 4,1 */
15419         { 0x2a02, 0x106b, 0x00a1, quirk_backlight_present },
15420
15421         /* Toshiba CB35 Chromebook (Celeron 2955U) */
15422         { 0x0a06, 0x1179, 0x0a88, quirk_backlight_present },
15423
15424         /* HP Chromebook 14 (Celeron 2955U) */
15425         { 0x0a06, 0x103c, 0x21ed, quirk_backlight_present },
15426
15427         /* Dell Chromebook 11 */
15428         { 0x0a06, 0x1028, 0x0a35, quirk_backlight_present },
15429
15430         /* Dell Chromebook 11 (2015 version) */
15431         { 0x0a16, 0x1028, 0x0a35, quirk_backlight_present },
15432 };
15433
15434 static void intel_init_quirks(struct drm_device *dev)
15435 {
15436         struct pci_dev *d = dev->pdev;
15437         int i;
15438
15439         for (i = 0; i < ARRAY_SIZE(intel_quirks); i++) {
15440                 struct intel_quirk *q = &intel_quirks[i];
15441
15442                 if (d->device == q->device &&
15443                     (d->subsystem_vendor == q->subsystem_vendor ||
15444                      q->subsystem_vendor == PCI_ANY_ID) &&
15445                     (d->subsystem_device == q->subsystem_device ||
15446                      q->subsystem_device == PCI_ANY_ID))
15447                         q->hook(dev);
15448         }
15449         for (i = 0; i < ARRAY_SIZE(intel_dmi_quirks); i++) {
15450                 if (dmi_check_system(*intel_dmi_quirks[i].dmi_id_list) != 0)
15451                         intel_dmi_quirks[i].hook(dev);
15452         }
15453 }
15454
15455 /* Disable the VGA plane that we never use */
15456 static void i915_disable_vga(struct drm_device *dev)
15457 {
15458         struct drm_i915_private *dev_priv = to_i915(dev);
15459         u8 sr1;
15460         i915_reg_t vga_reg = i915_vgacntrl_reg(dev);
15461
15462         /* WaEnableVGAAccessThroughIOPort:ctg,elk,ilk,snb,ivb,vlv,hsw */
15463         vga_get_uninterruptible(dev->pdev, VGA_RSRC_LEGACY_IO);
15464         outb(SR01, VGA_SR_INDEX);
15465         sr1 = inb(VGA_SR_DATA);
15466         outb(sr1 | 1<<5, VGA_SR_DATA);
15467         vga_put(dev->pdev, VGA_RSRC_LEGACY_IO);
15468         udelay(300);
15469
15470         I915_WRITE(vga_reg, VGA_DISP_DISABLE);
15471         POSTING_READ(vga_reg);
15472 }
15473
15474 void intel_modeset_init_hw(struct drm_device *dev)
15475 {
15476         struct drm_i915_private *dev_priv = to_i915(dev);
15477
15478         intel_update_cdclk(dev);
15479
15480         dev_priv->atomic_cdclk_freq = dev_priv->cdclk_freq;
15481
15482         intel_init_clock_gating(dev);
15483 }
15484
15485 /*
15486  * Calculate what we think the watermarks should be for the state we've read
15487  * out of the hardware and then immediately program those watermarks so that
15488  * we ensure the hardware settings match our internal state.
15489  *
15490  * We can calculate what we think WM's should be by creating a duplicate of the
15491  * current state (which was constructed during hardware readout) and running it
15492  * through the atomic check code to calculate new watermark values in the
15493  * state object.
15494  */
15495 static void sanitize_watermarks(struct drm_device *dev)
15496 {
15497         struct drm_i915_private *dev_priv = to_i915(dev);
15498         struct drm_atomic_state *state;
15499         struct drm_crtc *crtc;
15500         struct drm_crtc_state *cstate;
15501         struct drm_modeset_acquire_ctx ctx;
15502         int ret;
15503         int i;
15504
15505         /* Only supported on platforms that use atomic watermark design */
15506         if (!dev_priv->display.optimize_watermarks)
15507                 return;
15508
15509         /*
15510          * We need to hold connection_mutex before calling duplicate_state so
15511          * that the connector loop is protected.
15512          */
15513         drm_modeset_acquire_init(&ctx, 0);
15514 retry:
15515         ret = drm_modeset_lock_all_ctx(dev, &ctx);
15516         if (ret == -EDEADLK) {
15517                 drm_modeset_backoff(&ctx);
15518                 goto retry;
15519         } else if (WARN_ON(ret)) {
15520                 goto fail;
15521         }
15522
15523         state = drm_atomic_helper_duplicate_state(dev, &ctx);
15524         if (WARN_ON(IS_ERR(state)))
15525                 goto fail;
15526
15527         /*
15528          * Hardware readout is the only time we don't want to calculate
15529          * intermediate watermarks (since we don't trust the current
15530          * watermarks).
15531          */
15532         to_intel_atomic_state(state)->skip_intermediate_wm = true;
15533
15534         ret = intel_atomic_check(dev, state);
15535         if (ret) {
15536                 /*
15537                  * If we fail here, it means that the hardware appears to be
15538                  * programmed in a way that shouldn't be possible, given our
15539                  * understanding of watermark requirements.  This might mean a
15540                  * mistake in the hardware readout code or a mistake in the
15541                  * watermark calculations for a given platform.  Raise a WARN
15542                  * so that this is noticeable.
15543                  *
15544                  * If this actually happens, we'll have to just leave the
15545                  * BIOS-programmed watermarks untouched and hope for the best.
15546                  */
15547                 WARN(true, "Could not determine valid watermarks for inherited state\n");
15548                 goto fail;
15549         }
15550
15551         /* Write calculated watermark values back */
15552         for_each_crtc_in_state(state, crtc, cstate, i) {
15553                 struct intel_crtc_state *cs = to_intel_crtc_state(cstate);
15554
15555                 cs->wm.need_postvbl_update = true;
15556                 dev_priv->display.optimize_watermarks(cs);
15557         }
15558
15559         drm_atomic_state_free(state);
15560 fail:
15561         drm_modeset_drop_locks(&ctx);
15562         drm_modeset_acquire_fini(&ctx);
15563 }
15564
15565 void intel_modeset_init(struct drm_device *dev)
15566 {
15567         struct drm_i915_private *dev_priv = to_i915(dev);
15568         struct i915_ggtt *ggtt = &dev_priv->ggtt;
15569         int sprite, ret;
15570         enum pipe pipe;
15571         struct intel_crtc *crtc;
15572
15573         drm_mode_config_init(dev);
15574
15575         dev->mode_config.min_width = 0;
15576         dev->mode_config.min_height = 0;
15577
15578         dev->mode_config.preferred_depth = 24;
15579         dev->mode_config.prefer_shadow = 1;
15580
15581         dev->mode_config.allow_fb_modifiers = true;
15582
15583         dev->mode_config.funcs = &intel_mode_funcs;
15584
15585         intel_init_quirks(dev);
15586
15587         intel_init_pm(dev);
15588
15589         if (INTEL_INFO(dev)->num_pipes == 0)
15590                 return;
15591
15592         /*
15593          * There may be no VBT; and if the BIOS enabled SSC we can
15594          * just keep using it to avoid unnecessary flicker.  Whereas if the
15595          * BIOS isn't using it, don't assume it will work even if the VBT
15596          * indicates as much.
15597          */
15598         if (HAS_PCH_IBX(dev) || HAS_PCH_CPT(dev)) {
15599                 bool bios_lvds_use_ssc = !!(I915_READ(PCH_DREF_CONTROL) &
15600                                             DREF_SSC1_ENABLE);
15601
15602                 if (dev_priv->vbt.lvds_use_ssc != bios_lvds_use_ssc) {
15603                         DRM_DEBUG_KMS("SSC %sabled by BIOS, overriding VBT which says %sabled\n",
15604                                      bios_lvds_use_ssc ? "en" : "dis",
15605                                      dev_priv->vbt.lvds_use_ssc ? "en" : "dis");
15606                         dev_priv->vbt.lvds_use_ssc = bios_lvds_use_ssc;
15607                 }
15608         }
15609
15610         if (IS_GEN2(dev)) {
15611                 dev->mode_config.max_width = 2048;
15612                 dev->mode_config.max_height = 2048;
15613         } else if (IS_GEN3(dev)) {
15614                 dev->mode_config.max_width = 4096;
15615                 dev->mode_config.max_height = 4096;
15616         } else {
15617                 dev->mode_config.max_width = 8192;
15618                 dev->mode_config.max_height = 8192;
15619         }
15620
15621         if (IS_845G(dev) || IS_I865G(dev)) {
15622                 dev->mode_config.cursor_width = IS_845G(dev) ? 64 : 512;
15623                 dev->mode_config.cursor_height = 1023;
15624         } else if (IS_GEN2(dev)) {
15625                 dev->mode_config.cursor_width = GEN2_CURSOR_WIDTH;
15626                 dev->mode_config.cursor_height = GEN2_CURSOR_HEIGHT;
15627         } else {
15628                 dev->mode_config.cursor_width = MAX_CURSOR_WIDTH;
15629                 dev->mode_config.cursor_height = MAX_CURSOR_HEIGHT;
15630         }
15631
15632         dev->mode_config.fb_base = ggtt->mappable_base;
15633
15634         DRM_DEBUG_KMS("%d display pipe%s available.\n",
15635                       INTEL_INFO(dev)->num_pipes,
15636                       INTEL_INFO(dev)->num_pipes > 1 ? "s" : "");
15637
15638         for_each_pipe(dev_priv, pipe) {
15639                 intel_crtc_init(dev, pipe);
15640                 for_each_sprite(dev_priv, pipe, sprite) {
15641                         ret = intel_plane_init(dev, pipe, sprite);
15642                         if (ret)
15643                                 DRM_DEBUG_KMS("pipe %c sprite %c init failed: %d\n",
15644                                               pipe_name(pipe), sprite_name(pipe, sprite), ret);
15645                 }
15646         }
15647
15648         intel_update_czclk(dev_priv);
15649         intel_update_cdclk(dev);
15650
15651         intel_shared_dpll_init(dev);
15652
15653         if (dev_priv->max_cdclk_freq == 0)
15654                 intel_update_max_cdclk(dev);
15655
15656         /* Just disable it once at startup */
15657         i915_disable_vga(dev);
15658         intel_setup_outputs(dev);
15659
15660         drm_modeset_lock_all(dev);
15661         intel_modeset_setup_hw_state(dev);
15662         drm_modeset_unlock_all(dev);
15663
15664         for_each_intel_crtc(dev, crtc) {
15665                 struct intel_initial_plane_config plane_config = {};
15666
15667                 if (!crtc->active)
15668                         continue;
15669
15670                 /*
15671                  * Note that reserving the BIOS fb up front prevents us
15672                  * from stuffing other stolen allocations like the ring
15673                  * on top.  This prevents some ugliness at boot time, and
15674                  * can even allow for smooth boot transitions if the BIOS
15675                  * fb is large enough for the active pipe configuration.
15676                  */
15677                 dev_priv->display.get_initial_plane_config(crtc,
15678                                                            &plane_config);
15679
15680                 /*
15681                  * If the fb is shared between multiple heads, we'll
15682                  * just get the first one.
15683                  */
15684                 intel_find_initial_plane_obj(crtc, &plane_config);
15685         }
15686
15687         /*
15688          * Make sure hardware watermarks really match the state we read out.
15689          * Note that we need to do this after reconstructing the BIOS fb's
15690          * since the watermark calculation done here will use pstate->fb.
15691          */
15692         sanitize_watermarks(dev);
15693 }
15694
15695 static void intel_enable_pipe_a(struct drm_device *dev)
15696 {
15697         struct intel_connector *connector;
15698         struct drm_connector *crt = NULL;
15699         struct intel_load_detect_pipe load_detect_temp;
15700         struct drm_modeset_acquire_ctx *ctx = dev->mode_config.acquire_ctx;
15701
15702         /* We can't just switch on the pipe A, we need to set things up with a
15703          * proper mode and output configuration. As a gross hack, enable pipe A
15704          * by enabling the load detect pipe once. */
15705         for_each_intel_connector(dev, connector) {
15706                 if (connector->encoder->type == INTEL_OUTPUT_ANALOG) {
15707                         crt = &connector->base;
15708                         break;
15709                 }
15710         }
15711
15712         if (!crt)
15713                 return;
15714
15715         if (intel_get_load_detect_pipe(crt, NULL, &load_detect_temp, ctx))
15716                 intel_release_load_detect_pipe(crt, &load_detect_temp, ctx);
15717 }
15718
15719 static bool
15720 intel_check_plane_mapping(struct intel_crtc *crtc)
15721 {
15722         struct drm_device *dev = crtc->base.dev;
15723         struct drm_i915_private *dev_priv = to_i915(dev);
15724         u32 val;
15725
15726         if (INTEL_INFO(dev)->num_pipes == 1)
15727                 return true;
15728
15729         val = I915_READ(DSPCNTR(!crtc->plane));
15730
15731         if ((val & DISPLAY_PLANE_ENABLE) &&
15732             (!!(val & DISPPLANE_SEL_PIPE_MASK) == crtc->pipe))
15733                 return false;
15734
15735         return true;
15736 }
15737
15738 static bool intel_crtc_has_encoders(struct intel_crtc *crtc)
15739 {
15740         struct drm_device *dev = crtc->base.dev;
15741         struct intel_encoder *encoder;
15742
15743         for_each_encoder_on_crtc(dev, &crtc->base, encoder)
15744                 return true;
15745
15746         return false;
15747 }
15748
15749 static bool intel_encoder_has_connectors(struct intel_encoder *encoder)
15750 {
15751         struct drm_device *dev = encoder->base.dev;
15752         struct intel_connector *connector;
15753
15754         for_each_connector_on_encoder(dev, &encoder->base, connector)
15755                 return true;
15756
15757         return false;
15758 }
15759
15760 static void intel_sanitize_crtc(struct intel_crtc *crtc)
15761 {
15762         struct drm_device *dev = crtc->base.dev;
15763         struct drm_i915_private *dev_priv = to_i915(dev);
15764         enum transcoder cpu_transcoder = crtc->config->cpu_transcoder;
15765
15766         /* Clear any frame start delays used for debugging left by the BIOS */
15767         if (!transcoder_is_dsi(cpu_transcoder)) {
15768                 i915_reg_t reg = PIPECONF(cpu_transcoder);
15769
15770                 I915_WRITE(reg,
15771                            I915_READ(reg) & ~PIPECONF_FRAME_START_DELAY_MASK);
15772         }
15773
15774         /* restore vblank interrupts to correct state */
15775         drm_crtc_vblank_reset(&crtc->base);
15776         if (crtc->active) {
15777                 struct intel_plane *plane;
15778
15779                 drm_crtc_vblank_on(&crtc->base);
15780
15781                 /* Disable everything but the primary plane */
15782                 for_each_intel_plane_on_crtc(dev, crtc, plane) {
15783                         if (plane->base.type == DRM_PLANE_TYPE_PRIMARY)
15784                                 continue;
15785
15786                         plane->disable_plane(&plane->base, &crtc->base);
15787                 }
15788         }
15789
15790         /* We need to sanitize the plane -> pipe mapping first because this will
15791          * disable the crtc (and hence change the state) if it is wrong. Note
15792          * that gen4+ has a fixed plane -> pipe mapping.  */
15793         if (INTEL_INFO(dev)->gen < 4 && !intel_check_plane_mapping(crtc)) {
15794                 bool plane;
15795
15796                 DRM_DEBUG_KMS("[CRTC:%d:%s] wrong plane connection detected!\n",
15797                               crtc->base.base.id, crtc->base.name);
15798
15799                 /* Pipe has the wrong plane attached and the plane is active.
15800                  * Temporarily change the plane mapping and disable everything
15801                  * ...  */
15802                 plane = crtc->plane;
15803                 to_intel_plane_state(crtc->base.primary->state)->base.visible = true;
15804                 crtc->plane = !plane;
15805                 intel_crtc_disable_noatomic(&crtc->base);
15806                 crtc->plane = plane;
15807         }
15808
15809         if (dev_priv->quirks & QUIRK_PIPEA_FORCE &&
15810             crtc->pipe == PIPE_A && !crtc->active) {
15811                 /* BIOS forgot to enable pipe A, this mostly happens after
15812                  * resume. Force-enable the pipe to fix this, the update_dpms
15813                  * call below we restore the pipe to the right state, but leave
15814                  * the required bits on. */
15815                 intel_enable_pipe_a(dev);
15816         }
15817
15818         /* Adjust the state of the output pipe according to whether we
15819          * have active connectors/encoders. */
15820         if (crtc->active && !intel_crtc_has_encoders(crtc))
15821                 intel_crtc_disable_noatomic(&crtc->base);
15822
15823         if (crtc->active || HAS_GMCH_DISPLAY(dev)) {
15824                 /*
15825                  * We start out with underrun reporting disabled to avoid races.
15826                  * For correct bookkeeping mark this on active crtcs.
15827                  *
15828                  * Also on gmch platforms we dont have any hardware bits to
15829                  * disable the underrun reporting. Which means we need to start
15830                  * out with underrun reporting disabled also on inactive pipes,
15831                  * since otherwise we'll complain about the garbage we read when
15832                  * e.g. coming up after runtime pm.
15833                  *
15834                  * No protection against concurrent access is required - at
15835                  * worst a fifo underrun happens which also sets this to false.
15836                  */
15837                 crtc->cpu_fifo_underrun_disabled = true;
15838                 crtc->pch_fifo_underrun_disabled = true;
15839         }
15840 }
15841
15842 static void intel_sanitize_encoder(struct intel_encoder *encoder)
15843 {
15844         struct intel_connector *connector;
15845         struct drm_device *dev = encoder->base.dev;
15846
15847         /* We need to check both for a crtc link (meaning that the
15848          * encoder is active and trying to read from a pipe) and the
15849          * pipe itself being active. */
15850         bool has_active_crtc = encoder->base.crtc &&
15851                 to_intel_crtc(encoder->base.crtc)->active;
15852
15853         if (intel_encoder_has_connectors(encoder) && !has_active_crtc) {
15854                 DRM_DEBUG_KMS("[ENCODER:%d:%s] has active connectors but no active pipe!\n",
15855                               encoder->base.base.id,
15856                               encoder->base.name);
15857
15858                 /* Connector is active, but has no active pipe. This is
15859                  * fallout from our resume register restoring. Disable
15860                  * the encoder manually again. */
15861                 if (encoder->base.crtc) {
15862                         DRM_DEBUG_KMS("[ENCODER:%d:%s] manually disabled\n",
15863                                       encoder->base.base.id,
15864                                       encoder->base.name);
15865                         encoder->disable(encoder);
15866                         if (encoder->post_disable)
15867                                 encoder->post_disable(encoder);
15868                 }
15869                 encoder->base.crtc = NULL;
15870
15871                 /* Inconsistent output/port/pipe state happens presumably due to
15872                  * a bug in one of the get_hw_state functions. Or someplace else
15873                  * in our code, like the register restore mess on resume. Clamp
15874                  * things to off as a safer default. */
15875                 for_each_intel_connector(dev, connector) {
15876                         if (connector->encoder != encoder)
15877                                 continue;
15878                         connector->base.dpms = DRM_MODE_DPMS_OFF;
15879                         connector->base.encoder = NULL;
15880                 }
15881         }
15882         /* Enabled encoders without active connectors will be fixed in
15883          * the crtc fixup. */
15884 }
15885
15886 void i915_redisable_vga_power_on(struct drm_device *dev)
15887 {
15888         struct drm_i915_private *dev_priv = to_i915(dev);
15889         i915_reg_t vga_reg = i915_vgacntrl_reg(dev);
15890
15891         if (!(I915_READ(vga_reg) & VGA_DISP_DISABLE)) {
15892                 DRM_DEBUG_KMS("Something enabled VGA plane, disabling it\n");
15893                 i915_disable_vga(dev);
15894         }
15895 }
15896
15897 void i915_redisable_vga(struct drm_device *dev)
15898 {
15899         struct drm_i915_private *dev_priv = to_i915(dev);
15900
15901         /* This function can be called both from intel_modeset_setup_hw_state or
15902          * at a very early point in our resume sequence, where the power well
15903          * structures are not yet restored. Since this function is at a very
15904          * paranoid "someone might have enabled VGA while we were not looking"
15905          * level, just check if the power well is enabled instead of trying to
15906          * follow the "don't touch the power well if we don't need it" policy
15907          * the rest of the driver uses. */
15908         if (!intel_display_power_get_if_enabled(dev_priv, POWER_DOMAIN_VGA))
15909                 return;
15910
15911         i915_redisable_vga_power_on(dev);
15912
15913         intel_display_power_put(dev_priv, POWER_DOMAIN_VGA);
15914 }
15915
15916 static bool primary_get_hw_state(struct intel_plane *plane)
15917 {
15918         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
15919
15920         return I915_READ(DSPCNTR(plane->plane)) & DISPLAY_PLANE_ENABLE;
15921 }
15922
15923 /* FIXME read out full plane state for all planes */
15924 static void readout_plane_state(struct intel_crtc *crtc)
15925 {
15926         struct drm_plane *primary = crtc->base.primary;
15927         struct intel_plane_state *plane_state =
15928                 to_intel_plane_state(primary->state);
15929
15930         plane_state->base.visible = crtc->active &&
15931                 primary_get_hw_state(to_intel_plane(primary));
15932
15933         if (plane_state->base.visible)
15934                 crtc->base.state->plane_mask |= 1 << drm_plane_index(primary);
15935 }
15936
15937 static void intel_modeset_readout_hw_state(struct drm_device *dev)
15938 {
15939         struct drm_i915_private *dev_priv = to_i915(dev);
15940         enum pipe pipe;
15941         struct intel_crtc *crtc;
15942         struct intel_encoder *encoder;
15943         struct intel_connector *connector;
15944         int i;
15945
15946         dev_priv->active_crtcs = 0;
15947
15948         for_each_intel_crtc(dev, crtc) {
15949                 struct intel_crtc_state *crtc_state = crtc->config;
15950                 int pixclk = 0;
15951
15952                 __drm_atomic_helper_crtc_destroy_state(&crtc_state->base);
15953                 memset(crtc_state, 0, sizeof(*crtc_state));
15954                 crtc_state->base.crtc = &crtc->base;
15955
15956                 crtc_state->base.active = crtc_state->base.enable =
15957                         dev_priv->display.get_pipe_config(crtc, crtc_state);
15958
15959                 crtc->base.enabled = crtc_state->base.enable;
15960                 crtc->active = crtc_state->base.active;
15961
15962                 if (crtc_state->base.active) {
15963                         dev_priv->active_crtcs |= 1 << crtc->pipe;
15964
15965                         if (INTEL_GEN(dev_priv) >= 9 || IS_BROADWELL(dev_priv))
15966                                 pixclk = ilk_pipe_pixel_rate(crtc_state);
15967                         else if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
15968                                 pixclk = crtc_state->base.adjusted_mode.crtc_clock;
15969                         else
15970                                 WARN_ON(dev_priv->display.modeset_calc_cdclk);
15971
15972                         /* pixel rate mustn't exceed 95% of cdclk with IPS on BDW */
15973                         if (IS_BROADWELL(dev_priv) && crtc_state->ips_enabled)
15974                                 pixclk = DIV_ROUND_UP(pixclk * 100, 95);
15975                 }
15976
15977                 dev_priv->min_pixclk[crtc->pipe] = pixclk;
15978
15979                 readout_plane_state(crtc);
15980
15981                 DRM_DEBUG_KMS("[CRTC:%d:%s] hw state readout: %s\n",
15982                               crtc->base.base.id, crtc->base.name,
15983                               crtc->active ? "enabled" : "disabled");
15984         }
15985
15986         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
15987                 struct intel_shared_dpll *pll = &dev_priv->shared_dplls[i];
15988
15989                 pll->on = pll->funcs.get_hw_state(dev_priv, pll,
15990                                                   &pll->config.hw_state);
15991                 pll->config.crtc_mask = 0;
15992                 for_each_intel_crtc(dev, crtc) {
15993                         if (crtc->active && crtc->config->shared_dpll == pll)
15994                                 pll->config.crtc_mask |= 1 << crtc->pipe;
15995                 }
15996                 pll->active_mask = pll->config.crtc_mask;
15997
15998                 DRM_DEBUG_KMS("%s hw state readout: crtc_mask 0x%08x, on %i\n",
15999                               pll->name, pll->config.crtc_mask, pll->on);
16000         }
16001
16002         for_each_intel_encoder(dev, encoder) {
16003                 pipe = 0;
16004
16005                 if (encoder->get_hw_state(encoder, &pipe)) {
16006                         crtc = to_intel_crtc(dev_priv->pipe_to_crtc_mapping[pipe]);
16007                         encoder->base.crtc = &crtc->base;
16008                         crtc->config->output_types |= 1 << encoder->type;
16009                         encoder->get_config(encoder, crtc->config);
16010                 } else {
16011                         encoder->base.crtc = NULL;
16012                 }
16013
16014                 DRM_DEBUG_KMS("[ENCODER:%d:%s] hw state readout: %s, pipe %c\n",
16015                               encoder->base.base.id,
16016                               encoder->base.name,
16017                               encoder->base.crtc ? "enabled" : "disabled",
16018                               pipe_name(pipe));
16019         }
16020
16021         for_each_intel_connector(dev, connector) {
16022                 if (connector->get_hw_state(connector)) {
16023                         connector->base.dpms = DRM_MODE_DPMS_ON;
16024
16025                         encoder = connector->encoder;
16026                         connector->base.encoder = &encoder->base;
16027
16028                         if (encoder->base.crtc &&
16029                             encoder->base.crtc->state->active) {
16030                                 /*
16031                                  * This has to be done during hardware readout
16032                                  * because anything calling .crtc_disable may
16033                                  * rely on the connector_mask being accurate.
16034                                  */
16035                                 encoder->base.crtc->state->connector_mask |=
16036                                         1 << drm_connector_index(&connector->base);
16037                                 encoder->base.crtc->state->encoder_mask |=
16038                                         1 << drm_encoder_index(&encoder->base);
16039                         }
16040
16041                 } else {
16042                         connector->base.dpms = DRM_MODE_DPMS_OFF;
16043                         connector->base.encoder = NULL;
16044                 }
16045                 DRM_DEBUG_KMS("[CONNECTOR:%d:%s] hw state readout: %s\n",
16046                               connector->base.base.id,
16047                               connector->base.name,
16048                               connector->base.encoder ? "enabled" : "disabled");
16049         }
16050
16051         for_each_intel_crtc(dev, crtc) {
16052                 crtc->base.hwmode = crtc->config->base.adjusted_mode;
16053
16054                 memset(&crtc->base.mode, 0, sizeof(crtc->base.mode));
16055                 if (crtc->base.state->active) {
16056                         intel_mode_from_pipe_config(&crtc->base.mode, crtc->config);
16057                         intel_mode_from_pipe_config(&crtc->base.state->adjusted_mode, crtc->config);
16058                         WARN_ON(drm_atomic_set_mode_for_crtc(crtc->base.state, &crtc->base.mode));
16059
16060                         /*
16061                          * The initial mode needs to be set in order to keep
16062                          * the atomic core happy. It wants a valid mode if the
16063                          * crtc's enabled, so we do the above call.
16064                          *
16065                          * At this point some state updated by the connectors
16066                          * in their ->detect() callback has not run yet, so
16067                          * no recalculation can be done yet.
16068                          *
16069                          * Even if we could do a recalculation and modeset
16070                          * right now it would cause a double modeset if
16071                          * fbdev or userspace chooses a different initial mode.
16072                          *
16073                          * If that happens, someone indicated they wanted a
16074                          * mode change, which means it's safe to do a full
16075                          * recalculation.
16076                          */
16077                         crtc->base.state->mode.private_flags = I915_MODE_FLAG_INHERITED;
16078
16079                         drm_calc_timestamping_constants(&crtc->base, &crtc->base.hwmode);
16080                         update_scanline_offset(crtc);
16081                 }
16082
16083                 intel_pipe_config_sanity_check(dev_priv, crtc->config);
16084         }
16085 }
16086
16087 /* Scan out the current hw modeset state,
16088  * and sanitizes it to the current state
16089  */
16090 static void
16091 intel_modeset_setup_hw_state(struct drm_device *dev)
16092 {
16093         struct drm_i915_private *dev_priv = to_i915(dev);
16094         enum pipe pipe;
16095         struct intel_crtc *crtc;
16096         struct intel_encoder *encoder;
16097         int i;
16098
16099         intel_modeset_readout_hw_state(dev);
16100
16101         /* HW state is read out, now we need to sanitize this mess. */
16102         for_each_intel_encoder(dev, encoder) {
16103                 intel_sanitize_encoder(encoder);
16104         }
16105
16106         for_each_pipe(dev_priv, pipe) {
16107                 crtc = to_intel_crtc(dev_priv->pipe_to_crtc_mapping[pipe]);
16108                 intel_sanitize_crtc(crtc);
16109                 intel_dump_pipe_config(crtc, crtc->config,
16110                                        "[setup_hw_state]");
16111         }
16112
16113         intel_modeset_update_connector_atomic_state(dev);
16114
16115         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
16116                 struct intel_shared_dpll *pll = &dev_priv->shared_dplls[i];
16117
16118                 if (!pll->on || pll->active_mask)
16119                         continue;
16120
16121                 DRM_DEBUG_KMS("%s enabled but not in use, disabling\n", pll->name);
16122
16123                 pll->funcs.disable(dev_priv, pll);
16124                 pll->on = false;
16125         }
16126
16127         if (IS_VALLEYVIEW(dev) || IS_CHERRYVIEW(dev))
16128                 vlv_wm_get_hw_state(dev);
16129         else if (IS_GEN9(dev))
16130                 skl_wm_get_hw_state(dev);
16131         else if (HAS_PCH_SPLIT(dev))
16132                 ilk_wm_get_hw_state(dev);
16133
16134         for_each_intel_crtc(dev, crtc) {
16135                 unsigned long put_domains;
16136
16137                 put_domains = modeset_get_crtc_power_domains(&crtc->base, crtc->config);
16138                 if (WARN_ON(put_domains))
16139                         modeset_put_power_domains(dev_priv, put_domains);
16140         }
16141         intel_display_set_init_power(dev_priv, false);
16142
16143         intel_fbc_init_pipe_state(dev_priv);
16144 }
16145
16146 void intel_display_resume(struct drm_device *dev)
16147 {
16148         struct drm_i915_private *dev_priv = to_i915(dev);
16149         struct drm_atomic_state *state = dev_priv->modeset_restore_state;
16150         struct drm_modeset_acquire_ctx ctx;
16151         int ret;
16152         bool setup = false;
16153
16154         dev_priv->modeset_restore_state = NULL;
16155
16156         /*
16157          * This is a cludge because with real atomic modeset mode_config.mutex
16158          * won't be taken. Unfortunately some probed state like
16159          * audio_codec_enable is still protected by mode_config.mutex, so lock
16160          * it here for now.
16161          */
16162         mutex_lock(&dev->mode_config.mutex);
16163         drm_modeset_acquire_init(&ctx, 0);
16164
16165 retry:
16166         ret = drm_modeset_lock_all_ctx(dev, &ctx);
16167
16168         if (ret == 0 && !setup) {
16169                 setup = true;
16170
16171                 intel_modeset_setup_hw_state(dev);
16172                 i915_redisable_vga(dev);
16173         }
16174
16175         if (ret == 0 && state) {
16176                 struct drm_crtc_state *crtc_state;
16177                 struct drm_crtc *crtc;
16178                 int i;
16179
16180                 state->acquire_ctx = &ctx;
16181
16182                 /* ignore any reset values/BIOS leftovers in the WM registers */
16183                 to_intel_atomic_state(state)->skip_intermediate_wm = true;
16184
16185                 for_each_crtc_in_state(state, crtc, crtc_state, i) {
16186                         /*
16187                          * Force recalculation even if we restore
16188                          * current state. With fast modeset this may not result
16189                          * in a modeset when the state is compatible.
16190                          */
16191                         crtc_state->mode_changed = true;
16192                 }
16193
16194                 ret = drm_atomic_commit(state);
16195         }
16196
16197         if (ret == -EDEADLK) {
16198                 drm_modeset_backoff(&ctx);
16199                 goto retry;
16200         }
16201
16202         drm_modeset_drop_locks(&ctx);
16203         drm_modeset_acquire_fini(&ctx);
16204         mutex_unlock(&dev->mode_config.mutex);
16205
16206         if (ret) {
16207                 DRM_ERROR("Restoring old state failed with %i\n", ret);
16208                 drm_atomic_state_free(state);
16209         }
16210 }
16211
16212 void intel_modeset_gem_init(struct drm_device *dev)
16213 {
16214         struct drm_i915_private *dev_priv = to_i915(dev);
16215         struct drm_crtc *c;
16216         struct drm_i915_gem_object *obj;
16217         int ret;
16218
16219         intel_init_gt_powersave(dev_priv);
16220
16221         intel_modeset_init_hw(dev);
16222
16223         intel_setup_overlay(dev_priv);
16224
16225         /*
16226          * Make sure any fbs we allocated at startup are properly
16227          * pinned & fenced.  When we do the allocation it's too early
16228          * for this.
16229          */
16230         for_each_crtc(dev, c) {
16231                 obj = intel_fb_obj(c->primary->fb);
16232                 if (obj == NULL)
16233                         continue;
16234
16235                 mutex_lock(&dev->struct_mutex);
16236                 ret = intel_pin_and_fence_fb_obj(c->primary->fb,
16237                                                  c->primary->state->rotation);
16238                 mutex_unlock(&dev->struct_mutex);
16239                 if (ret) {
16240                         DRM_ERROR("failed to pin boot fb on pipe %d\n",
16241                                   to_intel_crtc(c)->pipe);
16242                         drm_framebuffer_unreference(c->primary->fb);
16243                         c->primary->fb = NULL;
16244                         c->primary->crtc = c->primary->state->crtc = NULL;
16245                         update_state_fb(c->primary);
16246                         c->state->plane_mask &= ~(1 << drm_plane_index(c->primary));
16247                 }
16248         }
16249 }
16250
16251 int intel_connector_register(struct drm_connector *connector)
16252 {
16253         struct intel_connector *intel_connector = to_intel_connector(connector);
16254         int ret;
16255
16256         ret = intel_backlight_device_register(intel_connector);
16257         if (ret)
16258                 goto err;
16259
16260         return 0;
16261
16262 err:
16263         return ret;
16264 }
16265
16266 void intel_connector_unregister(struct drm_connector *connector)
16267 {
16268         struct intel_connector *intel_connector = to_intel_connector(connector);
16269
16270         intel_backlight_device_unregister(intel_connector);
16271         intel_panel_destroy_backlight(connector);
16272 }
16273
16274 void intel_modeset_cleanup(struct drm_device *dev)
16275 {
16276         struct drm_i915_private *dev_priv = to_i915(dev);
16277
16278         intel_disable_gt_powersave(dev_priv);
16279
16280         /*
16281          * Interrupts and polling as the first thing to avoid creating havoc.
16282          * Too much stuff here (turning of connectors, ...) would
16283          * experience fancy races otherwise.
16284          */
16285         intel_irq_uninstall(dev_priv);
16286
16287         /*
16288          * Due to the hpd irq storm handling the hotplug work can re-arm the
16289          * poll handlers. Hence disable polling after hpd handling is shut down.
16290          */
16291         drm_kms_helper_poll_fini(dev);
16292
16293         intel_unregister_dsm_handler();
16294
16295         intel_fbc_global_disable(dev_priv);
16296
16297         /* flush any delayed tasks or pending work */
16298         flush_scheduled_work();
16299
16300         drm_mode_config_cleanup(dev);
16301
16302         intel_cleanup_overlay(dev_priv);
16303
16304         intel_cleanup_gt_powersave(dev_priv);
16305
16306         intel_teardown_gmbus(dev);
16307 }
16308
16309 void intel_connector_attach_encoder(struct intel_connector *connector,
16310                                     struct intel_encoder *encoder)
16311 {
16312         connector->encoder = encoder;
16313         drm_mode_connector_attach_encoder(&connector->base,
16314                                           &encoder->base);
16315 }
16316
16317 /*
16318  * set vga decode state - true == enable VGA decode
16319  */
16320 int intel_modeset_vga_set_state(struct drm_device *dev, bool state)
16321 {
16322         struct drm_i915_private *dev_priv = to_i915(dev);
16323         unsigned reg = INTEL_INFO(dev)->gen >= 6 ? SNB_GMCH_CTRL : INTEL_GMCH_CTRL;
16324         u16 gmch_ctrl;
16325
16326         if (pci_read_config_word(dev_priv->bridge_dev, reg, &gmch_ctrl)) {
16327                 DRM_ERROR("failed to read control word\n");
16328                 return -EIO;
16329         }
16330
16331         if (!!(gmch_ctrl & INTEL_GMCH_VGA_DISABLE) == !state)
16332                 return 0;
16333
16334         if (state)
16335                 gmch_ctrl &= ~INTEL_GMCH_VGA_DISABLE;
16336         else
16337                 gmch_ctrl |= INTEL_GMCH_VGA_DISABLE;
16338
16339         if (pci_write_config_word(dev_priv->bridge_dev, reg, gmch_ctrl)) {
16340                 DRM_ERROR("failed to write control word\n");
16341                 return -EIO;
16342         }
16343
16344         return 0;
16345 }
16346
16347 struct intel_display_error_state {
16348
16349         u32 power_well_driver;
16350
16351         int num_transcoders;
16352
16353         struct intel_cursor_error_state {
16354                 u32 control;
16355                 u32 position;
16356                 u32 base;
16357                 u32 size;
16358         } cursor[I915_MAX_PIPES];
16359
16360         struct intel_pipe_error_state {
16361                 bool power_domain_on;
16362                 u32 source;
16363                 u32 stat;
16364         } pipe[I915_MAX_PIPES];
16365
16366         struct intel_plane_error_state {
16367                 u32 control;
16368                 u32 stride;
16369                 u32 size;
16370                 u32 pos;
16371                 u32 addr;
16372                 u32 surface;
16373                 u32 tile_offset;
16374         } plane[I915_MAX_PIPES];
16375
16376         struct intel_transcoder_error_state {
16377                 bool power_domain_on;
16378                 enum transcoder cpu_transcoder;
16379
16380                 u32 conf;
16381
16382                 u32 htotal;
16383                 u32 hblank;
16384                 u32 hsync;
16385                 u32 vtotal;
16386                 u32 vblank;
16387                 u32 vsync;
16388         } transcoder[4];
16389 };
16390
16391 struct intel_display_error_state *
16392 intel_display_capture_error_state(struct drm_i915_private *dev_priv)
16393 {
16394         struct intel_display_error_state *error;
16395         int transcoders[] = {
16396                 TRANSCODER_A,
16397                 TRANSCODER_B,
16398                 TRANSCODER_C,
16399                 TRANSCODER_EDP,
16400         };
16401         int i;
16402
16403         if (INTEL_INFO(dev_priv)->num_pipes == 0)
16404                 return NULL;
16405
16406         error = kzalloc(sizeof(*error), GFP_ATOMIC);
16407         if (error == NULL)
16408                 return NULL;
16409
16410         if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv))
16411                 error->power_well_driver = I915_READ(HSW_PWR_WELL_DRIVER);
16412
16413         for_each_pipe(dev_priv, i) {
16414                 error->pipe[i].power_domain_on =
16415                         __intel_display_power_is_enabled(dev_priv,
16416                                                          POWER_DOMAIN_PIPE(i));
16417                 if (!error->pipe[i].power_domain_on)
16418                         continue;
16419
16420                 error->cursor[i].control = I915_READ(CURCNTR(i));
16421                 error->cursor[i].position = I915_READ(CURPOS(i));
16422                 error->cursor[i].base = I915_READ(CURBASE(i));
16423
16424                 error->plane[i].control = I915_READ(DSPCNTR(i));
16425                 error->plane[i].stride = I915_READ(DSPSTRIDE(i));
16426                 if (INTEL_GEN(dev_priv) <= 3) {
16427                         error->plane[i].size = I915_READ(DSPSIZE(i));
16428                         error->plane[i].pos = I915_READ(DSPPOS(i));
16429                 }
16430                 if (INTEL_GEN(dev_priv) <= 7 && !IS_HASWELL(dev_priv))
16431                         error->plane[i].addr = I915_READ(DSPADDR(i));
16432                 if (INTEL_GEN(dev_priv) >= 4) {
16433                         error->plane[i].surface = I915_READ(DSPSURF(i));
16434                         error->plane[i].tile_offset = I915_READ(DSPTILEOFF(i));
16435                 }
16436
16437                 error->pipe[i].source = I915_READ(PIPESRC(i));
16438
16439                 if (HAS_GMCH_DISPLAY(dev_priv))
16440                         error->pipe[i].stat = I915_READ(PIPESTAT(i));
16441         }
16442
16443         /* Note: this does not include DSI transcoders. */
16444         error->num_transcoders = INTEL_INFO(dev_priv)->num_pipes;
16445         if (HAS_DDI(dev_priv))
16446                 error->num_transcoders++; /* Account for eDP. */
16447
16448         for (i = 0; i < error->num_transcoders; i++) {
16449                 enum transcoder cpu_transcoder = transcoders[i];
16450
16451                 error->transcoder[i].power_domain_on =
16452                         __intel_display_power_is_enabled(dev_priv,
16453                                 POWER_DOMAIN_TRANSCODER(cpu_transcoder));
16454                 if (!error->transcoder[i].power_domain_on)
16455                         continue;
16456
16457                 error->transcoder[i].cpu_transcoder = cpu_transcoder;
16458
16459                 error->transcoder[i].conf = I915_READ(PIPECONF(cpu_transcoder));
16460                 error->transcoder[i].htotal = I915_READ(HTOTAL(cpu_transcoder));
16461                 error->transcoder[i].hblank = I915_READ(HBLANK(cpu_transcoder));
16462                 error->transcoder[i].hsync = I915_READ(HSYNC(cpu_transcoder));
16463                 error->transcoder[i].vtotal = I915_READ(VTOTAL(cpu_transcoder));
16464                 error->transcoder[i].vblank = I915_READ(VBLANK(cpu_transcoder));
16465                 error->transcoder[i].vsync = I915_READ(VSYNC(cpu_transcoder));
16466         }
16467
16468         return error;
16469 }
16470
16471 #define err_printf(e, ...) i915_error_printf(e, __VA_ARGS__)
16472
16473 void
16474 intel_display_print_error_state(struct drm_i915_error_state_buf *m,
16475                                 struct drm_device *dev,
16476                                 struct intel_display_error_state *error)
16477 {
16478         struct drm_i915_private *dev_priv = to_i915(dev);
16479         int i;
16480
16481         if (!error)
16482                 return;
16483
16484         err_printf(m, "Num Pipes: %d\n", INTEL_INFO(dev)->num_pipes);
16485         if (IS_HASWELL(dev) || IS_BROADWELL(dev))
16486                 err_printf(m, "PWR_WELL_CTL2: %08x\n",
16487                            error->power_well_driver);
16488         for_each_pipe(dev_priv, i) {
16489                 err_printf(m, "Pipe [%d]:\n", i);
16490                 err_printf(m, "  Power: %s\n",
16491                            onoff(error->pipe[i].power_domain_on));
16492                 err_printf(m, "  SRC: %08x\n", error->pipe[i].source);
16493                 err_printf(m, "  STAT: %08x\n", error->pipe[i].stat);
16494
16495                 err_printf(m, "Plane [%d]:\n", i);
16496                 err_printf(m, "  CNTR: %08x\n", error->plane[i].control);
16497                 err_printf(m, "  STRIDE: %08x\n", error->plane[i].stride);
16498                 if (INTEL_INFO(dev)->gen <= 3) {
16499                         err_printf(m, "  SIZE: %08x\n", error->plane[i].size);
16500                         err_printf(m, "  POS: %08x\n", error->plane[i].pos);
16501                 }
16502                 if (INTEL_INFO(dev)->gen <= 7 && !IS_HASWELL(dev))
16503                         err_printf(m, "  ADDR: %08x\n", error->plane[i].addr);
16504                 if (INTEL_INFO(dev)->gen >= 4) {
16505                         err_printf(m, "  SURF: %08x\n", error->plane[i].surface);
16506                         err_printf(m, "  TILEOFF: %08x\n", error->plane[i].tile_offset);
16507                 }
16508
16509                 err_printf(m, "Cursor [%d]:\n", i);
16510                 err_printf(m, "  CNTR: %08x\n", error->cursor[i].control);
16511                 err_printf(m, "  POS: %08x\n", error->cursor[i].position);
16512                 err_printf(m, "  BASE: %08x\n", error->cursor[i].base);
16513         }
16514
16515         for (i = 0; i < error->num_transcoders; i++) {
16516                 err_printf(m, "CPU transcoder: %s\n",
16517                            transcoder_name(error->transcoder[i].cpu_transcoder));
16518                 err_printf(m, "  Power: %s\n",
16519                            onoff(error->transcoder[i].power_domain_on));
16520                 err_printf(m, "  CONF: %08x\n", error->transcoder[i].conf);
16521                 err_printf(m, "  HTOTAL: %08x\n", error->transcoder[i].htotal);
16522                 err_printf(m, "  HBLANK: %08x\n", error->transcoder[i].hblank);
16523                 err_printf(m, "  HSYNC: %08x\n", error->transcoder[i].hsync);
16524                 err_printf(m, "  VTOTAL: %08x\n", error->transcoder[i].vtotal);
16525                 err_printf(m, "  VBLANK: %08x\n", error->transcoder[i].vblank);
16526                 err_printf(m, "  VSYNC: %08x\n", error->transcoder[i].vsync);
16527         }
16528 }