]> git.karo-electronics.de Git - karo-tx-linux.git/blob - drivers/gpu/drm/i915/intel_display.c
drm/i915: Compute display surface offset in the plane check hook for SKL+
[karo-tx-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 = PP_CONTROL(0);
1206                 port_sel = I915_READ(PP_ON_DELAYS(0)) & PANEL_PORT_SELECT_MASK;
1207
1208                 if (port_sel == PANEL_PORT_SELECT_LVDS &&
1209                     I915_READ(PCH_LVDS) & LVDS_PIPEB_SELECT)
1210                         panel_pipe = PIPE_B;
1211                 /* XXX: else fix for eDP */
1212         } else if (IS_VALLEYVIEW(dev) || IS_CHERRYVIEW(dev)) {
1213                 /* presumably write lock depends on pipe, not port select */
1214                 pp_reg = PP_CONTROL(pipe);
1215                 panel_pipe = pipe;
1216         } else {
1217                 pp_reg = PP_CONTROL(0);
1218                 if (I915_READ(LVDS) & LVDS_PIPEB_SELECT)
1219                         panel_pipe = PIPE_B;
1220         }
1221
1222         val = I915_READ(pp_reg);
1223         if (!(val & PANEL_POWER_ON) ||
1224             ((val & PANEL_UNLOCK_MASK) == PANEL_UNLOCK_REGS))
1225                 locked = false;
1226
1227         I915_STATE_WARN(panel_pipe == pipe && locked,
1228              "panel assertion failure, pipe %c regs locked\n",
1229              pipe_name(pipe));
1230 }
1231
1232 static void assert_cursor(struct drm_i915_private *dev_priv,
1233                           enum pipe pipe, bool state)
1234 {
1235         struct drm_device *dev = &dev_priv->drm;
1236         bool cur_state;
1237
1238         if (IS_845G(dev) || IS_I865G(dev))
1239                 cur_state = I915_READ(CURCNTR(PIPE_A)) & CURSOR_ENABLE;
1240         else
1241                 cur_state = I915_READ(CURCNTR(pipe)) & CURSOR_MODE;
1242
1243         I915_STATE_WARN(cur_state != state,
1244              "cursor on pipe %c assertion failure (expected %s, current %s)\n",
1245                         pipe_name(pipe), onoff(state), onoff(cur_state));
1246 }
1247 #define assert_cursor_enabled(d, p) assert_cursor(d, p, true)
1248 #define assert_cursor_disabled(d, p) assert_cursor(d, p, false)
1249
1250 void assert_pipe(struct drm_i915_private *dev_priv,
1251                  enum pipe pipe, bool state)
1252 {
1253         bool cur_state;
1254         enum transcoder cpu_transcoder = intel_pipe_to_cpu_transcoder(dev_priv,
1255                                                                       pipe);
1256         enum intel_display_power_domain power_domain;
1257
1258         /* if we need the pipe quirk it must be always on */
1259         if ((pipe == PIPE_A && dev_priv->quirks & QUIRK_PIPEA_FORCE) ||
1260             (pipe == PIPE_B && dev_priv->quirks & QUIRK_PIPEB_FORCE))
1261                 state = true;
1262
1263         power_domain = POWER_DOMAIN_TRANSCODER(cpu_transcoder);
1264         if (intel_display_power_get_if_enabled(dev_priv, power_domain)) {
1265                 u32 val = I915_READ(PIPECONF(cpu_transcoder));
1266                 cur_state = !!(val & PIPECONF_ENABLE);
1267
1268                 intel_display_power_put(dev_priv, power_domain);
1269         } else {
1270                 cur_state = false;
1271         }
1272
1273         I915_STATE_WARN(cur_state != state,
1274              "pipe %c assertion failure (expected %s, current %s)\n",
1275                         pipe_name(pipe), onoff(state), onoff(cur_state));
1276 }
1277
1278 static void assert_plane(struct drm_i915_private *dev_priv,
1279                          enum plane plane, bool state)
1280 {
1281         u32 val;
1282         bool cur_state;
1283
1284         val = I915_READ(DSPCNTR(plane));
1285         cur_state = !!(val & DISPLAY_PLANE_ENABLE);
1286         I915_STATE_WARN(cur_state != state,
1287              "plane %c assertion failure (expected %s, current %s)\n",
1288                         plane_name(plane), onoff(state), onoff(cur_state));
1289 }
1290
1291 #define assert_plane_enabled(d, p) assert_plane(d, p, true)
1292 #define assert_plane_disabled(d, p) assert_plane(d, p, false)
1293
1294 static void assert_planes_disabled(struct drm_i915_private *dev_priv,
1295                                    enum pipe pipe)
1296 {
1297         struct drm_device *dev = &dev_priv->drm;
1298         int i;
1299
1300         /* Primary planes are fixed to pipes on gen4+ */
1301         if (INTEL_INFO(dev)->gen >= 4) {
1302                 u32 val = I915_READ(DSPCNTR(pipe));
1303                 I915_STATE_WARN(val & DISPLAY_PLANE_ENABLE,
1304                      "plane %c assertion failure, should be disabled but not\n",
1305                      plane_name(pipe));
1306                 return;
1307         }
1308
1309         /* Need to check both planes against the pipe */
1310         for_each_pipe(dev_priv, i) {
1311                 u32 val = I915_READ(DSPCNTR(i));
1312                 enum pipe cur_pipe = (val & DISPPLANE_SEL_PIPE_MASK) >>
1313                         DISPPLANE_SEL_PIPE_SHIFT;
1314                 I915_STATE_WARN((val & DISPLAY_PLANE_ENABLE) && pipe == cur_pipe,
1315                      "plane %c assertion failure, should be off on pipe %c but is still active\n",
1316                      plane_name(i), pipe_name(pipe));
1317         }
1318 }
1319
1320 static void assert_sprites_disabled(struct drm_i915_private *dev_priv,
1321                                     enum pipe pipe)
1322 {
1323         struct drm_device *dev = &dev_priv->drm;
1324         int sprite;
1325
1326         if (INTEL_INFO(dev)->gen >= 9) {
1327                 for_each_sprite(dev_priv, pipe, sprite) {
1328                         u32 val = I915_READ(PLANE_CTL(pipe, sprite));
1329                         I915_STATE_WARN(val & PLANE_CTL_ENABLE,
1330                              "plane %d assertion failure, should be off on pipe %c but is still active\n",
1331                              sprite, pipe_name(pipe));
1332                 }
1333         } else if (IS_VALLEYVIEW(dev) || IS_CHERRYVIEW(dev)) {
1334                 for_each_sprite(dev_priv, pipe, sprite) {
1335                         u32 val = I915_READ(SPCNTR(pipe, sprite));
1336                         I915_STATE_WARN(val & SP_ENABLE,
1337                              "sprite %c assertion failure, should be off on pipe %c but is still active\n",
1338                              sprite_name(pipe, sprite), pipe_name(pipe));
1339                 }
1340         } else if (INTEL_INFO(dev)->gen >= 7) {
1341                 u32 val = I915_READ(SPRCTL(pipe));
1342                 I915_STATE_WARN(val & SPRITE_ENABLE,
1343                      "sprite %c assertion failure, should be off on pipe %c but is still active\n",
1344                      plane_name(pipe), pipe_name(pipe));
1345         } else if (INTEL_INFO(dev)->gen >= 5) {
1346                 u32 val = I915_READ(DVSCNTR(pipe));
1347                 I915_STATE_WARN(val & DVS_ENABLE,
1348                      "sprite %c assertion failure, should be off on pipe %c but is still active\n",
1349                      plane_name(pipe), pipe_name(pipe));
1350         }
1351 }
1352
1353 static void assert_vblank_disabled(struct drm_crtc *crtc)
1354 {
1355         if (I915_STATE_WARN_ON(drm_crtc_vblank_get(crtc) == 0))
1356                 drm_crtc_vblank_put(crtc);
1357 }
1358
1359 void assert_pch_transcoder_disabled(struct drm_i915_private *dev_priv,
1360                                     enum pipe pipe)
1361 {
1362         u32 val;
1363         bool enabled;
1364
1365         val = I915_READ(PCH_TRANSCONF(pipe));
1366         enabled = !!(val & TRANS_ENABLE);
1367         I915_STATE_WARN(enabled,
1368              "transcoder assertion failed, should be off on pipe %c but is still active\n",
1369              pipe_name(pipe));
1370 }
1371
1372 static bool dp_pipe_enabled(struct drm_i915_private *dev_priv,
1373                             enum pipe pipe, u32 port_sel, u32 val)
1374 {
1375         if ((val & DP_PORT_EN) == 0)
1376                 return false;
1377
1378         if (HAS_PCH_CPT(dev_priv)) {
1379                 u32 trans_dp_ctl = I915_READ(TRANS_DP_CTL(pipe));
1380                 if ((trans_dp_ctl & TRANS_DP_PORT_SEL_MASK) != port_sel)
1381                         return false;
1382         } else if (IS_CHERRYVIEW(dev_priv)) {
1383                 if ((val & DP_PIPE_MASK_CHV) != DP_PIPE_SELECT_CHV(pipe))
1384                         return false;
1385         } else {
1386                 if ((val & DP_PIPE_MASK) != (pipe << 30))
1387                         return false;
1388         }
1389         return true;
1390 }
1391
1392 static bool hdmi_pipe_enabled(struct drm_i915_private *dev_priv,
1393                               enum pipe pipe, u32 val)
1394 {
1395         if ((val & SDVO_ENABLE) == 0)
1396                 return false;
1397
1398         if (HAS_PCH_CPT(dev_priv)) {
1399                 if ((val & SDVO_PIPE_SEL_MASK_CPT) != SDVO_PIPE_SEL_CPT(pipe))
1400                         return false;
1401         } else if (IS_CHERRYVIEW(dev_priv)) {
1402                 if ((val & SDVO_PIPE_SEL_MASK_CHV) != SDVO_PIPE_SEL_CHV(pipe))
1403                         return false;
1404         } else {
1405                 if ((val & SDVO_PIPE_SEL_MASK) != SDVO_PIPE_SEL(pipe))
1406                         return false;
1407         }
1408         return true;
1409 }
1410
1411 static bool lvds_pipe_enabled(struct drm_i915_private *dev_priv,
1412                               enum pipe pipe, u32 val)
1413 {
1414         if ((val & LVDS_PORT_EN) == 0)
1415                 return false;
1416
1417         if (HAS_PCH_CPT(dev_priv)) {
1418                 if ((val & PORT_TRANS_SEL_MASK) != PORT_TRANS_SEL_CPT(pipe))
1419                         return false;
1420         } else {
1421                 if ((val & LVDS_PIPE_MASK) != LVDS_PIPE(pipe))
1422                         return false;
1423         }
1424         return true;
1425 }
1426
1427 static bool adpa_pipe_enabled(struct drm_i915_private *dev_priv,
1428                               enum pipe pipe, u32 val)
1429 {
1430         if ((val & ADPA_DAC_ENABLE) == 0)
1431                 return false;
1432         if (HAS_PCH_CPT(dev_priv)) {
1433                 if ((val & PORT_TRANS_SEL_MASK) != PORT_TRANS_SEL_CPT(pipe))
1434                         return false;
1435         } else {
1436                 if ((val & ADPA_PIPE_SELECT_MASK) != ADPA_PIPE_SELECT(pipe))
1437                         return false;
1438         }
1439         return true;
1440 }
1441
1442 static void assert_pch_dp_disabled(struct drm_i915_private *dev_priv,
1443                                    enum pipe pipe, i915_reg_t reg,
1444                                    u32 port_sel)
1445 {
1446         u32 val = I915_READ(reg);
1447         I915_STATE_WARN(dp_pipe_enabled(dev_priv, pipe, port_sel, val),
1448              "PCH DP (0x%08x) enabled on transcoder %c, should be disabled\n",
1449              i915_mmio_reg_offset(reg), pipe_name(pipe));
1450
1451         I915_STATE_WARN(HAS_PCH_IBX(dev_priv) && (val & DP_PORT_EN) == 0
1452              && (val & DP_PIPEB_SELECT),
1453              "IBX PCH dp port still using transcoder B\n");
1454 }
1455
1456 static void assert_pch_hdmi_disabled(struct drm_i915_private *dev_priv,
1457                                      enum pipe pipe, i915_reg_t reg)
1458 {
1459         u32 val = I915_READ(reg);
1460         I915_STATE_WARN(hdmi_pipe_enabled(dev_priv, pipe, val),
1461              "PCH HDMI (0x%08x) enabled on transcoder %c, should be disabled\n",
1462              i915_mmio_reg_offset(reg), pipe_name(pipe));
1463
1464         I915_STATE_WARN(HAS_PCH_IBX(dev_priv) && (val & SDVO_ENABLE) == 0
1465              && (val & SDVO_PIPE_B_SELECT),
1466              "IBX PCH hdmi port still using transcoder B\n");
1467 }
1468
1469 static void assert_pch_ports_disabled(struct drm_i915_private *dev_priv,
1470                                       enum pipe pipe)
1471 {
1472         u32 val;
1473
1474         assert_pch_dp_disabled(dev_priv, pipe, PCH_DP_B, TRANS_DP_PORT_SEL_B);
1475         assert_pch_dp_disabled(dev_priv, pipe, PCH_DP_C, TRANS_DP_PORT_SEL_C);
1476         assert_pch_dp_disabled(dev_priv, pipe, PCH_DP_D, TRANS_DP_PORT_SEL_D);
1477
1478         val = I915_READ(PCH_ADPA);
1479         I915_STATE_WARN(adpa_pipe_enabled(dev_priv, pipe, val),
1480              "PCH VGA enabled on transcoder %c, should be disabled\n",
1481              pipe_name(pipe));
1482
1483         val = I915_READ(PCH_LVDS);
1484         I915_STATE_WARN(lvds_pipe_enabled(dev_priv, pipe, val),
1485              "PCH LVDS enabled on transcoder %c, should be disabled\n",
1486              pipe_name(pipe));
1487
1488         assert_pch_hdmi_disabled(dev_priv, pipe, PCH_HDMIB);
1489         assert_pch_hdmi_disabled(dev_priv, pipe, PCH_HDMIC);
1490         assert_pch_hdmi_disabled(dev_priv, pipe, PCH_HDMID);
1491 }
1492
1493 static void _vlv_enable_pll(struct intel_crtc *crtc,
1494                             const struct intel_crtc_state *pipe_config)
1495 {
1496         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1497         enum pipe pipe = crtc->pipe;
1498
1499         I915_WRITE(DPLL(pipe), pipe_config->dpll_hw_state.dpll);
1500         POSTING_READ(DPLL(pipe));
1501         udelay(150);
1502
1503         if (intel_wait_for_register(dev_priv,
1504                                     DPLL(pipe),
1505                                     DPLL_LOCK_VLV,
1506                                     DPLL_LOCK_VLV,
1507                                     1))
1508                 DRM_ERROR("DPLL %d failed to lock\n", pipe);
1509 }
1510
1511 static void vlv_enable_pll(struct intel_crtc *crtc,
1512                            const struct intel_crtc_state *pipe_config)
1513 {
1514         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1515         enum pipe pipe = crtc->pipe;
1516
1517         assert_pipe_disabled(dev_priv, pipe);
1518
1519         /* PLL is protected by panel, make sure we can write it */
1520         assert_panel_unlocked(dev_priv, pipe);
1521
1522         if (pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE)
1523                 _vlv_enable_pll(crtc, pipe_config);
1524
1525         I915_WRITE(DPLL_MD(pipe), pipe_config->dpll_hw_state.dpll_md);
1526         POSTING_READ(DPLL_MD(pipe));
1527 }
1528
1529
1530 static void _chv_enable_pll(struct intel_crtc *crtc,
1531                             const struct intel_crtc_state *pipe_config)
1532 {
1533         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1534         enum pipe pipe = crtc->pipe;
1535         enum dpio_channel port = vlv_pipe_to_channel(pipe);
1536         u32 tmp;
1537
1538         mutex_lock(&dev_priv->sb_lock);
1539
1540         /* Enable back the 10bit clock to display controller */
1541         tmp = vlv_dpio_read(dev_priv, pipe, CHV_CMN_DW14(port));
1542         tmp |= DPIO_DCLKP_EN;
1543         vlv_dpio_write(dev_priv, pipe, CHV_CMN_DW14(port), tmp);
1544
1545         mutex_unlock(&dev_priv->sb_lock);
1546
1547         /*
1548          * Need to wait > 100ns between dclkp clock enable bit and PLL enable.
1549          */
1550         udelay(1);
1551
1552         /* Enable PLL */
1553         I915_WRITE(DPLL(pipe), pipe_config->dpll_hw_state.dpll);
1554
1555         /* Check PLL is locked */
1556         if (intel_wait_for_register(dev_priv,
1557                                     DPLL(pipe), DPLL_LOCK_VLV, DPLL_LOCK_VLV,
1558                                     1))
1559                 DRM_ERROR("PLL %d failed to lock\n", pipe);
1560 }
1561
1562 static void chv_enable_pll(struct intel_crtc *crtc,
1563                            const struct intel_crtc_state *pipe_config)
1564 {
1565         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1566         enum pipe pipe = crtc->pipe;
1567
1568         assert_pipe_disabled(dev_priv, pipe);
1569
1570         /* PLL is protected by panel, make sure we can write it */
1571         assert_panel_unlocked(dev_priv, pipe);
1572
1573         if (pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE)
1574                 _chv_enable_pll(crtc, pipe_config);
1575
1576         if (pipe != PIPE_A) {
1577                 /*
1578                  * WaPixelRepeatModeFixForC0:chv
1579                  *
1580                  * DPLLCMD is AWOL. Use chicken bits to propagate
1581                  * the value from DPLLBMD to either pipe B or C.
1582                  */
1583                 I915_WRITE(CBR4_VLV, pipe == PIPE_B ? CBR_DPLLBMD_PIPE_B : CBR_DPLLBMD_PIPE_C);
1584                 I915_WRITE(DPLL_MD(PIPE_B), pipe_config->dpll_hw_state.dpll_md);
1585                 I915_WRITE(CBR4_VLV, 0);
1586                 dev_priv->chv_dpll_md[pipe] = pipe_config->dpll_hw_state.dpll_md;
1587
1588                 /*
1589                  * DPLLB VGA mode also seems to cause problems.
1590                  * We should always have it disabled.
1591                  */
1592                 WARN_ON((I915_READ(DPLL(PIPE_B)) & DPLL_VGA_MODE_DIS) == 0);
1593         } else {
1594                 I915_WRITE(DPLL_MD(pipe), pipe_config->dpll_hw_state.dpll_md);
1595                 POSTING_READ(DPLL_MD(pipe));
1596         }
1597 }
1598
1599 static int intel_num_dvo_pipes(struct drm_device *dev)
1600 {
1601         struct intel_crtc *crtc;
1602         int count = 0;
1603
1604         for_each_intel_crtc(dev, crtc) {
1605                 count += crtc->base.state->active &&
1606                         intel_crtc_has_type(crtc->config, INTEL_OUTPUT_DVO);
1607         }
1608
1609         return count;
1610 }
1611
1612 static void i9xx_enable_pll(struct intel_crtc *crtc)
1613 {
1614         struct drm_device *dev = crtc->base.dev;
1615         struct drm_i915_private *dev_priv = to_i915(dev);
1616         i915_reg_t reg = DPLL(crtc->pipe);
1617         u32 dpll = crtc->config->dpll_hw_state.dpll;
1618
1619         assert_pipe_disabled(dev_priv, crtc->pipe);
1620
1621         /* PLL is protected by panel, make sure we can write it */
1622         if (IS_MOBILE(dev) && !IS_I830(dev))
1623                 assert_panel_unlocked(dev_priv, crtc->pipe);
1624
1625         /* Enable DVO 2x clock on both PLLs if necessary */
1626         if (IS_I830(dev) && intel_num_dvo_pipes(dev) > 0) {
1627                 /*
1628                  * It appears to be important that we don't enable this
1629                  * for the current pipe before otherwise configuring the
1630                  * PLL. No idea how this should be handled if multiple
1631                  * DVO outputs are enabled simultaneosly.
1632                  */
1633                 dpll |= DPLL_DVO_2X_MODE;
1634                 I915_WRITE(DPLL(!crtc->pipe),
1635                            I915_READ(DPLL(!crtc->pipe)) | DPLL_DVO_2X_MODE);
1636         }
1637
1638         /*
1639          * Apparently we need to have VGA mode enabled prior to changing
1640          * the P1/P2 dividers. Otherwise the DPLL will keep using the old
1641          * dividers, even though the register value does change.
1642          */
1643         I915_WRITE(reg, 0);
1644
1645         I915_WRITE(reg, dpll);
1646
1647         /* Wait for the clocks to stabilize. */
1648         POSTING_READ(reg);
1649         udelay(150);
1650
1651         if (INTEL_INFO(dev)->gen >= 4) {
1652                 I915_WRITE(DPLL_MD(crtc->pipe),
1653                            crtc->config->dpll_hw_state.dpll_md);
1654         } else {
1655                 /* The pixel multiplier can only be updated once the
1656                  * DPLL is enabled and the clocks are stable.
1657                  *
1658                  * So write it again.
1659                  */
1660                 I915_WRITE(reg, dpll);
1661         }
1662
1663         /* We do this three times for luck */
1664         I915_WRITE(reg, dpll);
1665         POSTING_READ(reg);
1666         udelay(150); /* wait for warmup */
1667         I915_WRITE(reg, dpll);
1668         POSTING_READ(reg);
1669         udelay(150); /* wait for warmup */
1670         I915_WRITE(reg, dpll);
1671         POSTING_READ(reg);
1672         udelay(150); /* wait for warmup */
1673 }
1674
1675 /**
1676  * i9xx_disable_pll - disable a PLL
1677  * @dev_priv: i915 private structure
1678  * @pipe: pipe PLL to disable
1679  *
1680  * Disable the PLL for @pipe, making sure the pipe is off first.
1681  *
1682  * Note!  This is for pre-ILK only.
1683  */
1684 static void i9xx_disable_pll(struct intel_crtc *crtc)
1685 {
1686         struct drm_device *dev = crtc->base.dev;
1687         struct drm_i915_private *dev_priv = to_i915(dev);
1688         enum pipe pipe = crtc->pipe;
1689
1690         /* Disable DVO 2x clock on both PLLs if necessary */
1691         if (IS_I830(dev) &&
1692             intel_crtc_has_type(crtc->config, INTEL_OUTPUT_DVO) &&
1693             !intel_num_dvo_pipes(dev)) {
1694                 I915_WRITE(DPLL(PIPE_B),
1695                            I915_READ(DPLL(PIPE_B)) & ~DPLL_DVO_2X_MODE);
1696                 I915_WRITE(DPLL(PIPE_A),
1697                            I915_READ(DPLL(PIPE_A)) & ~DPLL_DVO_2X_MODE);
1698         }
1699
1700         /* Don't disable pipe or pipe PLLs if needed */
1701         if ((pipe == PIPE_A && dev_priv->quirks & QUIRK_PIPEA_FORCE) ||
1702             (pipe == PIPE_B && dev_priv->quirks & QUIRK_PIPEB_FORCE))
1703                 return;
1704
1705         /* Make sure the pipe isn't still relying on us */
1706         assert_pipe_disabled(dev_priv, pipe);
1707
1708         I915_WRITE(DPLL(pipe), DPLL_VGA_MODE_DIS);
1709         POSTING_READ(DPLL(pipe));
1710 }
1711
1712 static void vlv_disable_pll(struct drm_i915_private *dev_priv, enum pipe pipe)
1713 {
1714         u32 val;
1715
1716         /* Make sure the pipe isn't still relying on us */
1717         assert_pipe_disabled(dev_priv, pipe);
1718
1719         val = DPLL_INTEGRATED_REF_CLK_VLV |
1720                 DPLL_REF_CLK_ENABLE_VLV | DPLL_VGA_MODE_DIS;
1721         if (pipe != PIPE_A)
1722                 val |= DPLL_INTEGRATED_CRI_CLK_VLV;
1723
1724         I915_WRITE(DPLL(pipe), val);
1725         POSTING_READ(DPLL(pipe));
1726 }
1727
1728 static void chv_disable_pll(struct drm_i915_private *dev_priv, enum pipe pipe)
1729 {
1730         enum dpio_channel port = vlv_pipe_to_channel(pipe);
1731         u32 val;
1732
1733         /* Make sure the pipe isn't still relying on us */
1734         assert_pipe_disabled(dev_priv, pipe);
1735
1736         val = DPLL_SSC_REF_CLK_CHV |
1737                 DPLL_REF_CLK_ENABLE_VLV | DPLL_VGA_MODE_DIS;
1738         if (pipe != PIPE_A)
1739                 val |= DPLL_INTEGRATED_CRI_CLK_VLV;
1740
1741         I915_WRITE(DPLL(pipe), val);
1742         POSTING_READ(DPLL(pipe));
1743
1744         mutex_lock(&dev_priv->sb_lock);
1745
1746         /* Disable 10bit clock to display controller */
1747         val = vlv_dpio_read(dev_priv, pipe, CHV_CMN_DW14(port));
1748         val &= ~DPIO_DCLKP_EN;
1749         vlv_dpio_write(dev_priv, pipe, CHV_CMN_DW14(port), val);
1750
1751         mutex_unlock(&dev_priv->sb_lock);
1752 }
1753
1754 void vlv_wait_port_ready(struct drm_i915_private *dev_priv,
1755                          struct intel_digital_port *dport,
1756                          unsigned int expected_mask)
1757 {
1758         u32 port_mask;
1759         i915_reg_t dpll_reg;
1760
1761         switch (dport->port) {
1762         case PORT_B:
1763                 port_mask = DPLL_PORTB_READY_MASK;
1764                 dpll_reg = DPLL(0);
1765                 break;
1766         case PORT_C:
1767                 port_mask = DPLL_PORTC_READY_MASK;
1768                 dpll_reg = DPLL(0);
1769                 expected_mask <<= 4;
1770                 break;
1771         case PORT_D:
1772                 port_mask = DPLL_PORTD_READY_MASK;
1773                 dpll_reg = DPIO_PHY_STATUS;
1774                 break;
1775         default:
1776                 BUG();
1777         }
1778
1779         if (intel_wait_for_register(dev_priv,
1780                                     dpll_reg, port_mask, expected_mask,
1781                                     1000))
1782                 WARN(1, "timed out waiting for port %c ready: got 0x%x, expected 0x%x\n",
1783                      port_name(dport->port), I915_READ(dpll_reg) & port_mask, expected_mask);
1784 }
1785
1786 static void ironlake_enable_pch_transcoder(struct drm_i915_private *dev_priv,
1787                                            enum pipe pipe)
1788 {
1789         struct drm_device *dev = &dev_priv->drm;
1790         struct drm_crtc *crtc = dev_priv->pipe_to_crtc_mapping[pipe];
1791         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
1792         i915_reg_t reg;
1793         uint32_t val, pipeconf_val;
1794
1795         /* Make sure PCH DPLL is enabled */
1796         assert_shared_dpll_enabled(dev_priv, intel_crtc->config->shared_dpll);
1797
1798         /* FDI must be feeding us bits for PCH ports */
1799         assert_fdi_tx_enabled(dev_priv, pipe);
1800         assert_fdi_rx_enabled(dev_priv, pipe);
1801
1802         if (HAS_PCH_CPT(dev)) {
1803                 /* Workaround: Set the timing override bit before enabling the
1804                  * pch transcoder. */
1805                 reg = TRANS_CHICKEN2(pipe);
1806                 val = I915_READ(reg);
1807                 val |= TRANS_CHICKEN2_TIMING_OVERRIDE;
1808                 I915_WRITE(reg, val);
1809         }
1810
1811         reg = PCH_TRANSCONF(pipe);
1812         val = I915_READ(reg);
1813         pipeconf_val = I915_READ(PIPECONF(pipe));
1814
1815         if (HAS_PCH_IBX(dev_priv)) {
1816                 /*
1817                  * Make the BPC in transcoder be consistent with
1818                  * that in pipeconf reg. For HDMI we must use 8bpc
1819                  * here for both 8bpc and 12bpc.
1820                  */
1821                 val &= ~PIPECONF_BPC_MASK;
1822                 if (intel_crtc_has_type(intel_crtc->config, INTEL_OUTPUT_HDMI))
1823                         val |= PIPECONF_8BPC;
1824                 else
1825                         val |= pipeconf_val & PIPECONF_BPC_MASK;
1826         }
1827
1828         val &= ~TRANS_INTERLACE_MASK;
1829         if ((pipeconf_val & PIPECONF_INTERLACE_MASK) == PIPECONF_INTERLACED_ILK)
1830                 if (HAS_PCH_IBX(dev_priv) &&
1831                     intel_crtc_has_type(intel_crtc->config, INTEL_OUTPUT_SDVO))
1832                         val |= TRANS_LEGACY_INTERLACED_ILK;
1833                 else
1834                         val |= TRANS_INTERLACED;
1835         else
1836                 val |= TRANS_PROGRESSIVE;
1837
1838         I915_WRITE(reg, val | TRANS_ENABLE);
1839         if (intel_wait_for_register(dev_priv,
1840                                     reg, TRANS_STATE_ENABLE, TRANS_STATE_ENABLE,
1841                                     100))
1842                 DRM_ERROR("failed to enable transcoder %c\n", pipe_name(pipe));
1843 }
1844
1845 static void lpt_enable_pch_transcoder(struct drm_i915_private *dev_priv,
1846                                       enum transcoder cpu_transcoder)
1847 {
1848         u32 val, pipeconf_val;
1849
1850         /* FDI must be feeding us bits for PCH ports */
1851         assert_fdi_tx_enabled(dev_priv, (enum pipe) cpu_transcoder);
1852         assert_fdi_rx_enabled(dev_priv, 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 unsigned int intel_linear_alignment(const struct drm_i915_private *dev_priv)
2151 {
2152         if (INTEL_INFO(dev_priv)->gen >= 9)
2153                 return 256 * 1024;
2154         else if (IS_BROADWATER(dev_priv) || IS_CRESTLINE(dev_priv) ||
2155                  IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
2156                 return 128 * 1024;
2157         else if (INTEL_INFO(dev_priv)->gen >= 4)
2158                 return 4 * 1024;
2159         else
2160                 return 0;
2161 }
2162
2163 static unsigned int intel_surf_alignment(const struct drm_i915_private *dev_priv,
2164                                          uint64_t fb_modifier)
2165 {
2166         switch (fb_modifier) {
2167         case DRM_FORMAT_MOD_NONE:
2168                 return intel_linear_alignment(dev_priv);
2169         case I915_FORMAT_MOD_X_TILED:
2170                 if (INTEL_INFO(dev_priv)->gen >= 9)
2171                         return 256 * 1024;
2172                 return 0;
2173         case I915_FORMAT_MOD_Y_TILED:
2174         case I915_FORMAT_MOD_Yf_TILED:
2175                 return 1 * 1024 * 1024;
2176         default:
2177                 MISSING_CASE(fb_modifier);
2178                 return 0;
2179         }
2180 }
2181
2182 int
2183 intel_pin_and_fence_fb_obj(struct drm_framebuffer *fb,
2184                            unsigned int rotation)
2185 {
2186         struct drm_device *dev = fb->dev;
2187         struct drm_i915_private *dev_priv = to_i915(dev);
2188         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
2189         struct i915_ggtt_view view;
2190         u32 alignment;
2191         int ret;
2192
2193         WARN_ON(!mutex_is_locked(&dev->struct_mutex));
2194
2195         alignment = intel_surf_alignment(dev_priv, fb->modifier[0]);
2196
2197         intel_fill_fb_ggtt_view(&view, fb, rotation);
2198
2199         /* Note that the w/a also requires 64 PTE of padding following the
2200          * bo. We currently fill all unused PTE with the shadow page and so
2201          * we should always have valid PTE following the scanout preventing
2202          * the VT-d warning.
2203          */
2204         if (intel_scanout_needs_vtd_wa(dev_priv) && alignment < 256 * 1024)
2205                 alignment = 256 * 1024;
2206
2207         /*
2208          * Global gtt pte registers are special registers which actually forward
2209          * writes to a chunk of system memory. Which means that there is no risk
2210          * that the register values disappear as soon as we call
2211          * intel_runtime_pm_put(), so it is correct to wrap only the
2212          * pin/unpin/fence and not more.
2213          */
2214         intel_runtime_pm_get(dev_priv);
2215
2216         ret = i915_gem_object_pin_to_display_plane(obj, alignment,
2217                                                    &view);
2218         if (ret)
2219                 goto err_pm;
2220
2221         /* Install a fence for tiled scan-out. Pre-i965 always needs a
2222          * fence, whereas 965+ only requires a fence if using
2223          * framebuffer compression.  For simplicity, we always install
2224          * a fence as the cost is not that onerous.
2225          */
2226         if (view.type == I915_GGTT_VIEW_NORMAL) {
2227                 ret = i915_gem_object_get_fence(obj);
2228                 if (ret == -EDEADLK) {
2229                         /*
2230                          * -EDEADLK means there are no free fences
2231                          * no pending flips.
2232                          *
2233                          * This is propagated to atomic, but it uses
2234                          * -EDEADLK to force a locking recovery, so
2235                          * change the returned error to -EBUSY.
2236                          */
2237                         ret = -EBUSY;
2238                         goto err_unpin;
2239                 } else if (ret)
2240                         goto err_unpin;
2241
2242                 i915_gem_object_pin_fence(obj);
2243         }
2244
2245         intel_runtime_pm_put(dev_priv);
2246         return 0;
2247
2248 err_unpin:
2249         i915_gem_object_unpin_from_display_plane(obj, &view);
2250 err_pm:
2251         intel_runtime_pm_put(dev_priv);
2252         return ret;
2253 }
2254
2255 void intel_unpin_fb_obj(struct drm_framebuffer *fb, unsigned int rotation)
2256 {
2257         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
2258         struct i915_ggtt_view view;
2259
2260         WARN_ON(!mutex_is_locked(&obj->base.dev->struct_mutex));
2261
2262         intel_fill_fb_ggtt_view(&view, fb, rotation);
2263
2264         if (view.type == I915_GGTT_VIEW_NORMAL)
2265                 i915_gem_object_unpin_fence(obj);
2266
2267         i915_gem_object_unpin_from_display_plane(obj, &view);
2268 }
2269
2270 static int intel_fb_pitch(const struct drm_framebuffer *fb, int plane,
2271                           unsigned int rotation)
2272 {
2273         if (intel_rotation_90_or_270(rotation))
2274                 return to_intel_framebuffer(fb)->rotated[plane].pitch;
2275         else
2276                 return fb->pitches[plane];
2277 }
2278
2279 /*
2280  * Convert the x/y offsets into a linear offset.
2281  * Only valid with 0/180 degree rotation, which is fine since linear
2282  * offset is only used with linear buffers on pre-hsw and tiled buffers
2283  * with gen2/3, and 90/270 degree rotations isn't supported on any of them.
2284  */
2285 u32 intel_fb_xy_to_linear(int x, int y,
2286                           const struct intel_plane_state *state,
2287                           int plane)
2288 {
2289         const struct drm_framebuffer *fb = state->base.fb;
2290         unsigned int cpp = drm_format_plane_cpp(fb->pixel_format, plane);
2291         unsigned int pitch = fb->pitches[plane];
2292
2293         return y * pitch + x * cpp;
2294 }
2295
2296 /*
2297  * Add the x/y offsets derived from fb->offsets[] to the user
2298  * specified plane src x/y offsets. The resulting x/y offsets
2299  * specify the start of scanout from the beginning of the gtt mapping.
2300  */
2301 void intel_add_fb_offsets(int *x, int *y,
2302                           const struct intel_plane_state *state,
2303                           int plane)
2304
2305 {
2306         const struct intel_framebuffer *intel_fb = to_intel_framebuffer(state->base.fb);
2307         unsigned int rotation = state->base.rotation;
2308
2309         if (intel_rotation_90_or_270(rotation)) {
2310                 *x += intel_fb->rotated[plane].x;
2311                 *y += intel_fb->rotated[plane].y;
2312         } else {
2313                 *x += intel_fb->normal[plane].x;
2314                 *y += intel_fb->normal[plane].y;
2315         }
2316 }
2317
2318 /*
2319  * Input tile dimensions and pitch must already be
2320  * rotated to match x and y, and in pixel units.
2321  */
2322 static u32 _intel_adjust_tile_offset(int *x, int *y,
2323                                      unsigned int tile_width,
2324                                      unsigned int tile_height,
2325                                      unsigned int tile_size,
2326                                      unsigned int pitch_tiles,
2327                                      u32 old_offset,
2328                                      u32 new_offset)
2329 {
2330         unsigned int pitch_pixels = pitch_tiles * tile_width;
2331         unsigned int tiles;
2332
2333         WARN_ON(old_offset & (tile_size - 1));
2334         WARN_ON(new_offset & (tile_size - 1));
2335         WARN_ON(new_offset > old_offset);
2336
2337         tiles = (old_offset - new_offset) / tile_size;
2338
2339         *y += tiles / pitch_tiles * tile_height;
2340         *x += tiles % pitch_tiles * tile_width;
2341
2342         /* minimize x in case it got needlessly big */
2343         *y += *x / pitch_pixels * tile_height;
2344         *x %= pitch_pixels;
2345
2346         return new_offset;
2347 }
2348
2349 /*
2350  * Adjust the tile offset by moving the difference into
2351  * the x/y offsets.
2352  */
2353 static u32 intel_adjust_tile_offset(int *x, int *y,
2354                                     const struct intel_plane_state *state, int plane,
2355                                     u32 old_offset, u32 new_offset)
2356 {
2357         const struct drm_i915_private *dev_priv = to_i915(state->base.plane->dev);
2358         const struct drm_framebuffer *fb = state->base.fb;
2359         unsigned int cpp = drm_format_plane_cpp(fb->pixel_format, plane);
2360         unsigned int rotation = state->base.rotation;
2361         unsigned int pitch = intel_fb_pitch(fb, plane, rotation);
2362
2363         WARN_ON(new_offset > old_offset);
2364
2365         if (fb->modifier[plane] != DRM_FORMAT_MOD_NONE) {
2366                 unsigned int tile_size, tile_width, tile_height;
2367                 unsigned int pitch_tiles;
2368
2369                 tile_size = intel_tile_size(dev_priv);
2370                 intel_tile_dims(dev_priv, &tile_width, &tile_height,
2371                                 fb->modifier[plane], cpp);
2372
2373                 if (intel_rotation_90_or_270(rotation)) {
2374                         pitch_tiles = pitch / tile_height;
2375                         swap(tile_width, tile_height);
2376                 } else {
2377                         pitch_tiles = pitch / (tile_width * cpp);
2378                 }
2379
2380                 _intel_adjust_tile_offset(x, y, tile_width, tile_height,
2381                                           tile_size, pitch_tiles,
2382                                           old_offset, new_offset);
2383         } else {
2384                 old_offset += *y * pitch + *x * cpp;
2385
2386                 *y = (old_offset - new_offset) / pitch;
2387                 *x = ((old_offset - new_offset) - *y * pitch) / cpp;
2388         }
2389
2390         return new_offset;
2391 }
2392
2393 /*
2394  * Computes the linear offset to the base tile and adjusts
2395  * x, y. bytes per pixel is assumed to be a power-of-two.
2396  *
2397  * In the 90/270 rotated case, x and y are assumed
2398  * to be already rotated to match the rotated GTT view, and
2399  * pitch is the tile_height aligned framebuffer height.
2400  *
2401  * This function is used when computing the derived information
2402  * under intel_framebuffer, so using any of that information
2403  * here is not allowed. Anything under drm_framebuffer can be
2404  * used. This is why the user has to pass in the pitch since it
2405  * is specified in the rotated orientation.
2406  */
2407 static u32 _intel_compute_tile_offset(const struct drm_i915_private *dev_priv,
2408                                       int *x, int *y,
2409                                       const struct drm_framebuffer *fb, int plane,
2410                                       unsigned int pitch,
2411                                       unsigned int rotation,
2412                                       u32 alignment)
2413 {
2414         uint64_t fb_modifier = fb->modifier[plane];
2415         unsigned int cpp = drm_format_plane_cpp(fb->pixel_format, plane);
2416         u32 offset, offset_aligned;
2417
2418         if (alignment)
2419                 alignment--;
2420
2421         if (fb_modifier != DRM_FORMAT_MOD_NONE) {
2422                 unsigned int tile_size, tile_width, tile_height;
2423                 unsigned int tile_rows, tiles, pitch_tiles;
2424
2425                 tile_size = intel_tile_size(dev_priv);
2426                 intel_tile_dims(dev_priv, &tile_width, &tile_height,
2427                                 fb_modifier, cpp);
2428
2429                 if (intel_rotation_90_or_270(rotation)) {
2430                         pitch_tiles = pitch / tile_height;
2431                         swap(tile_width, tile_height);
2432                 } else {
2433                         pitch_tiles = pitch / (tile_width * cpp);
2434                 }
2435
2436                 tile_rows = *y / tile_height;
2437                 *y %= tile_height;
2438
2439                 tiles = *x / tile_width;
2440                 *x %= tile_width;
2441
2442                 offset = (tile_rows * pitch_tiles + tiles) * tile_size;
2443                 offset_aligned = offset & ~alignment;
2444
2445                 _intel_adjust_tile_offset(x, y, tile_width, tile_height,
2446                                           tile_size, pitch_tiles,
2447                                           offset, offset_aligned);
2448         } else {
2449                 offset = *y * pitch + *x * cpp;
2450                 offset_aligned = offset & ~alignment;
2451
2452                 *y = (offset & alignment) / pitch;
2453                 *x = ((offset & alignment) - *y * pitch) / cpp;
2454         }
2455
2456         return offset_aligned;
2457 }
2458
2459 u32 intel_compute_tile_offset(int *x, int *y,
2460                               const struct intel_plane_state *state,
2461                               int plane)
2462 {
2463         const struct drm_i915_private *dev_priv = to_i915(state->base.plane->dev);
2464         const struct drm_framebuffer *fb = state->base.fb;
2465         unsigned int rotation = state->base.rotation;
2466         u32 alignment = intel_surf_alignment(dev_priv, fb->modifier[plane]);
2467         int pitch = intel_fb_pitch(fb, plane, rotation);
2468
2469         return _intel_compute_tile_offset(dev_priv, x, y, fb, plane, pitch,
2470                                           rotation, alignment);
2471 }
2472
2473 /* Convert the fb->offset[] linear offset into x/y offsets */
2474 static void intel_fb_offset_to_xy(int *x, int *y,
2475                                   const struct drm_framebuffer *fb, int plane)
2476 {
2477         unsigned int cpp = drm_format_plane_cpp(fb->pixel_format, plane);
2478         unsigned int pitch = fb->pitches[plane];
2479         u32 linear_offset = fb->offsets[plane];
2480
2481         *y = linear_offset / pitch;
2482         *x = linear_offset % pitch / cpp;
2483 }
2484
2485 static unsigned int intel_fb_modifier_to_tiling(uint64_t fb_modifier)
2486 {
2487         switch (fb_modifier) {
2488         case I915_FORMAT_MOD_X_TILED:
2489                 return I915_TILING_X;
2490         case I915_FORMAT_MOD_Y_TILED:
2491                 return I915_TILING_Y;
2492         default:
2493                 return I915_TILING_NONE;
2494         }
2495 }
2496
2497 static int
2498 intel_fill_fb_info(struct drm_i915_private *dev_priv,
2499                    struct drm_framebuffer *fb)
2500 {
2501         struct intel_framebuffer *intel_fb = to_intel_framebuffer(fb);
2502         struct intel_rotation_info *rot_info = &intel_fb->rot_info;
2503         u32 gtt_offset_rotated = 0;
2504         unsigned int max_size = 0;
2505         uint32_t format = fb->pixel_format;
2506         int i, num_planes = drm_format_num_planes(format);
2507         unsigned int tile_size = intel_tile_size(dev_priv);
2508
2509         for (i = 0; i < num_planes; i++) {
2510                 unsigned int width, height;
2511                 unsigned int cpp, size;
2512                 u32 offset;
2513                 int x, y;
2514
2515                 cpp = drm_format_plane_cpp(format, i);
2516                 width = drm_format_plane_width(fb->width, format, i);
2517                 height = drm_format_plane_height(fb->height, format, i);
2518
2519                 intel_fb_offset_to_xy(&x, &y, fb, i);
2520
2521                 /*
2522                  * The fence (if used) is aligned to the start of the object
2523                  * so having the framebuffer wrap around across the edge of the
2524                  * fenced region doesn't really work. We have no API to configure
2525                  * the fence start offset within the object (nor could we probably
2526                  * on gen2/3). So it's just easier if we just require that the
2527                  * fb layout agrees with the fence layout. We already check that the
2528                  * fb stride matches the fence stride elsewhere.
2529                  */
2530                 if (i915_gem_object_is_tiled(intel_fb->obj) &&
2531                     (x + width) * cpp > fb->pitches[i]) {
2532                         DRM_DEBUG("bad fb plane %d offset: 0x%x\n",
2533                                   i, fb->offsets[i]);
2534                         return -EINVAL;
2535                 }
2536
2537                 /*
2538                  * First pixel of the framebuffer from
2539                  * the start of the normal gtt mapping.
2540                  */
2541                 intel_fb->normal[i].x = x;
2542                 intel_fb->normal[i].y = y;
2543
2544                 offset = _intel_compute_tile_offset(dev_priv, &x, &y,
2545                                                     fb, 0, fb->pitches[i],
2546                                                     BIT(DRM_ROTATE_0), tile_size);
2547                 offset /= tile_size;
2548
2549                 if (fb->modifier[i] != DRM_FORMAT_MOD_NONE) {
2550                         unsigned int tile_width, tile_height;
2551                         unsigned int pitch_tiles;
2552                         struct drm_rect r;
2553
2554                         intel_tile_dims(dev_priv, &tile_width, &tile_height,
2555                                         fb->modifier[i], cpp);
2556
2557                         rot_info->plane[i].offset = offset;
2558                         rot_info->plane[i].stride = DIV_ROUND_UP(fb->pitches[i], tile_width * cpp);
2559                         rot_info->plane[i].width = DIV_ROUND_UP(x + width, tile_width);
2560                         rot_info->plane[i].height = DIV_ROUND_UP(y + height, tile_height);
2561
2562                         intel_fb->rotated[i].pitch =
2563                                 rot_info->plane[i].height * tile_height;
2564
2565                         /* how many tiles does this plane need */
2566                         size = rot_info->plane[i].stride * rot_info->plane[i].height;
2567                         /*
2568                          * If the plane isn't horizontally tile aligned,
2569                          * we need one more tile.
2570                          */
2571                         if (x != 0)
2572                                 size++;
2573
2574                         /* rotate the x/y offsets to match the GTT view */
2575                         r.x1 = x;
2576                         r.y1 = y;
2577                         r.x2 = x + width;
2578                         r.y2 = y + height;
2579                         drm_rect_rotate(&r,
2580                                         rot_info->plane[i].width * tile_width,
2581                                         rot_info->plane[i].height * tile_height,
2582                                         BIT(DRM_ROTATE_270));
2583                         x = r.x1;
2584                         y = r.y1;
2585
2586                         /* rotate the tile dimensions to match the GTT view */
2587                         pitch_tiles = intel_fb->rotated[i].pitch / tile_height;
2588                         swap(tile_width, tile_height);
2589
2590                         /*
2591                          * We only keep the x/y offsets, so push all of the
2592                          * gtt offset into the x/y offsets.
2593                          */
2594                         _intel_adjust_tile_offset(&x, &y, tile_size,
2595                                                   tile_width, tile_height, pitch_tiles,
2596                                                   gtt_offset_rotated * tile_size, 0);
2597
2598                         gtt_offset_rotated += rot_info->plane[i].width * rot_info->plane[i].height;
2599
2600                         /*
2601                          * First pixel of the framebuffer from
2602                          * the start of the rotated gtt mapping.
2603                          */
2604                         intel_fb->rotated[i].x = x;
2605                         intel_fb->rotated[i].y = y;
2606                 } else {
2607                         size = DIV_ROUND_UP((y + height) * fb->pitches[i] +
2608                                             x * cpp, tile_size);
2609                 }
2610
2611                 /* how many tiles in total needed in the bo */
2612                 max_size = max(max_size, offset + size);
2613         }
2614
2615         if (max_size * tile_size > to_intel_framebuffer(fb)->obj->base.size) {
2616                 DRM_DEBUG("fb too big for bo (need %u bytes, have %zu bytes)\n",
2617                           max_size * tile_size, to_intel_framebuffer(fb)->obj->base.size);
2618                 return -EINVAL;
2619         }
2620
2621         return 0;
2622 }
2623
2624 static int i9xx_format_to_fourcc(int format)
2625 {
2626         switch (format) {
2627         case DISPPLANE_8BPP:
2628                 return DRM_FORMAT_C8;
2629         case DISPPLANE_BGRX555:
2630                 return DRM_FORMAT_XRGB1555;
2631         case DISPPLANE_BGRX565:
2632                 return DRM_FORMAT_RGB565;
2633         default:
2634         case DISPPLANE_BGRX888:
2635                 return DRM_FORMAT_XRGB8888;
2636         case DISPPLANE_RGBX888:
2637                 return DRM_FORMAT_XBGR8888;
2638         case DISPPLANE_BGRX101010:
2639                 return DRM_FORMAT_XRGB2101010;
2640         case DISPPLANE_RGBX101010:
2641                 return DRM_FORMAT_XBGR2101010;
2642         }
2643 }
2644
2645 static int skl_format_to_fourcc(int format, bool rgb_order, bool alpha)
2646 {
2647         switch (format) {
2648         case PLANE_CTL_FORMAT_RGB_565:
2649                 return DRM_FORMAT_RGB565;
2650         default:
2651         case PLANE_CTL_FORMAT_XRGB_8888:
2652                 if (rgb_order) {
2653                         if (alpha)
2654                                 return DRM_FORMAT_ABGR8888;
2655                         else
2656                                 return DRM_FORMAT_XBGR8888;
2657                 } else {
2658                         if (alpha)
2659                                 return DRM_FORMAT_ARGB8888;
2660                         else
2661                                 return DRM_FORMAT_XRGB8888;
2662                 }
2663         case PLANE_CTL_FORMAT_XRGB_2101010:
2664                 if (rgb_order)
2665                         return DRM_FORMAT_XBGR2101010;
2666                 else
2667                         return DRM_FORMAT_XRGB2101010;
2668         }
2669 }
2670
2671 static bool
2672 intel_alloc_initial_plane_obj(struct intel_crtc *crtc,
2673                               struct intel_initial_plane_config *plane_config)
2674 {
2675         struct drm_device *dev = crtc->base.dev;
2676         struct drm_i915_private *dev_priv = to_i915(dev);
2677         struct i915_ggtt *ggtt = &dev_priv->ggtt;
2678         struct drm_i915_gem_object *obj = NULL;
2679         struct drm_mode_fb_cmd2 mode_cmd = { 0 };
2680         struct drm_framebuffer *fb = &plane_config->fb->base;
2681         u32 base_aligned = round_down(plane_config->base, PAGE_SIZE);
2682         u32 size_aligned = round_up(plane_config->base + plane_config->size,
2683                                     PAGE_SIZE);
2684
2685         size_aligned -= base_aligned;
2686
2687         if (plane_config->size == 0)
2688                 return false;
2689
2690         /* If the FB is too big, just don't use it since fbdev is not very
2691          * important and we should probably use that space with FBC or other
2692          * features. */
2693         if (size_aligned * 2 > ggtt->stolen_usable_size)
2694                 return false;
2695
2696         mutex_lock(&dev->struct_mutex);
2697
2698         obj = i915_gem_object_create_stolen_for_preallocated(dev,
2699                                                              base_aligned,
2700                                                              base_aligned,
2701                                                              size_aligned);
2702         if (!obj) {
2703                 mutex_unlock(&dev->struct_mutex);
2704                 return false;
2705         }
2706
2707         if (plane_config->tiling == I915_TILING_X)
2708                 obj->tiling_and_stride = fb->pitches[0] | I915_TILING_X;
2709
2710         mode_cmd.pixel_format = fb->pixel_format;
2711         mode_cmd.width = fb->width;
2712         mode_cmd.height = fb->height;
2713         mode_cmd.pitches[0] = fb->pitches[0];
2714         mode_cmd.modifier[0] = fb->modifier[0];
2715         mode_cmd.flags = DRM_MODE_FB_MODIFIERS;
2716
2717         if (intel_framebuffer_init(dev, to_intel_framebuffer(fb),
2718                                    &mode_cmd, obj)) {
2719                 DRM_DEBUG_KMS("intel fb init failed\n");
2720                 goto out_unref_obj;
2721         }
2722
2723         mutex_unlock(&dev->struct_mutex);
2724
2725         DRM_DEBUG_KMS("initial plane fb obj %p\n", obj);
2726         return true;
2727
2728 out_unref_obj:
2729         i915_gem_object_put(obj);
2730         mutex_unlock(&dev->struct_mutex);
2731         return false;
2732 }
2733
2734 /* Update plane->state->fb to match plane->fb after driver-internal updates */
2735 static void
2736 update_state_fb(struct drm_plane *plane)
2737 {
2738         if (plane->fb == plane->state->fb)
2739                 return;
2740
2741         if (plane->state->fb)
2742                 drm_framebuffer_unreference(plane->state->fb);
2743         plane->state->fb = plane->fb;
2744         if (plane->state->fb)
2745                 drm_framebuffer_reference(plane->state->fb);
2746 }
2747
2748 static void
2749 intel_find_initial_plane_obj(struct intel_crtc *intel_crtc,
2750                              struct intel_initial_plane_config *plane_config)
2751 {
2752         struct drm_device *dev = intel_crtc->base.dev;
2753         struct drm_i915_private *dev_priv = to_i915(dev);
2754         struct drm_crtc *c;
2755         struct intel_crtc *i;
2756         struct drm_i915_gem_object *obj;
2757         struct drm_plane *primary = intel_crtc->base.primary;
2758         struct drm_plane_state *plane_state = primary->state;
2759         struct drm_crtc_state *crtc_state = intel_crtc->base.state;
2760         struct intel_plane *intel_plane = to_intel_plane(primary);
2761         struct intel_plane_state *intel_state =
2762                 to_intel_plane_state(plane_state);
2763         struct drm_framebuffer *fb;
2764
2765         if (!plane_config->fb)
2766                 return;
2767
2768         if (intel_alloc_initial_plane_obj(intel_crtc, plane_config)) {
2769                 fb = &plane_config->fb->base;
2770                 goto valid_fb;
2771         }
2772
2773         kfree(plane_config->fb);
2774
2775         /*
2776          * Failed to alloc the obj, check to see if we should share
2777          * an fb with another CRTC instead
2778          */
2779         for_each_crtc(dev, c) {
2780                 i = to_intel_crtc(c);
2781
2782                 if (c == &intel_crtc->base)
2783                         continue;
2784
2785                 if (!i->active)
2786                         continue;
2787
2788                 fb = c->primary->fb;
2789                 if (!fb)
2790                         continue;
2791
2792                 obj = intel_fb_obj(fb);
2793                 if (i915_gem_obj_ggtt_offset(obj) == plane_config->base) {
2794                         drm_framebuffer_reference(fb);
2795                         goto valid_fb;
2796                 }
2797         }
2798
2799         /*
2800          * We've failed to reconstruct the BIOS FB.  Current display state
2801          * indicates that the primary plane is visible, but has a NULL FB,
2802          * which will lead to problems later if we don't fix it up.  The
2803          * simplest solution is to just disable the primary plane now and
2804          * pretend the BIOS never had it enabled.
2805          */
2806         to_intel_plane_state(plane_state)->visible = false;
2807         crtc_state->plane_mask &= ~(1 << drm_plane_index(primary));
2808         intel_pre_disable_primary_noatomic(&intel_crtc->base);
2809         intel_plane->disable_plane(primary, &intel_crtc->base);
2810
2811         return;
2812
2813 valid_fb:
2814         plane_state->src_x = 0;
2815         plane_state->src_y = 0;
2816         plane_state->src_w = fb->width << 16;
2817         plane_state->src_h = fb->height << 16;
2818
2819         plane_state->crtc_x = 0;
2820         plane_state->crtc_y = 0;
2821         plane_state->crtc_w = fb->width;
2822         plane_state->crtc_h = fb->height;
2823
2824         intel_state->src.x1 = plane_state->src_x;
2825         intel_state->src.y1 = plane_state->src_y;
2826         intel_state->src.x2 = plane_state->src_x + plane_state->src_w;
2827         intel_state->src.y2 = plane_state->src_y + plane_state->src_h;
2828         intel_state->dst.x1 = plane_state->crtc_x;
2829         intel_state->dst.y1 = plane_state->crtc_y;
2830         intel_state->dst.x2 = plane_state->crtc_x + plane_state->crtc_w;
2831         intel_state->dst.y2 = plane_state->crtc_y + plane_state->crtc_h;
2832
2833         obj = intel_fb_obj(fb);
2834         if (i915_gem_object_is_tiled(obj))
2835                 dev_priv->preserve_bios_swizzle = true;
2836
2837         drm_framebuffer_reference(fb);
2838         primary->fb = primary->state->fb = fb;
2839         primary->crtc = primary->state->crtc = &intel_crtc->base;
2840         intel_crtc->base.state->plane_mask |= (1 << drm_plane_index(primary));
2841         atomic_or(to_intel_plane(primary)->frontbuffer_bit,
2842                   &obj->frontbuffer_bits);
2843 }
2844
2845 static int skl_max_plane_width(const struct drm_framebuffer *fb, int plane,
2846                                unsigned int rotation)
2847 {
2848         int cpp = drm_format_plane_cpp(fb->pixel_format, plane);
2849
2850         switch (fb->modifier[plane]) {
2851         case DRM_FORMAT_MOD_NONE:
2852         case I915_FORMAT_MOD_X_TILED:
2853                 switch (cpp) {
2854                 case 8:
2855                         return 4096;
2856                 case 4:
2857                 case 2:
2858                 case 1:
2859                         return 8192;
2860                 default:
2861                         MISSING_CASE(cpp);
2862                         break;
2863                 }
2864                 break;
2865         case I915_FORMAT_MOD_Y_TILED:
2866         case I915_FORMAT_MOD_Yf_TILED:
2867                 switch (cpp) {
2868                 case 8:
2869                         return 2048;
2870                 case 4:
2871                         return 4096;
2872                 case 2:
2873                 case 1:
2874                         return 8192;
2875                 default:
2876                         MISSING_CASE(cpp);
2877                         break;
2878                 }
2879                 break;
2880         default:
2881                 MISSING_CASE(fb->modifier[plane]);
2882         }
2883
2884         return 2048;
2885 }
2886
2887 static int skl_check_main_surface(struct intel_plane_state *plane_state)
2888 {
2889         const struct drm_i915_private *dev_priv = to_i915(plane_state->base.plane->dev);
2890         const struct drm_framebuffer *fb = plane_state->base.fb;
2891         unsigned int rotation = plane_state->base.rotation;
2892         int x = plane_state->src.x1 >> 16;
2893         int y = plane_state->src.y1 >> 16;
2894         int w = drm_rect_width(&plane_state->src) >> 16;
2895         int h = drm_rect_height(&plane_state->src) >> 16;
2896         int max_width = skl_max_plane_width(fb, 0, rotation);
2897         int max_height = 4096;
2898         u32 alignment, offset;
2899
2900         if (w > max_width || h > max_height) {
2901                 DRM_DEBUG_KMS("requested Y/RGB source size %dx%d too big (limit %dx%d)\n",
2902                               w, h, max_width, max_height);
2903                 return -EINVAL;
2904         }
2905
2906         intel_add_fb_offsets(&x, &y, plane_state, 0);
2907         offset = intel_compute_tile_offset(&x, &y, plane_state, 0);
2908
2909         alignment = intel_surf_alignment(dev_priv, fb->modifier[0]);
2910
2911         /*
2912          * When using an X-tiled surface, the plane blows up
2913          * if the x offset + width exceed the stride.
2914          *
2915          * TODO: linear and Y-tiled seem fine, Yf untested,
2916          */
2917         if (fb->modifier[0] == I915_FORMAT_MOD_X_TILED) {
2918                 int cpp = drm_format_plane_cpp(fb->pixel_format, 0);
2919
2920                 while ((x + w) * cpp > fb->pitches[0]) {
2921                         if (offset == 0) {
2922                                 DRM_DEBUG_KMS("Unable to find suitable display surface offset\n");
2923                                 return -EINVAL;
2924                         }
2925
2926                         offset = intel_adjust_tile_offset(&x, &y, plane_state, 0,
2927                                                           offset, offset - alignment);
2928                 }
2929         }
2930
2931         plane_state->main.offset = offset;
2932         plane_state->main.x = x;
2933         plane_state->main.y = y;
2934
2935         return 0;
2936 }
2937
2938 int skl_check_plane_surface(struct intel_plane_state *plane_state)
2939 {
2940         const struct drm_framebuffer *fb = plane_state->base.fb;
2941         unsigned int rotation = plane_state->base.rotation;
2942         int ret;
2943
2944         /* Rotate src coordinates to match rotated GTT view */
2945         if (intel_rotation_90_or_270(rotation))
2946                 drm_rect_rotate(&plane_state->src,
2947                                 fb->width, fb->height, BIT(DRM_ROTATE_270));
2948
2949         ret = skl_check_main_surface(plane_state);
2950         if (ret)
2951                 return ret;
2952
2953         return 0;
2954 }
2955
2956 static void i9xx_update_primary_plane(struct drm_plane *primary,
2957                                       const struct intel_crtc_state *crtc_state,
2958                                       const struct intel_plane_state *plane_state)
2959 {
2960         struct drm_device *dev = primary->dev;
2961         struct drm_i915_private *dev_priv = to_i915(dev);
2962         struct intel_crtc *intel_crtc = to_intel_crtc(crtc_state->base.crtc);
2963         struct drm_framebuffer *fb = plane_state->base.fb;
2964         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
2965         int plane = intel_crtc->plane;
2966         u32 linear_offset;
2967         u32 dspcntr;
2968         i915_reg_t reg = DSPCNTR(plane);
2969         unsigned int rotation = plane_state->base.rotation;
2970         int x = plane_state->src.x1 >> 16;
2971         int y = plane_state->src.y1 >> 16;
2972
2973         dspcntr = DISPPLANE_GAMMA_ENABLE;
2974
2975         dspcntr |= DISPLAY_PLANE_ENABLE;
2976
2977         if (INTEL_INFO(dev)->gen < 4) {
2978                 if (intel_crtc->pipe == PIPE_B)
2979                         dspcntr |= DISPPLANE_SEL_PIPE_B;
2980
2981                 /* pipesrc and dspsize control the size that is scaled from,
2982                  * which should always be the user's requested size.
2983                  */
2984                 I915_WRITE(DSPSIZE(plane),
2985                            ((crtc_state->pipe_src_h - 1) << 16) |
2986                            (crtc_state->pipe_src_w - 1));
2987                 I915_WRITE(DSPPOS(plane), 0);
2988         } else if (IS_CHERRYVIEW(dev) && plane == PLANE_B) {
2989                 I915_WRITE(PRIMSIZE(plane),
2990                            ((crtc_state->pipe_src_h - 1) << 16) |
2991                            (crtc_state->pipe_src_w - 1));
2992                 I915_WRITE(PRIMPOS(plane), 0);
2993                 I915_WRITE(PRIMCNSTALPHA(plane), 0);
2994         }
2995
2996         switch (fb->pixel_format) {
2997         case DRM_FORMAT_C8:
2998                 dspcntr |= DISPPLANE_8BPP;
2999                 break;
3000         case DRM_FORMAT_XRGB1555:
3001                 dspcntr |= DISPPLANE_BGRX555;
3002                 break;
3003         case DRM_FORMAT_RGB565:
3004                 dspcntr |= DISPPLANE_BGRX565;
3005                 break;
3006         case DRM_FORMAT_XRGB8888:
3007                 dspcntr |= DISPPLANE_BGRX888;
3008                 break;
3009         case DRM_FORMAT_XBGR8888:
3010                 dspcntr |= DISPPLANE_RGBX888;
3011                 break;
3012         case DRM_FORMAT_XRGB2101010:
3013                 dspcntr |= DISPPLANE_BGRX101010;
3014                 break;
3015         case DRM_FORMAT_XBGR2101010:
3016                 dspcntr |= DISPPLANE_RGBX101010;
3017                 break;
3018         default:
3019                 BUG();
3020         }
3021
3022         if (INTEL_GEN(dev_priv) >= 4 &&
3023             fb->modifier[0] == I915_FORMAT_MOD_X_TILED)
3024                 dspcntr |= DISPPLANE_TILED;
3025
3026         if (IS_G4X(dev))
3027                 dspcntr |= DISPPLANE_TRICKLE_FEED_DISABLE;
3028
3029         intel_add_fb_offsets(&x, &y, plane_state, 0);
3030
3031         if (INTEL_INFO(dev)->gen >= 4)
3032                 intel_crtc->dspaddr_offset =
3033                         intel_compute_tile_offset(&x, &y, plane_state, 0);
3034
3035         if (rotation == BIT(DRM_ROTATE_180)) {
3036                 dspcntr |= DISPPLANE_ROTATE_180;
3037
3038                 x += (crtc_state->pipe_src_w - 1);
3039                 y += (crtc_state->pipe_src_h - 1);
3040         }
3041
3042         linear_offset = intel_fb_xy_to_linear(x, y, plane_state, 0);
3043
3044         if (INTEL_INFO(dev)->gen < 4)
3045                 intel_crtc->dspaddr_offset = linear_offset;
3046
3047         intel_crtc->adjusted_x = x;
3048         intel_crtc->adjusted_y = y;
3049
3050         I915_WRITE(reg, dspcntr);
3051
3052         I915_WRITE(DSPSTRIDE(plane), fb->pitches[0]);
3053         if (INTEL_INFO(dev)->gen >= 4) {
3054                 I915_WRITE(DSPSURF(plane),
3055                            intel_fb_gtt_offset(fb, rotation) +
3056                            intel_crtc->dspaddr_offset);
3057                 I915_WRITE(DSPTILEOFF(plane), (y << 16) | x);
3058                 I915_WRITE(DSPLINOFF(plane), linear_offset);
3059         } else
3060                 I915_WRITE(DSPADDR(plane), i915_gem_obj_ggtt_offset(obj) + linear_offset);
3061         POSTING_READ(reg);
3062 }
3063
3064 static void i9xx_disable_primary_plane(struct drm_plane *primary,
3065                                        struct drm_crtc *crtc)
3066 {
3067         struct drm_device *dev = crtc->dev;
3068         struct drm_i915_private *dev_priv = to_i915(dev);
3069         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3070         int plane = intel_crtc->plane;
3071
3072         I915_WRITE(DSPCNTR(plane), 0);
3073         if (INTEL_INFO(dev_priv)->gen >= 4)
3074                 I915_WRITE(DSPSURF(plane), 0);
3075         else
3076                 I915_WRITE(DSPADDR(plane), 0);
3077         POSTING_READ(DSPCNTR(plane));
3078 }
3079
3080 static void ironlake_update_primary_plane(struct drm_plane *primary,
3081                                           const struct intel_crtc_state *crtc_state,
3082                                           const struct intel_plane_state *plane_state)
3083 {
3084         struct drm_device *dev = primary->dev;
3085         struct drm_i915_private *dev_priv = to_i915(dev);
3086         struct intel_crtc *intel_crtc = to_intel_crtc(crtc_state->base.crtc);
3087         struct drm_framebuffer *fb = plane_state->base.fb;
3088         int plane = intel_crtc->plane;
3089         u32 linear_offset;
3090         u32 dspcntr;
3091         i915_reg_t reg = DSPCNTR(plane);
3092         unsigned int rotation = plane_state->base.rotation;
3093         int x = plane_state->src.x1 >> 16;
3094         int y = plane_state->src.y1 >> 16;
3095
3096         dspcntr = DISPPLANE_GAMMA_ENABLE;
3097         dspcntr |= DISPLAY_PLANE_ENABLE;
3098
3099         if (IS_HASWELL(dev) || IS_BROADWELL(dev))
3100                 dspcntr |= DISPPLANE_PIPE_CSC_ENABLE;
3101
3102         switch (fb->pixel_format) {
3103         case DRM_FORMAT_C8:
3104                 dspcntr |= DISPPLANE_8BPP;
3105                 break;
3106         case DRM_FORMAT_RGB565:
3107                 dspcntr |= DISPPLANE_BGRX565;
3108                 break;
3109         case DRM_FORMAT_XRGB8888:
3110                 dspcntr |= DISPPLANE_BGRX888;
3111                 break;
3112         case DRM_FORMAT_XBGR8888:
3113                 dspcntr |= DISPPLANE_RGBX888;
3114                 break;
3115         case DRM_FORMAT_XRGB2101010:
3116                 dspcntr |= DISPPLANE_BGRX101010;
3117                 break;
3118         case DRM_FORMAT_XBGR2101010:
3119                 dspcntr |= DISPPLANE_RGBX101010;
3120                 break;
3121         default:
3122                 BUG();
3123         }
3124
3125         if (fb->modifier[0] == I915_FORMAT_MOD_X_TILED)
3126                 dspcntr |= DISPPLANE_TILED;
3127
3128         if (!IS_HASWELL(dev) && !IS_BROADWELL(dev))
3129                 dspcntr |= DISPPLANE_TRICKLE_FEED_DISABLE;
3130
3131         intel_add_fb_offsets(&x, &y, plane_state, 0);
3132
3133         intel_crtc->dspaddr_offset =
3134                 intel_compute_tile_offset(&x, &y, plane_state, 0);
3135
3136         if (rotation == BIT(DRM_ROTATE_180)) {
3137                 dspcntr |= DISPPLANE_ROTATE_180;
3138
3139                 if (!IS_HASWELL(dev) && !IS_BROADWELL(dev)) {
3140                         x += (crtc_state->pipe_src_w - 1);
3141                         y += (crtc_state->pipe_src_h - 1);
3142                 }
3143         }
3144
3145         linear_offset = intel_fb_xy_to_linear(x, y, plane_state, 0);
3146
3147         intel_crtc->adjusted_x = x;
3148         intel_crtc->adjusted_y = y;
3149
3150         I915_WRITE(reg, dspcntr);
3151
3152         I915_WRITE(DSPSTRIDE(plane), fb->pitches[0]);
3153         I915_WRITE(DSPSURF(plane),
3154                    intel_fb_gtt_offset(fb, rotation) +
3155                    intel_crtc->dspaddr_offset);
3156         if (IS_HASWELL(dev) || IS_BROADWELL(dev)) {
3157                 I915_WRITE(DSPOFFSET(plane), (y << 16) | x);
3158         } else {
3159                 I915_WRITE(DSPTILEOFF(plane), (y << 16) | x);
3160                 I915_WRITE(DSPLINOFF(plane), linear_offset);
3161         }
3162         POSTING_READ(reg);
3163 }
3164
3165 u32 intel_fb_stride_alignment(const struct drm_i915_private *dev_priv,
3166                               uint64_t fb_modifier, uint32_t pixel_format)
3167 {
3168         if (fb_modifier == DRM_FORMAT_MOD_NONE) {
3169                 return 64;
3170         } else {
3171                 int cpp = drm_format_plane_cpp(pixel_format, 0);
3172
3173                 return intel_tile_width_bytes(dev_priv, fb_modifier, cpp);
3174         }
3175 }
3176
3177 u32 intel_fb_gtt_offset(struct drm_framebuffer *fb,
3178                         unsigned int rotation)
3179 {
3180         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
3181         struct i915_ggtt_view view;
3182         u64 offset;
3183
3184         intel_fill_fb_ggtt_view(&view, fb, rotation);
3185
3186         offset = i915_gem_obj_ggtt_offset_view(obj, &view);
3187
3188         WARN_ON(upper_32_bits(offset));
3189
3190         return lower_32_bits(offset);
3191 }
3192
3193 static void skl_detach_scaler(struct intel_crtc *intel_crtc, int id)
3194 {
3195         struct drm_device *dev = intel_crtc->base.dev;
3196         struct drm_i915_private *dev_priv = to_i915(dev);
3197
3198         I915_WRITE(SKL_PS_CTRL(intel_crtc->pipe, id), 0);
3199         I915_WRITE(SKL_PS_WIN_POS(intel_crtc->pipe, id), 0);
3200         I915_WRITE(SKL_PS_WIN_SZ(intel_crtc->pipe, id), 0);
3201 }
3202
3203 /*
3204  * This function detaches (aka. unbinds) unused scalers in hardware
3205  */
3206 static void skl_detach_scalers(struct intel_crtc *intel_crtc)
3207 {
3208         struct intel_crtc_scaler_state *scaler_state;
3209         int i;
3210
3211         scaler_state = &intel_crtc->config->scaler_state;
3212
3213         /* loop through and disable scalers that aren't in use */
3214         for (i = 0; i < intel_crtc->num_scalers; i++) {
3215                 if (!scaler_state->scalers[i].in_use)
3216                         skl_detach_scaler(intel_crtc, i);
3217         }
3218 }
3219
3220 u32 skl_plane_stride(const struct drm_framebuffer *fb, int plane,
3221                      unsigned int rotation)
3222 {
3223         const struct drm_i915_private *dev_priv = to_i915(fb->dev);
3224         u32 stride = intel_fb_pitch(fb, plane, rotation);
3225
3226         /*
3227          * The stride is either expressed as a multiple of 64 bytes chunks for
3228          * linear buffers or in number of tiles for tiled buffers.
3229          */
3230         if (intel_rotation_90_or_270(rotation)) {
3231                 int cpp = drm_format_plane_cpp(fb->pixel_format, plane);
3232
3233                 stride /= intel_tile_height(dev_priv, fb->modifier[0], cpp);
3234         } else {
3235                 stride /= intel_fb_stride_alignment(dev_priv, fb->modifier[0],
3236                                                     fb->pixel_format);
3237         }
3238
3239         return stride;
3240 }
3241
3242 u32 skl_plane_ctl_format(uint32_t pixel_format)
3243 {
3244         switch (pixel_format) {
3245         case DRM_FORMAT_C8:
3246                 return PLANE_CTL_FORMAT_INDEXED;
3247         case DRM_FORMAT_RGB565:
3248                 return PLANE_CTL_FORMAT_RGB_565;
3249         case DRM_FORMAT_XBGR8888:
3250                 return PLANE_CTL_FORMAT_XRGB_8888 | PLANE_CTL_ORDER_RGBX;
3251         case DRM_FORMAT_XRGB8888:
3252                 return PLANE_CTL_FORMAT_XRGB_8888;
3253         /*
3254          * XXX: For ARBG/ABGR formats we default to expecting scanout buffers
3255          * to be already pre-multiplied. We need to add a knob (or a different
3256          * DRM_FORMAT) for user-space to configure that.
3257          */
3258         case DRM_FORMAT_ABGR8888:
3259                 return PLANE_CTL_FORMAT_XRGB_8888 | PLANE_CTL_ORDER_RGBX |
3260                         PLANE_CTL_ALPHA_SW_PREMULTIPLY;
3261         case DRM_FORMAT_ARGB8888:
3262                 return PLANE_CTL_FORMAT_XRGB_8888 |
3263                         PLANE_CTL_ALPHA_SW_PREMULTIPLY;
3264         case DRM_FORMAT_XRGB2101010:
3265                 return PLANE_CTL_FORMAT_XRGB_2101010;
3266         case DRM_FORMAT_XBGR2101010:
3267                 return PLANE_CTL_ORDER_RGBX | PLANE_CTL_FORMAT_XRGB_2101010;
3268         case DRM_FORMAT_YUYV:
3269                 return PLANE_CTL_FORMAT_YUV422 | PLANE_CTL_YUV422_YUYV;
3270         case DRM_FORMAT_YVYU:
3271                 return PLANE_CTL_FORMAT_YUV422 | PLANE_CTL_YUV422_YVYU;
3272         case DRM_FORMAT_UYVY:
3273                 return PLANE_CTL_FORMAT_YUV422 | PLANE_CTL_YUV422_UYVY;
3274         case DRM_FORMAT_VYUY:
3275                 return PLANE_CTL_FORMAT_YUV422 | PLANE_CTL_YUV422_VYUY;
3276         default:
3277                 MISSING_CASE(pixel_format);
3278         }
3279
3280         return 0;
3281 }
3282
3283 u32 skl_plane_ctl_tiling(uint64_t fb_modifier)
3284 {
3285         switch (fb_modifier) {
3286         case DRM_FORMAT_MOD_NONE:
3287                 break;
3288         case I915_FORMAT_MOD_X_TILED:
3289                 return PLANE_CTL_TILED_X;
3290         case I915_FORMAT_MOD_Y_TILED:
3291                 return PLANE_CTL_TILED_Y;
3292         case I915_FORMAT_MOD_Yf_TILED:
3293                 return PLANE_CTL_TILED_YF;
3294         default:
3295                 MISSING_CASE(fb_modifier);
3296         }
3297
3298         return 0;
3299 }
3300
3301 u32 skl_plane_ctl_rotation(unsigned int rotation)
3302 {
3303         switch (rotation) {
3304         case BIT(DRM_ROTATE_0):
3305                 break;
3306         /*
3307          * DRM_ROTATE_ is counter clockwise to stay compatible with Xrandr
3308          * while i915 HW rotation is clockwise, thats why this swapping.
3309          */
3310         case BIT(DRM_ROTATE_90):
3311                 return PLANE_CTL_ROTATE_270;
3312         case BIT(DRM_ROTATE_180):
3313                 return PLANE_CTL_ROTATE_180;
3314         case BIT(DRM_ROTATE_270):
3315                 return PLANE_CTL_ROTATE_90;
3316         default:
3317                 MISSING_CASE(rotation);
3318         }
3319
3320         return 0;
3321 }
3322
3323 static void skylake_update_primary_plane(struct drm_plane *plane,
3324                                          const struct intel_crtc_state *crtc_state,
3325                                          const struct intel_plane_state *plane_state)
3326 {
3327         struct drm_device *dev = plane->dev;
3328         struct drm_i915_private *dev_priv = to_i915(dev);
3329         struct intel_crtc *intel_crtc = to_intel_crtc(crtc_state->base.crtc);
3330         struct drm_framebuffer *fb = plane_state->base.fb;
3331         int pipe = intel_crtc->pipe;
3332         u32 plane_ctl;
3333         unsigned int rotation = plane_state->base.rotation;
3334         u32 stride = skl_plane_stride(fb, 0, rotation);
3335         u32 surf_addr = plane_state->main.offset;
3336         int scaler_id = plane_state->scaler_id;
3337         int src_x = plane_state->main.x;
3338         int src_y = plane_state->main.y;
3339         int src_w = drm_rect_width(&plane_state->src) >> 16;
3340         int src_h = drm_rect_height(&plane_state->src) >> 16;
3341         int dst_x = plane_state->dst.x1;
3342         int dst_y = plane_state->dst.y1;
3343         int dst_w = drm_rect_width(&plane_state->dst);
3344         int dst_h = drm_rect_height(&plane_state->dst);
3345
3346         plane_ctl = PLANE_CTL_ENABLE |
3347                     PLANE_CTL_PIPE_GAMMA_ENABLE |
3348                     PLANE_CTL_PIPE_CSC_ENABLE;
3349
3350         plane_ctl |= skl_plane_ctl_format(fb->pixel_format);
3351         plane_ctl |= skl_plane_ctl_tiling(fb->modifier[0]);
3352         plane_ctl |= PLANE_CTL_PLANE_GAMMA_DISABLE;
3353         plane_ctl |= skl_plane_ctl_rotation(rotation);
3354
3355         /* Sizes are 0 based */
3356         src_w--;
3357         src_h--;
3358         dst_w--;
3359         dst_h--;
3360
3361         intel_crtc->adjusted_x = src_x;
3362         intel_crtc->adjusted_y = src_y;
3363
3364         I915_WRITE(PLANE_CTL(pipe, 0), plane_ctl);
3365         I915_WRITE(PLANE_OFFSET(pipe, 0), (src_y << 16) | src_x);
3366         I915_WRITE(PLANE_STRIDE(pipe, 0), stride);
3367         I915_WRITE(PLANE_SIZE(pipe, 0), (src_h << 16) | src_w);
3368
3369         if (scaler_id >= 0) {
3370                 uint32_t ps_ctrl = 0;
3371
3372                 WARN_ON(!dst_w || !dst_h);
3373                 ps_ctrl = PS_SCALER_EN | PS_PLANE_SEL(0) |
3374                         crtc_state->scaler_state.scalers[scaler_id].mode;
3375                 I915_WRITE(SKL_PS_CTRL(pipe, scaler_id), ps_ctrl);
3376                 I915_WRITE(SKL_PS_PWR_GATE(pipe, scaler_id), 0);
3377                 I915_WRITE(SKL_PS_WIN_POS(pipe, scaler_id), (dst_x << 16) | dst_y);
3378                 I915_WRITE(SKL_PS_WIN_SZ(pipe, scaler_id), (dst_w << 16) | dst_h);
3379                 I915_WRITE(PLANE_POS(pipe, 0), 0);
3380         } else {
3381                 I915_WRITE(PLANE_POS(pipe, 0), (dst_y << 16) | dst_x);
3382         }
3383
3384         I915_WRITE(PLANE_SURF(pipe, 0),
3385                    intel_fb_gtt_offset(fb, rotation) + surf_addr);
3386
3387         POSTING_READ(PLANE_SURF(pipe, 0));
3388 }
3389
3390 static void skylake_disable_primary_plane(struct drm_plane *primary,
3391                                           struct drm_crtc *crtc)
3392 {
3393         struct drm_device *dev = crtc->dev;
3394         struct drm_i915_private *dev_priv = to_i915(dev);
3395         int pipe = to_intel_crtc(crtc)->pipe;
3396
3397         I915_WRITE(PLANE_CTL(pipe, 0), 0);
3398         I915_WRITE(PLANE_SURF(pipe, 0), 0);
3399         POSTING_READ(PLANE_SURF(pipe, 0));
3400 }
3401
3402 /* Assume fb object is pinned & idle & fenced and just update base pointers */
3403 static int
3404 intel_pipe_set_base_atomic(struct drm_crtc *crtc, struct drm_framebuffer *fb,
3405                            int x, int y, enum mode_set_atomic state)
3406 {
3407         /* Support for kgdboc is disabled, this needs a major rework. */
3408         DRM_ERROR("legacy panic handler not supported any more.\n");
3409
3410         return -ENODEV;
3411 }
3412
3413 static void intel_complete_page_flips(struct drm_i915_private *dev_priv)
3414 {
3415         struct intel_crtc *crtc;
3416
3417         for_each_intel_crtc(&dev_priv->drm, crtc)
3418                 intel_finish_page_flip_cs(dev_priv, crtc->pipe);
3419 }
3420
3421 static void intel_update_primary_planes(struct drm_device *dev)
3422 {
3423         struct drm_crtc *crtc;
3424
3425         for_each_crtc(dev, crtc) {
3426                 struct intel_plane *plane = to_intel_plane(crtc->primary);
3427                 struct intel_plane_state *plane_state =
3428                         to_intel_plane_state(plane->base.state);
3429
3430                 if (plane_state->visible)
3431                         plane->update_plane(&plane->base,
3432                                             to_intel_crtc_state(crtc->state),
3433                                             plane_state);
3434         }
3435 }
3436
3437 static int
3438 __intel_display_resume(struct drm_device *dev,
3439                        struct drm_atomic_state *state)
3440 {
3441         struct drm_crtc_state *crtc_state;
3442         struct drm_crtc *crtc;
3443         int i, ret;
3444
3445         intel_modeset_setup_hw_state(dev);
3446         i915_redisable_vga(dev);
3447
3448         if (!state)
3449                 return 0;
3450
3451         for_each_crtc_in_state(state, crtc, crtc_state, i) {
3452                 /*
3453                  * Force recalculation even if we restore
3454                  * current state. With fast modeset this may not result
3455                  * in a modeset when the state is compatible.
3456                  */
3457                 crtc_state->mode_changed = true;
3458         }
3459
3460         /* ignore any reset values/BIOS leftovers in the WM registers */
3461         to_intel_atomic_state(state)->skip_intermediate_wm = true;
3462
3463         ret = drm_atomic_commit(state);
3464
3465         WARN_ON(ret == -EDEADLK);
3466         return ret;
3467 }
3468
3469 static bool gpu_reset_clobbers_display(struct drm_i915_private *dev_priv)
3470 {
3471         return intel_has_gpu_reset(dev_priv) &&
3472                 INTEL_GEN(dev_priv) < 5 && !IS_G4X(dev_priv);
3473 }
3474
3475 void intel_prepare_reset(struct drm_i915_private *dev_priv)
3476 {
3477         struct drm_device *dev = &dev_priv->drm;
3478         struct drm_modeset_acquire_ctx *ctx = &dev_priv->reset_ctx;
3479         struct drm_atomic_state *state;
3480         int ret;
3481
3482         /*
3483          * Need mode_config.mutex so that we don't
3484          * trample ongoing ->detect() and whatnot.
3485          */
3486         mutex_lock(&dev->mode_config.mutex);
3487         drm_modeset_acquire_init(ctx, 0);
3488         while (1) {
3489                 ret = drm_modeset_lock_all_ctx(dev, ctx);
3490                 if (ret != -EDEADLK)
3491                         break;
3492
3493                 drm_modeset_backoff(ctx);
3494         }
3495
3496         /* reset doesn't touch the display, but flips might get nuked anyway, */
3497         if (!i915.force_reset_modeset_test &&
3498             !gpu_reset_clobbers_display(dev_priv))
3499                 return;
3500
3501         /*
3502          * Disabling the crtcs gracefully seems nicer. Also the
3503          * g33 docs say we should at least disable all the planes.
3504          */
3505         state = drm_atomic_helper_duplicate_state(dev, ctx);
3506         if (IS_ERR(state)) {
3507                 ret = PTR_ERR(state);
3508                 state = NULL;
3509                 DRM_ERROR("Duplicating state failed with %i\n", ret);
3510                 goto err;
3511         }
3512
3513         ret = drm_atomic_helper_disable_all(dev, ctx);
3514         if (ret) {
3515                 DRM_ERROR("Suspending crtc's failed with %i\n", ret);
3516                 goto err;
3517         }
3518
3519         dev_priv->modeset_restore_state = state;
3520         state->acquire_ctx = ctx;
3521         return;
3522
3523 err:
3524         drm_atomic_state_free(state);
3525 }
3526
3527 void intel_finish_reset(struct drm_i915_private *dev_priv)
3528 {
3529         struct drm_device *dev = &dev_priv->drm;
3530         struct drm_modeset_acquire_ctx *ctx = &dev_priv->reset_ctx;
3531         struct drm_atomic_state *state = dev_priv->modeset_restore_state;
3532         int ret;
3533
3534         /*
3535          * Flips in the rings will be nuked by the reset,
3536          * so complete all pending flips so that user space
3537          * will get its events and not get stuck.
3538          */
3539         intel_complete_page_flips(dev_priv);
3540
3541         dev_priv->modeset_restore_state = NULL;
3542
3543         /* reset doesn't touch the display */
3544         if (!gpu_reset_clobbers_display(dev_priv)) {
3545                 if (!state) {
3546                         /*
3547                          * Flips in the rings have been nuked by the reset,
3548                          * so update the base address of all primary
3549                          * planes to the the last fb to make sure we're
3550                          * showing the correct fb after a reset.
3551                          *
3552                          * FIXME: Atomic will make this obsolete since we won't schedule
3553                          * CS-based flips (which might get lost in gpu resets) any more.
3554                          */
3555                         intel_update_primary_planes(dev);
3556                 } else {
3557                         ret = __intel_display_resume(dev, state);
3558                         if (ret)
3559                                 DRM_ERROR("Restoring old state failed with %i\n", ret);
3560                 }
3561         } else {
3562                 /*
3563                  * The display has been reset as well,
3564                  * so need a full re-initialization.
3565                  */
3566                 intel_runtime_pm_disable_interrupts(dev_priv);
3567                 intel_runtime_pm_enable_interrupts(dev_priv);
3568
3569                 intel_modeset_init_hw(dev);
3570
3571                 spin_lock_irq(&dev_priv->irq_lock);
3572                 if (dev_priv->display.hpd_irq_setup)
3573                         dev_priv->display.hpd_irq_setup(dev_priv);
3574                 spin_unlock_irq(&dev_priv->irq_lock);
3575
3576                 ret = __intel_display_resume(dev, state);
3577                 if (ret)
3578                         DRM_ERROR("Restoring old state failed with %i\n", ret);
3579
3580                 intel_hpd_init(dev_priv);
3581         }
3582
3583         drm_modeset_drop_locks(ctx);
3584         drm_modeset_acquire_fini(ctx);
3585         mutex_unlock(&dev->mode_config.mutex);
3586 }
3587
3588 static bool intel_crtc_has_pending_flip(struct drm_crtc *crtc)
3589 {
3590         struct drm_device *dev = crtc->dev;
3591         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3592         unsigned reset_counter;
3593         bool pending;
3594
3595         reset_counter = i915_reset_counter(&to_i915(dev)->gpu_error);
3596         if (intel_crtc->reset_counter != reset_counter)
3597                 return false;
3598
3599         spin_lock_irq(&dev->event_lock);
3600         pending = to_intel_crtc(crtc)->flip_work != NULL;
3601         spin_unlock_irq(&dev->event_lock);
3602
3603         return pending;
3604 }
3605
3606 static void intel_update_pipe_config(struct intel_crtc *crtc,
3607                                      struct intel_crtc_state *old_crtc_state)
3608 {
3609         struct drm_device *dev = crtc->base.dev;
3610         struct drm_i915_private *dev_priv = to_i915(dev);
3611         struct intel_crtc_state *pipe_config =
3612                 to_intel_crtc_state(crtc->base.state);
3613
3614         /* drm_atomic_helper_update_legacy_modeset_state might not be called. */
3615         crtc->base.mode = crtc->base.state->mode;
3616
3617         DRM_DEBUG_KMS("Updating pipe size %ix%i -> %ix%i\n",
3618                       old_crtc_state->pipe_src_w, old_crtc_state->pipe_src_h,
3619                       pipe_config->pipe_src_w, pipe_config->pipe_src_h);
3620
3621         /*
3622          * Update pipe size and adjust fitter if needed: the reason for this is
3623          * that in compute_mode_changes we check the native mode (not the pfit
3624          * mode) to see if we can flip rather than do a full mode set. In the
3625          * fastboot case, we'll flip, but if we don't update the pipesrc and
3626          * pfit state, we'll end up with a big fb scanned out into the wrong
3627          * sized surface.
3628          */
3629
3630         I915_WRITE(PIPESRC(crtc->pipe),
3631                    ((pipe_config->pipe_src_w - 1) << 16) |
3632                    (pipe_config->pipe_src_h - 1));
3633
3634         /* on skylake this is done by detaching scalers */
3635         if (INTEL_INFO(dev)->gen >= 9) {
3636                 skl_detach_scalers(crtc);
3637
3638                 if (pipe_config->pch_pfit.enabled)
3639                         skylake_pfit_enable(crtc);
3640         } else if (HAS_PCH_SPLIT(dev)) {
3641                 if (pipe_config->pch_pfit.enabled)
3642                         ironlake_pfit_enable(crtc);
3643                 else if (old_crtc_state->pch_pfit.enabled)
3644                         ironlake_pfit_disable(crtc, true);
3645         }
3646 }
3647
3648 static void intel_fdi_normal_train(struct drm_crtc *crtc)
3649 {
3650         struct drm_device *dev = crtc->dev;
3651         struct drm_i915_private *dev_priv = to_i915(dev);
3652         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3653         int pipe = intel_crtc->pipe;
3654         i915_reg_t reg;
3655         u32 temp;
3656
3657         /* enable normal train */
3658         reg = FDI_TX_CTL(pipe);
3659         temp = I915_READ(reg);
3660         if (IS_IVYBRIDGE(dev)) {
3661                 temp &= ~FDI_LINK_TRAIN_NONE_IVB;
3662                 temp |= FDI_LINK_TRAIN_NONE_IVB | FDI_TX_ENHANCE_FRAME_ENABLE;
3663         } else {
3664                 temp &= ~FDI_LINK_TRAIN_NONE;
3665                 temp |= FDI_LINK_TRAIN_NONE | FDI_TX_ENHANCE_FRAME_ENABLE;
3666         }
3667         I915_WRITE(reg, temp);
3668
3669         reg = FDI_RX_CTL(pipe);
3670         temp = I915_READ(reg);
3671         if (HAS_PCH_CPT(dev)) {
3672                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
3673                 temp |= FDI_LINK_TRAIN_NORMAL_CPT;
3674         } else {
3675                 temp &= ~FDI_LINK_TRAIN_NONE;
3676                 temp |= FDI_LINK_TRAIN_NONE;
3677         }
3678         I915_WRITE(reg, temp | FDI_RX_ENHANCE_FRAME_ENABLE);
3679
3680         /* wait one idle pattern time */
3681         POSTING_READ(reg);
3682         udelay(1000);
3683
3684         /* IVB wants error correction enabled */
3685         if (IS_IVYBRIDGE(dev))
3686                 I915_WRITE(reg, I915_READ(reg) | FDI_FS_ERRC_ENABLE |
3687                            FDI_FE_ERRC_ENABLE);
3688 }
3689
3690 /* The FDI link training functions for ILK/Ibexpeak. */
3691 static void ironlake_fdi_link_train(struct drm_crtc *crtc)
3692 {
3693         struct drm_device *dev = crtc->dev;
3694         struct drm_i915_private *dev_priv = to_i915(dev);
3695         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3696         int pipe = intel_crtc->pipe;
3697         i915_reg_t reg;
3698         u32 temp, tries;
3699
3700         /* FDI needs bits from pipe first */
3701         assert_pipe_enabled(dev_priv, pipe);
3702
3703         /* Train 1: umask FDI RX Interrupt symbol_lock and bit_lock bit
3704            for train result */
3705         reg = FDI_RX_IMR(pipe);
3706         temp = I915_READ(reg);
3707         temp &= ~FDI_RX_SYMBOL_LOCK;
3708         temp &= ~FDI_RX_BIT_LOCK;
3709         I915_WRITE(reg, temp);
3710         I915_READ(reg);
3711         udelay(150);
3712
3713         /* enable CPU FDI TX and PCH FDI RX */
3714         reg = FDI_TX_CTL(pipe);
3715         temp = I915_READ(reg);
3716         temp &= ~FDI_DP_PORT_WIDTH_MASK;
3717         temp |= FDI_DP_PORT_WIDTH(intel_crtc->config->fdi_lanes);
3718         temp &= ~FDI_LINK_TRAIN_NONE;
3719         temp |= FDI_LINK_TRAIN_PATTERN_1;
3720         I915_WRITE(reg, temp | FDI_TX_ENABLE);
3721
3722         reg = FDI_RX_CTL(pipe);
3723         temp = I915_READ(reg);
3724         temp &= ~FDI_LINK_TRAIN_NONE;
3725         temp |= FDI_LINK_TRAIN_PATTERN_1;
3726         I915_WRITE(reg, temp | FDI_RX_ENABLE);
3727
3728         POSTING_READ(reg);
3729         udelay(150);
3730
3731         /* Ironlake workaround, enable clock pointer after FDI enable*/
3732         I915_WRITE(FDI_RX_CHICKEN(pipe), FDI_RX_PHASE_SYNC_POINTER_OVR);
3733         I915_WRITE(FDI_RX_CHICKEN(pipe), FDI_RX_PHASE_SYNC_POINTER_OVR |
3734                    FDI_RX_PHASE_SYNC_POINTER_EN);
3735
3736         reg = FDI_RX_IIR(pipe);
3737         for (tries = 0; tries < 5; tries++) {
3738                 temp = I915_READ(reg);
3739                 DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
3740
3741                 if ((temp & FDI_RX_BIT_LOCK)) {
3742                         DRM_DEBUG_KMS("FDI train 1 done.\n");
3743                         I915_WRITE(reg, temp | FDI_RX_BIT_LOCK);
3744                         break;
3745                 }
3746         }
3747         if (tries == 5)
3748                 DRM_ERROR("FDI train 1 fail!\n");
3749
3750         /* Train 2 */
3751         reg = FDI_TX_CTL(pipe);
3752         temp = I915_READ(reg);
3753         temp &= ~FDI_LINK_TRAIN_NONE;
3754         temp |= FDI_LINK_TRAIN_PATTERN_2;
3755         I915_WRITE(reg, temp);
3756
3757         reg = FDI_RX_CTL(pipe);
3758         temp = I915_READ(reg);
3759         temp &= ~FDI_LINK_TRAIN_NONE;
3760         temp |= FDI_LINK_TRAIN_PATTERN_2;
3761         I915_WRITE(reg, temp);
3762
3763         POSTING_READ(reg);
3764         udelay(150);
3765
3766         reg = FDI_RX_IIR(pipe);
3767         for (tries = 0; tries < 5; tries++) {
3768                 temp = I915_READ(reg);
3769                 DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
3770
3771                 if (temp & FDI_RX_SYMBOL_LOCK) {
3772                         I915_WRITE(reg, temp | FDI_RX_SYMBOL_LOCK);
3773                         DRM_DEBUG_KMS("FDI train 2 done.\n");
3774                         break;
3775                 }
3776         }
3777         if (tries == 5)
3778                 DRM_ERROR("FDI train 2 fail!\n");
3779
3780         DRM_DEBUG_KMS("FDI train done\n");
3781
3782 }
3783
3784 static const int snb_b_fdi_train_param[] = {
3785         FDI_LINK_TRAIN_400MV_0DB_SNB_B,
3786         FDI_LINK_TRAIN_400MV_6DB_SNB_B,
3787         FDI_LINK_TRAIN_600MV_3_5DB_SNB_B,
3788         FDI_LINK_TRAIN_800MV_0DB_SNB_B,
3789 };
3790
3791 /* The FDI link training functions for SNB/Cougarpoint. */
3792 static void gen6_fdi_link_train(struct drm_crtc *crtc)
3793 {
3794         struct drm_device *dev = crtc->dev;
3795         struct drm_i915_private *dev_priv = to_i915(dev);
3796         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3797         int pipe = intel_crtc->pipe;
3798         i915_reg_t reg;
3799         u32 temp, i, retry;
3800
3801         /* Train 1: umask FDI RX Interrupt symbol_lock and bit_lock bit
3802            for train result */
3803         reg = FDI_RX_IMR(pipe);
3804         temp = I915_READ(reg);
3805         temp &= ~FDI_RX_SYMBOL_LOCK;
3806         temp &= ~FDI_RX_BIT_LOCK;
3807         I915_WRITE(reg, temp);
3808
3809         POSTING_READ(reg);
3810         udelay(150);
3811
3812         /* enable CPU FDI TX and PCH FDI RX */
3813         reg = FDI_TX_CTL(pipe);
3814         temp = I915_READ(reg);
3815         temp &= ~FDI_DP_PORT_WIDTH_MASK;
3816         temp |= FDI_DP_PORT_WIDTH(intel_crtc->config->fdi_lanes);
3817         temp &= ~FDI_LINK_TRAIN_NONE;
3818         temp |= FDI_LINK_TRAIN_PATTERN_1;
3819         temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
3820         /* SNB-B */
3821         temp |= FDI_LINK_TRAIN_400MV_0DB_SNB_B;
3822         I915_WRITE(reg, temp | FDI_TX_ENABLE);
3823
3824         I915_WRITE(FDI_RX_MISC(pipe),
3825                    FDI_RX_TP1_TO_TP2_48 | FDI_RX_FDI_DELAY_90);
3826
3827         reg = FDI_RX_CTL(pipe);
3828         temp = I915_READ(reg);
3829         if (HAS_PCH_CPT(dev)) {
3830                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
3831                 temp |= FDI_LINK_TRAIN_PATTERN_1_CPT;
3832         } else {
3833                 temp &= ~FDI_LINK_TRAIN_NONE;
3834                 temp |= FDI_LINK_TRAIN_PATTERN_1;
3835         }
3836         I915_WRITE(reg, temp | FDI_RX_ENABLE);
3837
3838         POSTING_READ(reg);
3839         udelay(150);
3840
3841         for (i = 0; i < 4; i++) {
3842                 reg = FDI_TX_CTL(pipe);
3843                 temp = I915_READ(reg);
3844                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
3845                 temp |= snb_b_fdi_train_param[i];
3846                 I915_WRITE(reg, temp);
3847
3848                 POSTING_READ(reg);
3849                 udelay(500);
3850
3851                 for (retry = 0; retry < 5; retry++) {
3852                         reg = FDI_RX_IIR(pipe);
3853                         temp = I915_READ(reg);
3854                         DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
3855                         if (temp & FDI_RX_BIT_LOCK) {
3856                                 I915_WRITE(reg, temp | FDI_RX_BIT_LOCK);
3857                                 DRM_DEBUG_KMS("FDI train 1 done.\n");
3858                                 break;
3859                         }
3860                         udelay(50);
3861                 }
3862                 if (retry < 5)
3863                         break;
3864         }
3865         if (i == 4)
3866                 DRM_ERROR("FDI train 1 fail!\n");
3867
3868         /* Train 2 */
3869         reg = FDI_TX_CTL(pipe);
3870         temp = I915_READ(reg);
3871         temp &= ~FDI_LINK_TRAIN_NONE;
3872         temp |= FDI_LINK_TRAIN_PATTERN_2;
3873         if (IS_GEN6(dev)) {
3874                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
3875                 /* SNB-B */
3876                 temp |= FDI_LINK_TRAIN_400MV_0DB_SNB_B;
3877         }
3878         I915_WRITE(reg, temp);
3879
3880         reg = FDI_RX_CTL(pipe);
3881         temp = I915_READ(reg);
3882         if (HAS_PCH_CPT(dev)) {
3883                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
3884                 temp |= FDI_LINK_TRAIN_PATTERN_2_CPT;
3885         } else {
3886                 temp &= ~FDI_LINK_TRAIN_NONE;
3887                 temp |= FDI_LINK_TRAIN_PATTERN_2;
3888         }
3889         I915_WRITE(reg, temp);
3890
3891         POSTING_READ(reg);
3892         udelay(150);
3893
3894         for (i = 0; i < 4; i++) {
3895                 reg = FDI_TX_CTL(pipe);
3896                 temp = I915_READ(reg);
3897                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
3898                 temp |= snb_b_fdi_train_param[i];
3899                 I915_WRITE(reg, temp);
3900
3901                 POSTING_READ(reg);
3902                 udelay(500);
3903
3904                 for (retry = 0; retry < 5; retry++) {
3905                         reg = FDI_RX_IIR(pipe);
3906                         temp = I915_READ(reg);
3907                         DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
3908                         if (temp & FDI_RX_SYMBOL_LOCK) {
3909                                 I915_WRITE(reg, temp | FDI_RX_SYMBOL_LOCK);
3910                                 DRM_DEBUG_KMS("FDI train 2 done.\n");
3911                                 break;
3912                         }
3913                         udelay(50);
3914                 }
3915                 if (retry < 5)
3916                         break;
3917         }
3918         if (i == 4)
3919                 DRM_ERROR("FDI train 2 fail!\n");
3920
3921         DRM_DEBUG_KMS("FDI train done.\n");
3922 }
3923
3924 /* Manual link training for Ivy Bridge A0 parts */
3925 static void ivb_manual_fdi_link_train(struct drm_crtc *crtc)
3926 {
3927         struct drm_device *dev = crtc->dev;
3928         struct drm_i915_private *dev_priv = to_i915(dev);
3929         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3930         int pipe = intel_crtc->pipe;
3931         i915_reg_t reg;
3932         u32 temp, i, j;
3933
3934         /* Train 1: umask FDI RX Interrupt symbol_lock and bit_lock bit
3935            for train result */
3936         reg = FDI_RX_IMR(pipe);
3937         temp = I915_READ(reg);
3938         temp &= ~FDI_RX_SYMBOL_LOCK;
3939         temp &= ~FDI_RX_BIT_LOCK;
3940         I915_WRITE(reg, temp);
3941
3942         POSTING_READ(reg);
3943         udelay(150);
3944
3945         DRM_DEBUG_KMS("FDI_RX_IIR before link train 0x%x\n",
3946                       I915_READ(FDI_RX_IIR(pipe)));
3947
3948         /* Try each vswing and preemphasis setting twice before moving on */
3949         for (j = 0; j < ARRAY_SIZE(snb_b_fdi_train_param) * 2; j++) {
3950                 /* disable first in case we need to retry */
3951                 reg = FDI_TX_CTL(pipe);
3952                 temp = I915_READ(reg);
3953                 temp &= ~(FDI_LINK_TRAIN_AUTO | FDI_LINK_TRAIN_NONE_IVB);
3954                 temp &= ~FDI_TX_ENABLE;
3955                 I915_WRITE(reg, temp);
3956
3957                 reg = FDI_RX_CTL(pipe);
3958                 temp = I915_READ(reg);
3959                 temp &= ~FDI_LINK_TRAIN_AUTO;
3960                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
3961                 temp &= ~FDI_RX_ENABLE;
3962                 I915_WRITE(reg, temp);
3963
3964                 /* enable CPU FDI TX and PCH FDI RX */
3965                 reg = FDI_TX_CTL(pipe);
3966                 temp = I915_READ(reg);
3967                 temp &= ~FDI_DP_PORT_WIDTH_MASK;
3968                 temp |= FDI_DP_PORT_WIDTH(intel_crtc->config->fdi_lanes);
3969                 temp |= FDI_LINK_TRAIN_PATTERN_1_IVB;
3970                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
3971                 temp |= snb_b_fdi_train_param[j/2];
3972                 temp |= FDI_COMPOSITE_SYNC;
3973                 I915_WRITE(reg, temp | FDI_TX_ENABLE);
3974
3975                 I915_WRITE(FDI_RX_MISC(pipe),
3976                            FDI_RX_TP1_TO_TP2_48 | FDI_RX_FDI_DELAY_90);
3977
3978                 reg = FDI_RX_CTL(pipe);
3979                 temp = I915_READ(reg);
3980                 temp |= FDI_LINK_TRAIN_PATTERN_1_CPT;
3981                 temp |= FDI_COMPOSITE_SYNC;
3982                 I915_WRITE(reg, temp | FDI_RX_ENABLE);
3983
3984                 POSTING_READ(reg);
3985                 udelay(1); /* should be 0.5us */
3986
3987                 for (i = 0; i < 4; i++) {
3988                         reg = FDI_RX_IIR(pipe);
3989                         temp = I915_READ(reg);
3990                         DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
3991
3992                         if (temp & FDI_RX_BIT_LOCK ||
3993                             (I915_READ(reg) & FDI_RX_BIT_LOCK)) {
3994                                 I915_WRITE(reg, temp | FDI_RX_BIT_LOCK);
3995                                 DRM_DEBUG_KMS("FDI train 1 done, level %i.\n",
3996                                               i);
3997                                 break;
3998                         }
3999                         udelay(1); /* should be 0.5us */
4000                 }
4001                 if (i == 4) {
4002                         DRM_DEBUG_KMS("FDI train 1 fail on vswing %d\n", j / 2);
4003                         continue;
4004                 }
4005
4006                 /* Train 2 */
4007                 reg = FDI_TX_CTL(pipe);
4008                 temp = I915_READ(reg);
4009                 temp &= ~FDI_LINK_TRAIN_NONE_IVB;
4010                 temp |= FDI_LINK_TRAIN_PATTERN_2_IVB;
4011                 I915_WRITE(reg, temp);
4012
4013                 reg = FDI_RX_CTL(pipe);
4014                 temp = I915_READ(reg);
4015                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
4016                 temp |= FDI_LINK_TRAIN_PATTERN_2_CPT;
4017                 I915_WRITE(reg, temp);
4018
4019                 POSTING_READ(reg);
4020                 udelay(2); /* should be 1.5us */
4021
4022                 for (i = 0; i < 4; i++) {
4023                         reg = FDI_RX_IIR(pipe);
4024                         temp = I915_READ(reg);
4025                         DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
4026
4027                         if (temp & FDI_RX_SYMBOL_LOCK ||
4028                             (I915_READ(reg) & FDI_RX_SYMBOL_LOCK)) {
4029                                 I915_WRITE(reg, temp | FDI_RX_SYMBOL_LOCK);
4030                                 DRM_DEBUG_KMS("FDI train 2 done, level %i.\n",
4031                                               i);
4032                                 goto train_done;
4033                         }
4034                         udelay(2); /* should be 1.5us */
4035                 }
4036                 if (i == 4)
4037                         DRM_DEBUG_KMS("FDI train 2 fail on vswing %d\n", j / 2);
4038         }
4039
4040 train_done:
4041         DRM_DEBUG_KMS("FDI train done.\n");
4042 }
4043
4044 static void ironlake_fdi_pll_enable(struct intel_crtc *intel_crtc)
4045 {
4046         struct drm_device *dev = intel_crtc->base.dev;
4047         struct drm_i915_private *dev_priv = to_i915(dev);
4048         int pipe = intel_crtc->pipe;
4049         i915_reg_t reg;
4050         u32 temp;
4051
4052         /* enable PCH FDI RX PLL, wait warmup plus DMI latency */
4053         reg = FDI_RX_CTL(pipe);
4054         temp = I915_READ(reg);
4055         temp &= ~(FDI_DP_PORT_WIDTH_MASK | (0x7 << 16));
4056         temp |= FDI_DP_PORT_WIDTH(intel_crtc->config->fdi_lanes);
4057         temp |= (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) << 11;
4058         I915_WRITE(reg, temp | FDI_RX_PLL_ENABLE);
4059
4060         POSTING_READ(reg);
4061         udelay(200);
4062
4063         /* Switch from Rawclk to PCDclk */
4064         temp = I915_READ(reg);
4065         I915_WRITE(reg, temp | FDI_PCDCLK);
4066
4067         POSTING_READ(reg);
4068         udelay(200);
4069
4070         /* Enable CPU FDI TX PLL, always on for Ironlake */
4071         reg = FDI_TX_CTL(pipe);
4072         temp = I915_READ(reg);
4073         if ((temp & FDI_TX_PLL_ENABLE) == 0) {
4074                 I915_WRITE(reg, temp | FDI_TX_PLL_ENABLE);
4075
4076                 POSTING_READ(reg);
4077                 udelay(100);
4078         }
4079 }
4080
4081 static void ironlake_fdi_pll_disable(struct intel_crtc *intel_crtc)
4082 {
4083         struct drm_device *dev = intel_crtc->base.dev;
4084         struct drm_i915_private *dev_priv = to_i915(dev);
4085         int pipe = intel_crtc->pipe;
4086         i915_reg_t reg;
4087         u32 temp;
4088
4089         /* Switch from PCDclk to Rawclk */
4090         reg = FDI_RX_CTL(pipe);
4091         temp = I915_READ(reg);
4092         I915_WRITE(reg, temp & ~FDI_PCDCLK);
4093
4094         /* Disable CPU FDI TX PLL */
4095         reg = FDI_TX_CTL(pipe);
4096         temp = I915_READ(reg);
4097         I915_WRITE(reg, temp & ~FDI_TX_PLL_ENABLE);
4098
4099         POSTING_READ(reg);
4100         udelay(100);
4101
4102         reg = FDI_RX_CTL(pipe);
4103         temp = I915_READ(reg);
4104         I915_WRITE(reg, temp & ~FDI_RX_PLL_ENABLE);
4105
4106         /* Wait for the clocks to turn off. */
4107         POSTING_READ(reg);
4108         udelay(100);
4109 }
4110
4111 static void ironlake_fdi_disable(struct drm_crtc *crtc)
4112 {
4113         struct drm_device *dev = crtc->dev;
4114         struct drm_i915_private *dev_priv = to_i915(dev);
4115         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4116         int pipe = intel_crtc->pipe;
4117         i915_reg_t reg;
4118         u32 temp;
4119
4120         /* disable CPU FDI tx and PCH FDI rx */
4121         reg = FDI_TX_CTL(pipe);
4122         temp = I915_READ(reg);
4123         I915_WRITE(reg, temp & ~FDI_TX_ENABLE);
4124         POSTING_READ(reg);
4125
4126         reg = FDI_RX_CTL(pipe);
4127         temp = I915_READ(reg);
4128         temp &= ~(0x7 << 16);
4129         temp |= (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) << 11;
4130         I915_WRITE(reg, temp & ~FDI_RX_ENABLE);
4131
4132         POSTING_READ(reg);
4133         udelay(100);
4134
4135         /* Ironlake workaround, disable clock pointer after downing FDI */
4136         if (HAS_PCH_IBX(dev))
4137                 I915_WRITE(FDI_RX_CHICKEN(pipe), FDI_RX_PHASE_SYNC_POINTER_OVR);
4138
4139         /* still set train pattern 1 */
4140         reg = FDI_TX_CTL(pipe);
4141         temp = I915_READ(reg);
4142         temp &= ~FDI_LINK_TRAIN_NONE;
4143         temp |= FDI_LINK_TRAIN_PATTERN_1;
4144         I915_WRITE(reg, temp);
4145
4146         reg = FDI_RX_CTL(pipe);
4147         temp = I915_READ(reg);
4148         if (HAS_PCH_CPT(dev)) {
4149                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
4150                 temp |= FDI_LINK_TRAIN_PATTERN_1_CPT;
4151         } else {
4152                 temp &= ~FDI_LINK_TRAIN_NONE;
4153                 temp |= FDI_LINK_TRAIN_PATTERN_1;
4154         }
4155         /* BPC in FDI rx is consistent with that in PIPECONF */
4156         temp &= ~(0x07 << 16);
4157         temp |= (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) << 11;
4158         I915_WRITE(reg, temp);
4159
4160         POSTING_READ(reg);
4161         udelay(100);
4162 }
4163
4164 bool intel_has_pending_fb_unpin(struct drm_device *dev)
4165 {
4166         struct intel_crtc *crtc;
4167
4168         /* Note that we don't need to be called with mode_config.lock here
4169          * as our list of CRTC objects is static for the lifetime of the
4170          * device and so cannot disappear as we iterate. Similarly, we can
4171          * happily treat the predicates as racy, atomic checks as userspace
4172          * cannot claim and pin a new fb without at least acquring the
4173          * struct_mutex and so serialising with us.
4174          */
4175         for_each_intel_crtc(dev, crtc) {
4176                 if (atomic_read(&crtc->unpin_work_count) == 0)
4177                         continue;
4178
4179                 if (crtc->flip_work)
4180                         intel_wait_for_vblank(dev, crtc->pipe);
4181
4182                 return true;
4183         }
4184
4185         return false;
4186 }
4187
4188 static void page_flip_completed(struct intel_crtc *intel_crtc)
4189 {
4190         struct drm_i915_private *dev_priv = to_i915(intel_crtc->base.dev);
4191         struct intel_flip_work *work = intel_crtc->flip_work;
4192
4193         intel_crtc->flip_work = NULL;
4194
4195         if (work->event)
4196                 drm_crtc_send_vblank_event(&intel_crtc->base, work->event);
4197
4198         drm_crtc_vblank_put(&intel_crtc->base);
4199
4200         wake_up_all(&dev_priv->pending_flip_queue);
4201         queue_work(dev_priv->wq, &work->unpin_work);
4202
4203         trace_i915_flip_complete(intel_crtc->plane,
4204                                  work->pending_flip_obj);
4205 }
4206
4207 static int intel_crtc_wait_for_pending_flips(struct drm_crtc *crtc)
4208 {
4209         struct drm_device *dev = crtc->dev;
4210         struct drm_i915_private *dev_priv = to_i915(dev);
4211         long ret;
4212
4213         WARN_ON(waitqueue_active(&dev_priv->pending_flip_queue));
4214
4215         ret = wait_event_interruptible_timeout(
4216                                         dev_priv->pending_flip_queue,
4217                                         !intel_crtc_has_pending_flip(crtc),
4218                                         60*HZ);
4219
4220         if (ret < 0)
4221                 return ret;
4222
4223         if (ret == 0) {
4224                 struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4225                 struct intel_flip_work *work;
4226
4227                 spin_lock_irq(&dev->event_lock);
4228                 work = intel_crtc->flip_work;
4229                 if (work && !is_mmio_work(work)) {
4230                         WARN_ONCE(1, "Removing stuck page flip\n");
4231                         page_flip_completed(intel_crtc);
4232                 }
4233                 spin_unlock_irq(&dev->event_lock);
4234         }
4235
4236         return 0;
4237 }
4238
4239 static void lpt_disable_iclkip(struct drm_i915_private *dev_priv)
4240 {
4241         u32 temp;
4242
4243         I915_WRITE(PIXCLK_GATE, PIXCLK_GATE_GATE);
4244
4245         mutex_lock(&dev_priv->sb_lock);
4246
4247         temp = intel_sbi_read(dev_priv, SBI_SSCCTL6, SBI_ICLK);
4248         temp |= SBI_SSCCTL_DISABLE;
4249         intel_sbi_write(dev_priv, SBI_SSCCTL6, temp, SBI_ICLK);
4250
4251         mutex_unlock(&dev_priv->sb_lock);
4252 }
4253
4254 /* Program iCLKIP clock to the desired frequency */
4255 static void lpt_program_iclkip(struct drm_crtc *crtc)
4256 {
4257         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
4258         int clock = to_intel_crtc(crtc)->config->base.adjusted_mode.crtc_clock;
4259         u32 divsel, phaseinc, auxdiv, phasedir = 0;
4260         u32 temp;
4261
4262         lpt_disable_iclkip(dev_priv);
4263
4264         /* The iCLK virtual clock root frequency is in MHz,
4265          * but the adjusted_mode->crtc_clock in in KHz. To get the
4266          * divisors, it is necessary to divide one by another, so we
4267          * convert the virtual clock precision to KHz here for higher
4268          * precision.
4269          */
4270         for (auxdiv = 0; auxdiv < 2; auxdiv++) {
4271                 u32 iclk_virtual_root_freq = 172800 * 1000;
4272                 u32 iclk_pi_range = 64;
4273                 u32 desired_divisor;
4274
4275                 desired_divisor = DIV_ROUND_CLOSEST(iclk_virtual_root_freq,
4276                                                     clock << auxdiv);
4277                 divsel = (desired_divisor / iclk_pi_range) - 2;
4278                 phaseinc = desired_divisor % iclk_pi_range;
4279
4280                 /*
4281                  * Near 20MHz is a corner case which is
4282                  * out of range for the 7-bit divisor
4283                  */
4284                 if (divsel <= 0x7f)
4285                         break;
4286         }
4287
4288         /* This should not happen with any sane values */
4289         WARN_ON(SBI_SSCDIVINTPHASE_DIVSEL(divsel) &
4290                 ~SBI_SSCDIVINTPHASE_DIVSEL_MASK);
4291         WARN_ON(SBI_SSCDIVINTPHASE_DIR(phasedir) &
4292                 ~SBI_SSCDIVINTPHASE_INCVAL_MASK);
4293
4294         DRM_DEBUG_KMS("iCLKIP clock: found settings for %dKHz refresh rate: auxdiv=%x, divsel=%x, phasedir=%x, phaseinc=%x\n",
4295                         clock,
4296                         auxdiv,
4297                         divsel,
4298                         phasedir,
4299                         phaseinc);
4300
4301         mutex_lock(&dev_priv->sb_lock);
4302
4303         /* Program SSCDIVINTPHASE6 */
4304         temp = intel_sbi_read(dev_priv, SBI_SSCDIVINTPHASE6, SBI_ICLK);
4305         temp &= ~SBI_SSCDIVINTPHASE_DIVSEL_MASK;
4306         temp |= SBI_SSCDIVINTPHASE_DIVSEL(divsel);
4307         temp &= ~SBI_SSCDIVINTPHASE_INCVAL_MASK;
4308         temp |= SBI_SSCDIVINTPHASE_INCVAL(phaseinc);
4309         temp |= SBI_SSCDIVINTPHASE_DIR(phasedir);
4310         temp |= SBI_SSCDIVINTPHASE_PROPAGATE;
4311         intel_sbi_write(dev_priv, SBI_SSCDIVINTPHASE6, temp, SBI_ICLK);
4312
4313         /* Program SSCAUXDIV */
4314         temp = intel_sbi_read(dev_priv, SBI_SSCAUXDIV6, SBI_ICLK);
4315         temp &= ~SBI_SSCAUXDIV_FINALDIV2SEL(1);
4316         temp |= SBI_SSCAUXDIV_FINALDIV2SEL(auxdiv);
4317         intel_sbi_write(dev_priv, SBI_SSCAUXDIV6, temp, SBI_ICLK);
4318
4319         /* Enable modulator and associated divider */
4320         temp = intel_sbi_read(dev_priv, SBI_SSCCTL6, SBI_ICLK);
4321         temp &= ~SBI_SSCCTL_DISABLE;
4322         intel_sbi_write(dev_priv, SBI_SSCCTL6, temp, SBI_ICLK);
4323
4324         mutex_unlock(&dev_priv->sb_lock);
4325
4326         /* Wait for initialization time */
4327         udelay(24);
4328
4329         I915_WRITE(PIXCLK_GATE, PIXCLK_GATE_UNGATE);
4330 }
4331
4332 int lpt_get_iclkip(struct drm_i915_private *dev_priv)
4333 {
4334         u32 divsel, phaseinc, auxdiv;
4335         u32 iclk_virtual_root_freq = 172800 * 1000;
4336         u32 iclk_pi_range = 64;
4337         u32 desired_divisor;
4338         u32 temp;
4339
4340         if ((I915_READ(PIXCLK_GATE) & PIXCLK_GATE_UNGATE) == 0)
4341                 return 0;
4342
4343         mutex_lock(&dev_priv->sb_lock);
4344
4345         temp = intel_sbi_read(dev_priv, SBI_SSCCTL6, SBI_ICLK);
4346         if (temp & SBI_SSCCTL_DISABLE) {
4347                 mutex_unlock(&dev_priv->sb_lock);
4348                 return 0;
4349         }
4350
4351         temp = intel_sbi_read(dev_priv, SBI_SSCDIVINTPHASE6, SBI_ICLK);
4352         divsel = (temp & SBI_SSCDIVINTPHASE_DIVSEL_MASK) >>
4353                 SBI_SSCDIVINTPHASE_DIVSEL_SHIFT;
4354         phaseinc = (temp & SBI_SSCDIVINTPHASE_INCVAL_MASK) >>
4355                 SBI_SSCDIVINTPHASE_INCVAL_SHIFT;
4356
4357         temp = intel_sbi_read(dev_priv, SBI_SSCAUXDIV6, SBI_ICLK);
4358         auxdiv = (temp & SBI_SSCAUXDIV_FINALDIV2SEL_MASK) >>
4359                 SBI_SSCAUXDIV_FINALDIV2SEL_SHIFT;
4360
4361         mutex_unlock(&dev_priv->sb_lock);
4362
4363         desired_divisor = (divsel + 2) * iclk_pi_range + phaseinc;
4364
4365         return DIV_ROUND_CLOSEST(iclk_virtual_root_freq,
4366                                  desired_divisor << auxdiv);
4367 }
4368
4369 static void ironlake_pch_transcoder_set_timings(struct intel_crtc *crtc,
4370                                                 enum pipe pch_transcoder)
4371 {
4372         struct drm_device *dev = crtc->base.dev;
4373         struct drm_i915_private *dev_priv = to_i915(dev);
4374         enum transcoder cpu_transcoder = crtc->config->cpu_transcoder;
4375
4376         I915_WRITE(PCH_TRANS_HTOTAL(pch_transcoder),
4377                    I915_READ(HTOTAL(cpu_transcoder)));
4378         I915_WRITE(PCH_TRANS_HBLANK(pch_transcoder),
4379                    I915_READ(HBLANK(cpu_transcoder)));
4380         I915_WRITE(PCH_TRANS_HSYNC(pch_transcoder),
4381                    I915_READ(HSYNC(cpu_transcoder)));
4382
4383         I915_WRITE(PCH_TRANS_VTOTAL(pch_transcoder),
4384                    I915_READ(VTOTAL(cpu_transcoder)));
4385         I915_WRITE(PCH_TRANS_VBLANK(pch_transcoder),
4386                    I915_READ(VBLANK(cpu_transcoder)));
4387         I915_WRITE(PCH_TRANS_VSYNC(pch_transcoder),
4388                    I915_READ(VSYNC(cpu_transcoder)));
4389         I915_WRITE(PCH_TRANS_VSYNCSHIFT(pch_transcoder),
4390                    I915_READ(VSYNCSHIFT(cpu_transcoder)));
4391 }
4392
4393 static void cpt_set_fdi_bc_bifurcation(struct drm_device *dev, bool enable)
4394 {
4395         struct drm_i915_private *dev_priv = to_i915(dev);
4396         uint32_t temp;
4397
4398         temp = I915_READ(SOUTH_CHICKEN1);
4399         if (!!(temp & FDI_BC_BIFURCATION_SELECT) == enable)
4400                 return;
4401
4402         WARN_ON(I915_READ(FDI_RX_CTL(PIPE_B)) & FDI_RX_ENABLE);
4403         WARN_ON(I915_READ(FDI_RX_CTL(PIPE_C)) & FDI_RX_ENABLE);
4404
4405         temp &= ~FDI_BC_BIFURCATION_SELECT;
4406         if (enable)
4407                 temp |= FDI_BC_BIFURCATION_SELECT;
4408
4409         DRM_DEBUG_KMS("%sabling fdi C rx\n", enable ? "en" : "dis");
4410         I915_WRITE(SOUTH_CHICKEN1, temp);
4411         POSTING_READ(SOUTH_CHICKEN1);
4412 }
4413
4414 static void ivybridge_update_fdi_bc_bifurcation(struct intel_crtc *intel_crtc)
4415 {
4416         struct drm_device *dev = intel_crtc->base.dev;
4417
4418         switch (intel_crtc->pipe) {
4419         case PIPE_A:
4420                 break;
4421         case PIPE_B:
4422                 if (intel_crtc->config->fdi_lanes > 2)
4423                         cpt_set_fdi_bc_bifurcation(dev, false);
4424                 else
4425                         cpt_set_fdi_bc_bifurcation(dev, true);
4426
4427                 break;
4428         case PIPE_C:
4429                 cpt_set_fdi_bc_bifurcation(dev, true);
4430
4431                 break;
4432         default:
4433                 BUG();
4434         }
4435 }
4436
4437 /* Return which DP Port should be selected for Transcoder DP control */
4438 static enum port
4439 intel_trans_dp_port_sel(struct drm_crtc *crtc)
4440 {
4441         struct drm_device *dev = crtc->dev;
4442         struct intel_encoder *encoder;
4443
4444         for_each_encoder_on_crtc(dev, crtc, encoder) {
4445                 if (encoder->type == INTEL_OUTPUT_DP ||
4446                     encoder->type == INTEL_OUTPUT_EDP)
4447                         return enc_to_dig_port(&encoder->base)->port;
4448         }
4449
4450         return -1;
4451 }
4452
4453 /*
4454  * Enable PCH resources required for PCH ports:
4455  *   - PCH PLLs
4456  *   - FDI training & RX/TX
4457  *   - update transcoder timings
4458  *   - DP transcoding bits
4459  *   - transcoder
4460  */
4461 static void ironlake_pch_enable(struct drm_crtc *crtc)
4462 {
4463         struct drm_device *dev = crtc->dev;
4464         struct drm_i915_private *dev_priv = to_i915(dev);
4465         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4466         int pipe = intel_crtc->pipe;
4467         u32 temp;
4468
4469         assert_pch_transcoder_disabled(dev_priv, pipe);
4470
4471         if (IS_IVYBRIDGE(dev))
4472                 ivybridge_update_fdi_bc_bifurcation(intel_crtc);
4473
4474         /* Write the TU size bits before fdi link training, so that error
4475          * detection works. */
4476         I915_WRITE(FDI_RX_TUSIZE1(pipe),
4477                    I915_READ(PIPE_DATA_M1(pipe)) & TU_SIZE_MASK);
4478
4479         /* For PCH output, training FDI link */
4480         dev_priv->display.fdi_link_train(crtc);
4481
4482         /* We need to program the right clock selection before writing the pixel
4483          * mutliplier into the DPLL. */
4484         if (HAS_PCH_CPT(dev)) {
4485                 u32 sel;
4486
4487                 temp = I915_READ(PCH_DPLL_SEL);
4488                 temp |= TRANS_DPLL_ENABLE(pipe);
4489                 sel = TRANS_DPLLB_SEL(pipe);
4490                 if (intel_crtc->config->shared_dpll ==
4491                     intel_get_shared_dpll_by_id(dev_priv, DPLL_ID_PCH_PLL_B))
4492                         temp |= sel;
4493                 else
4494                         temp &= ~sel;
4495                 I915_WRITE(PCH_DPLL_SEL, temp);
4496         }
4497
4498         /* XXX: pch pll's can be enabled any time before we enable the PCH
4499          * transcoder, and we actually should do this to not upset any PCH
4500          * transcoder that already use the clock when we share it.
4501          *
4502          * Note that enable_shared_dpll tries to do the right thing, but
4503          * get_shared_dpll unconditionally resets the pll - we need that to have
4504          * the right LVDS enable sequence. */
4505         intel_enable_shared_dpll(intel_crtc);
4506
4507         /* set transcoder timing, panel must allow it */
4508         assert_panel_unlocked(dev_priv, pipe);
4509         ironlake_pch_transcoder_set_timings(intel_crtc, pipe);
4510
4511         intel_fdi_normal_train(crtc);
4512
4513         /* For PCH DP, enable TRANS_DP_CTL */
4514         if (HAS_PCH_CPT(dev) && intel_crtc_has_dp_encoder(intel_crtc->config)) {
4515                 const struct drm_display_mode *adjusted_mode =
4516                         &intel_crtc->config->base.adjusted_mode;
4517                 u32 bpc = (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) >> 5;
4518                 i915_reg_t reg = TRANS_DP_CTL(pipe);
4519                 temp = I915_READ(reg);
4520                 temp &= ~(TRANS_DP_PORT_SEL_MASK |
4521                           TRANS_DP_SYNC_MASK |
4522                           TRANS_DP_BPC_MASK);
4523                 temp |= TRANS_DP_OUTPUT_ENABLE;
4524                 temp |= bpc << 9; /* same format but at 11:9 */
4525
4526                 if (adjusted_mode->flags & DRM_MODE_FLAG_PHSYNC)
4527                         temp |= TRANS_DP_HSYNC_ACTIVE_HIGH;
4528                 if (adjusted_mode->flags & DRM_MODE_FLAG_PVSYNC)
4529                         temp |= TRANS_DP_VSYNC_ACTIVE_HIGH;
4530
4531                 switch (intel_trans_dp_port_sel(crtc)) {
4532                 case PORT_B:
4533                         temp |= TRANS_DP_PORT_SEL_B;
4534                         break;
4535                 case PORT_C:
4536                         temp |= TRANS_DP_PORT_SEL_C;
4537                         break;
4538                 case PORT_D:
4539                         temp |= TRANS_DP_PORT_SEL_D;
4540                         break;
4541                 default:
4542                         BUG();
4543                 }
4544
4545                 I915_WRITE(reg, temp);
4546         }
4547
4548         ironlake_enable_pch_transcoder(dev_priv, pipe);
4549 }
4550
4551 static void lpt_pch_enable(struct drm_crtc *crtc)
4552 {
4553         struct drm_device *dev = crtc->dev;
4554         struct drm_i915_private *dev_priv = to_i915(dev);
4555         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4556         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
4557
4558         assert_pch_transcoder_disabled(dev_priv, TRANSCODER_A);
4559
4560         lpt_program_iclkip(crtc);
4561
4562         /* Set transcoder timing. */
4563         ironlake_pch_transcoder_set_timings(intel_crtc, PIPE_A);
4564
4565         lpt_enable_pch_transcoder(dev_priv, cpu_transcoder);
4566 }
4567
4568 static void cpt_verify_modeset(struct drm_device *dev, int pipe)
4569 {
4570         struct drm_i915_private *dev_priv = to_i915(dev);
4571         i915_reg_t dslreg = PIPEDSL(pipe);
4572         u32 temp;
4573
4574         temp = I915_READ(dslreg);
4575         udelay(500);
4576         if (wait_for(I915_READ(dslreg) != temp, 5)) {
4577                 if (wait_for(I915_READ(dslreg) != temp, 5))
4578                         DRM_ERROR("mode set failed: pipe %c stuck\n", pipe_name(pipe));
4579         }
4580 }
4581
4582 static int
4583 skl_update_scaler(struct intel_crtc_state *crtc_state, bool force_detach,
4584                   unsigned scaler_user, int *scaler_id, unsigned int rotation,
4585                   int src_w, int src_h, int dst_w, int dst_h)
4586 {
4587         struct intel_crtc_scaler_state *scaler_state =
4588                 &crtc_state->scaler_state;
4589         struct intel_crtc *intel_crtc =
4590                 to_intel_crtc(crtc_state->base.crtc);
4591         int need_scaling;
4592
4593         need_scaling = intel_rotation_90_or_270(rotation) ?
4594                 (src_h != dst_w || src_w != dst_h):
4595                 (src_w != dst_w || src_h != dst_h);
4596
4597         /*
4598          * if plane is being disabled or scaler is no more required or force detach
4599          *  - free scaler binded to this plane/crtc
4600          *  - in order to do this, update crtc->scaler_usage
4601          *
4602          * Here scaler state in crtc_state is set free so that
4603          * scaler can be assigned to other user. Actual register
4604          * update to free the scaler is done in plane/panel-fit programming.
4605          * For this purpose crtc/plane_state->scaler_id isn't reset here.
4606          */
4607         if (force_detach || !need_scaling) {
4608                 if (*scaler_id >= 0) {
4609                         scaler_state->scaler_users &= ~(1 << scaler_user);
4610                         scaler_state->scalers[*scaler_id].in_use = 0;
4611
4612                         DRM_DEBUG_KMS("scaler_user index %u.%u: "
4613                                 "Staged freeing scaler id %d scaler_users = 0x%x\n",
4614                                 intel_crtc->pipe, scaler_user, *scaler_id,
4615                                 scaler_state->scaler_users);
4616                         *scaler_id = -1;
4617                 }
4618                 return 0;
4619         }
4620
4621         /* range checks */
4622         if (src_w < SKL_MIN_SRC_W || src_h < SKL_MIN_SRC_H ||
4623                 dst_w < SKL_MIN_DST_W || dst_h < SKL_MIN_DST_H ||
4624
4625                 src_w > SKL_MAX_SRC_W || src_h > SKL_MAX_SRC_H ||
4626                 dst_w > SKL_MAX_DST_W || dst_h > SKL_MAX_DST_H) {
4627                 DRM_DEBUG_KMS("scaler_user index %u.%u: src %ux%u dst %ux%u "
4628                         "size is out of scaler range\n",
4629                         intel_crtc->pipe, scaler_user, src_w, src_h, dst_w, dst_h);
4630                 return -EINVAL;
4631         }
4632
4633         /* mark this plane as a scaler user in crtc_state */
4634         scaler_state->scaler_users |= (1 << scaler_user);
4635         DRM_DEBUG_KMS("scaler_user index %u.%u: "
4636                 "staged scaling request for %ux%u->%ux%u scaler_users = 0x%x\n",
4637                 intel_crtc->pipe, scaler_user, src_w, src_h, dst_w, dst_h,
4638                 scaler_state->scaler_users);
4639
4640         return 0;
4641 }
4642
4643 /**
4644  * skl_update_scaler_crtc - Stages update to scaler state for a given crtc.
4645  *
4646  * @state: crtc's scaler state
4647  *
4648  * Return
4649  *     0 - scaler_usage updated successfully
4650  *    error - requested scaling cannot be supported or other error condition
4651  */
4652 int skl_update_scaler_crtc(struct intel_crtc_state *state)
4653 {
4654         struct intel_crtc *intel_crtc = to_intel_crtc(state->base.crtc);
4655         const struct drm_display_mode *adjusted_mode = &state->base.adjusted_mode;
4656
4657         DRM_DEBUG_KMS("Updating scaler for [CRTC:%d:%s] scaler_user index %u.%u\n",
4658                       intel_crtc->base.base.id, intel_crtc->base.name,
4659                       intel_crtc->pipe, SKL_CRTC_INDEX);
4660
4661         return skl_update_scaler(state, !state->base.active, SKL_CRTC_INDEX,
4662                 &state->scaler_state.scaler_id, BIT(DRM_ROTATE_0),
4663                 state->pipe_src_w, state->pipe_src_h,
4664                 adjusted_mode->crtc_hdisplay, adjusted_mode->crtc_vdisplay);
4665 }
4666
4667 /**
4668  * skl_update_scaler_plane - Stages update to scaler state for a given plane.
4669  *
4670  * @state: crtc's scaler state
4671  * @plane_state: atomic plane state to update
4672  *
4673  * Return
4674  *     0 - scaler_usage updated successfully
4675  *    error - requested scaling cannot be supported or other error condition
4676  */
4677 static int skl_update_scaler_plane(struct intel_crtc_state *crtc_state,
4678                                    struct intel_plane_state *plane_state)
4679 {
4680
4681         struct intel_crtc *intel_crtc = to_intel_crtc(crtc_state->base.crtc);
4682         struct intel_plane *intel_plane =
4683                 to_intel_plane(plane_state->base.plane);
4684         struct drm_framebuffer *fb = plane_state->base.fb;
4685         int ret;
4686
4687         bool force_detach = !fb || !plane_state->visible;
4688
4689         DRM_DEBUG_KMS("Updating scaler for [PLANE:%d:%s] scaler_user index %u.%u\n",
4690                       intel_plane->base.base.id, intel_plane->base.name,
4691                       intel_crtc->pipe, drm_plane_index(&intel_plane->base));
4692
4693         ret = skl_update_scaler(crtc_state, force_detach,
4694                                 drm_plane_index(&intel_plane->base),
4695                                 &plane_state->scaler_id,
4696                                 plane_state->base.rotation,
4697                                 drm_rect_width(&plane_state->src) >> 16,
4698                                 drm_rect_height(&plane_state->src) >> 16,
4699                                 drm_rect_width(&plane_state->dst),
4700                                 drm_rect_height(&plane_state->dst));
4701
4702         if (ret || plane_state->scaler_id < 0)
4703                 return ret;
4704
4705         /* check colorkey */
4706         if (plane_state->ckey.flags != I915_SET_COLORKEY_NONE) {
4707                 DRM_DEBUG_KMS("[PLANE:%d:%s] scaling with color key not allowed",
4708                               intel_plane->base.base.id,
4709                               intel_plane->base.name);
4710                 return -EINVAL;
4711         }
4712
4713         /* Check src format */
4714         switch (fb->pixel_format) {
4715         case DRM_FORMAT_RGB565:
4716         case DRM_FORMAT_XBGR8888:
4717         case DRM_FORMAT_XRGB8888:
4718         case DRM_FORMAT_ABGR8888:
4719         case DRM_FORMAT_ARGB8888:
4720         case DRM_FORMAT_XRGB2101010:
4721         case DRM_FORMAT_XBGR2101010:
4722         case DRM_FORMAT_YUYV:
4723         case DRM_FORMAT_YVYU:
4724         case DRM_FORMAT_UYVY:
4725         case DRM_FORMAT_VYUY:
4726                 break;
4727         default:
4728                 DRM_DEBUG_KMS("[PLANE:%d:%s] FB:%d unsupported scaling format 0x%x\n",
4729                               intel_plane->base.base.id, intel_plane->base.name,
4730                               fb->base.id, fb->pixel_format);
4731                 return -EINVAL;
4732         }
4733
4734         return 0;
4735 }
4736
4737 static void skylake_scaler_disable(struct intel_crtc *crtc)
4738 {
4739         int i;
4740
4741         for (i = 0; i < crtc->num_scalers; i++)
4742                 skl_detach_scaler(crtc, i);
4743 }
4744
4745 static void skylake_pfit_enable(struct intel_crtc *crtc)
4746 {
4747         struct drm_device *dev = crtc->base.dev;
4748         struct drm_i915_private *dev_priv = to_i915(dev);
4749         int pipe = crtc->pipe;
4750         struct intel_crtc_scaler_state *scaler_state =
4751                 &crtc->config->scaler_state;
4752
4753         DRM_DEBUG_KMS("for crtc_state = %p\n", crtc->config);
4754
4755         if (crtc->config->pch_pfit.enabled) {
4756                 int id;
4757
4758                 if (WARN_ON(crtc->config->scaler_state.scaler_id < 0)) {
4759                         DRM_ERROR("Requesting pfit without getting a scaler first\n");
4760                         return;
4761                 }
4762
4763                 id = scaler_state->scaler_id;
4764                 I915_WRITE(SKL_PS_CTRL(pipe, id), PS_SCALER_EN |
4765                         PS_FILTER_MEDIUM | scaler_state->scalers[id].mode);
4766                 I915_WRITE(SKL_PS_WIN_POS(pipe, id), crtc->config->pch_pfit.pos);
4767                 I915_WRITE(SKL_PS_WIN_SZ(pipe, id), crtc->config->pch_pfit.size);
4768
4769                 DRM_DEBUG_KMS("for crtc_state = %p scaler_id = %d\n", crtc->config, id);
4770         }
4771 }
4772
4773 static void ironlake_pfit_enable(struct intel_crtc *crtc)
4774 {
4775         struct drm_device *dev = crtc->base.dev;
4776         struct drm_i915_private *dev_priv = to_i915(dev);
4777         int pipe = crtc->pipe;
4778
4779         if (crtc->config->pch_pfit.enabled) {
4780                 /* Force use of hard-coded filter coefficients
4781                  * as some pre-programmed values are broken,
4782                  * e.g. x201.
4783                  */
4784                 if (IS_IVYBRIDGE(dev) || IS_HASWELL(dev))
4785                         I915_WRITE(PF_CTL(pipe), PF_ENABLE | PF_FILTER_MED_3x3 |
4786                                                  PF_PIPE_SEL_IVB(pipe));
4787                 else
4788                         I915_WRITE(PF_CTL(pipe), PF_ENABLE | PF_FILTER_MED_3x3);
4789                 I915_WRITE(PF_WIN_POS(pipe), crtc->config->pch_pfit.pos);
4790                 I915_WRITE(PF_WIN_SZ(pipe), crtc->config->pch_pfit.size);
4791         }
4792 }
4793
4794 void hsw_enable_ips(struct intel_crtc *crtc)
4795 {
4796         struct drm_device *dev = crtc->base.dev;
4797         struct drm_i915_private *dev_priv = to_i915(dev);
4798
4799         if (!crtc->config->ips_enabled)
4800                 return;
4801
4802         /*
4803          * We can only enable IPS after we enable a plane and wait for a vblank
4804          * This function is called from post_plane_update, which is run after
4805          * a vblank wait.
4806          */
4807
4808         assert_plane_enabled(dev_priv, crtc->plane);
4809         if (IS_BROADWELL(dev)) {
4810                 mutex_lock(&dev_priv->rps.hw_lock);
4811                 WARN_ON(sandybridge_pcode_write(dev_priv, DISPLAY_IPS_CONTROL, 0xc0000000));
4812                 mutex_unlock(&dev_priv->rps.hw_lock);
4813                 /* Quoting Art Runyan: "its not safe to expect any particular
4814                  * value in IPS_CTL bit 31 after enabling IPS through the
4815                  * mailbox." Moreover, the mailbox may return a bogus state,
4816                  * so we need to just enable it and continue on.
4817                  */
4818         } else {
4819                 I915_WRITE(IPS_CTL, IPS_ENABLE);
4820                 /* The bit only becomes 1 in the next vblank, so this wait here
4821                  * is essentially intel_wait_for_vblank. If we don't have this
4822                  * and don't wait for vblanks until the end of crtc_enable, then
4823                  * the HW state readout code will complain that the expected
4824                  * IPS_CTL value is not the one we read. */
4825                 if (intel_wait_for_register(dev_priv,
4826                                             IPS_CTL, IPS_ENABLE, IPS_ENABLE,
4827                                             50))
4828                         DRM_ERROR("Timed out waiting for IPS enable\n");
4829         }
4830 }
4831
4832 void hsw_disable_ips(struct intel_crtc *crtc)
4833 {
4834         struct drm_device *dev = crtc->base.dev;
4835         struct drm_i915_private *dev_priv = to_i915(dev);
4836
4837         if (!crtc->config->ips_enabled)
4838                 return;
4839
4840         assert_plane_enabled(dev_priv, crtc->plane);
4841         if (IS_BROADWELL(dev)) {
4842                 mutex_lock(&dev_priv->rps.hw_lock);
4843                 WARN_ON(sandybridge_pcode_write(dev_priv, DISPLAY_IPS_CONTROL, 0));
4844                 mutex_unlock(&dev_priv->rps.hw_lock);
4845                 /* wait for pcode to finish disabling IPS, which may take up to 42ms */
4846                 if (intel_wait_for_register(dev_priv,
4847                                             IPS_CTL, IPS_ENABLE, 0,
4848                                             42))
4849                         DRM_ERROR("Timed out waiting for IPS disable\n");
4850         } else {
4851                 I915_WRITE(IPS_CTL, 0);
4852                 POSTING_READ(IPS_CTL);
4853         }
4854
4855         /* We need to wait for a vblank before we can disable the plane. */
4856         intel_wait_for_vblank(dev, crtc->pipe);
4857 }
4858
4859 static void intel_crtc_dpms_overlay_disable(struct intel_crtc *intel_crtc)
4860 {
4861         if (intel_crtc->overlay) {
4862                 struct drm_device *dev = intel_crtc->base.dev;
4863                 struct drm_i915_private *dev_priv = to_i915(dev);
4864
4865                 mutex_lock(&dev->struct_mutex);
4866                 dev_priv->mm.interruptible = false;
4867                 (void) intel_overlay_switch_off(intel_crtc->overlay);
4868                 dev_priv->mm.interruptible = true;
4869                 mutex_unlock(&dev->struct_mutex);
4870         }
4871
4872         /* Let userspace switch the overlay on again. In most cases userspace
4873          * has to recompute where to put it anyway.
4874          */
4875 }
4876
4877 /**
4878  * intel_post_enable_primary - Perform operations after enabling primary plane
4879  * @crtc: the CRTC whose primary plane was just enabled
4880  *
4881  * Performs potentially sleeping operations that must be done after the primary
4882  * plane is enabled, such as updating FBC and IPS.  Note that this may be
4883  * called due to an explicit primary plane update, or due to an implicit
4884  * re-enable that is caused when a sprite plane is updated to no longer
4885  * completely hide the primary plane.
4886  */
4887 static void
4888 intel_post_enable_primary(struct drm_crtc *crtc)
4889 {
4890         struct drm_device *dev = crtc->dev;
4891         struct drm_i915_private *dev_priv = to_i915(dev);
4892         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4893         int pipe = intel_crtc->pipe;
4894
4895         /*
4896          * FIXME IPS should be fine as long as one plane is
4897          * enabled, but in practice it seems to have problems
4898          * when going from primary only to sprite only and vice
4899          * versa.
4900          */
4901         hsw_enable_ips(intel_crtc);
4902
4903         /*
4904          * Gen2 reports pipe underruns whenever all planes are disabled.
4905          * So don't enable underrun reporting before at least some planes
4906          * are enabled.
4907          * FIXME: Need to fix the logic to work when we turn off all planes
4908          * but leave the pipe running.
4909          */
4910         if (IS_GEN2(dev))
4911                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
4912
4913         /* Underruns don't always raise interrupts, so check manually. */
4914         intel_check_cpu_fifo_underruns(dev_priv);
4915         intel_check_pch_fifo_underruns(dev_priv);
4916 }
4917
4918 /* FIXME move all this to pre_plane_update() with proper state tracking */
4919 static void
4920 intel_pre_disable_primary(struct drm_crtc *crtc)
4921 {
4922         struct drm_device *dev = crtc->dev;
4923         struct drm_i915_private *dev_priv = to_i915(dev);
4924         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4925         int pipe = intel_crtc->pipe;
4926
4927         /*
4928          * Gen2 reports pipe underruns whenever all planes are disabled.
4929          * So diasble underrun reporting before all the planes get disabled.
4930          * FIXME: Need to fix the logic to work when we turn off all planes
4931          * but leave the pipe running.
4932          */
4933         if (IS_GEN2(dev))
4934                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
4935
4936         /*
4937          * FIXME IPS should be fine as long as one plane is
4938          * enabled, but in practice it seems to have problems
4939          * when going from primary only to sprite only and vice
4940          * versa.
4941          */
4942         hsw_disable_ips(intel_crtc);
4943 }
4944
4945 /* FIXME get rid of this and use pre_plane_update */
4946 static void
4947 intel_pre_disable_primary_noatomic(struct drm_crtc *crtc)
4948 {
4949         struct drm_device *dev = crtc->dev;
4950         struct drm_i915_private *dev_priv = to_i915(dev);
4951         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4952         int pipe = intel_crtc->pipe;
4953
4954         intel_pre_disable_primary(crtc);
4955
4956         /*
4957          * Vblank time updates from the shadow to live plane control register
4958          * are blocked if the memory self-refresh mode is active at that
4959          * moment. So to make sure the plane gets truly disabled, disable
4960          * first the self-refresh mode. The self-refresh enable bit in turn
4961          * will be checked/applied by the HW only at the next frame start
4962          * event which is after the vblank start event, so we need to have a
4963          * wait-for-vblank between disabling the plane and the pipe.
4964          */
4965         if (HAS_GMCH_DISPLAY(dev)) {
4966                 intel_set_memory_cxsr(dev_priv, false);
4967                 dev_priv->wm.vlv.cxsr = false;
4968                 intel_wait_for_vblank(dev, pipe);
4969         }
4970 }
4971
4972 static void intel_post_plane_update(struct intel_crtc_state *old_crtc_state)
4973 {
4974         struct intel_crtc *crtc = to_intel_crtc(old_crtc_state->base.crtc);
4975         struct drm_atomic_state *old_state = old_crtc_state->base.state;
4976         struct intel_crtc_state *pipe_config =
4977                 to_intel_crtc_state(crtc->base.state);
4978         struct drm_plane *primary = crtc->base.primary;
4979         struct drm_plane_state *old_pri_state =
4980                 drm_atomic_get_existing_plane_state(old_state, primary);
4981
4982         intel_frontbuffer_flip(to_i915(crtc->base.dev), pipe_config->fb_bits);
4983
4984         crtc->wm.cxsr_allowed = true;
4985
4986         if (pipe_config->update_wm_post && pipe_config->base.active)
4987                 intel_update_watermarks(&crtc->base);
4988
4989         if (old_pri_state) {
4990                 struct intel_plane_state *primary_state =
4991                         to_intel_plane_state(primary->state);
4992                 struct intel_plane_state *old_primary_state =
4993                         to_intel_plane_state(old_pri_state);
4994
4995                 intel_fbc_post_update(crtc);
4996
4997                 if (primary_state->visible &&
4998                     (needs_modeset(&pipe_config->base) ||
4999                      !old_primary_state->visible))
5000                         intel_post_enable_primary(&crtc->base);
5001         }
5002 }
5003
5004 static void intel_pre_plane_update(struct intel_crtc_state *old_crtc_state)
5005 {
5006         struct intel_crtc *crtc = to_intel_crtc(old_crtc_state->base.crtc);
5007         struct drm_device *dev = crtc->base.dev;
5008         struct drm_i915_private *dev_priv = to_i915(dev);
5009         struct intel_crtc_state *pipe_config =
5010                 to_intel_crtc_state(crtc->base.state);
5011         struct drm_atomic_state *old_state = old_crtc_state->base.state;
5012         struct drm_plane *primary = crtc->base.primary;
5013         struct drm_plane_state *old_pri_state =
5014                 drm_atomic_get_existing_plane_state(old_state, primary);
5015         bool modeset = needs_modeset(&pipe_config->base);
5016
5017         if (old_pri_state) {
5018                 struct intel_plane_state *primary_state =
5019                         to_intel_plane_state(primary->state);
5020                 struct intel_plane_state *old_primary_state =
5021                         to_intel_plane_state(old_pri_state);
5022
5023                 intel_fbc_pre_update(crtc, pipe_config, primary_state);
5024
5025                 if (old_primary_state->visible &&
5026                     (modeset || !primary_state->visible))
5027                         intel_pre_disable_primary(&crtc->base);
5028         }
5029
5030         if (pipe_config->disable_cxsr && HAS_GMCH_DISPLAY(dev)) {
5031                 crtc->wm.cxsr_allowed = false;
5032
5033                 /*
5034                  * Vblank time updates from the shadow to live plane control register
5035                  * are blocked if the memory self-refresh mode is active at that
5036                  * moment. So to make sure the plane gets truly disabled, disable
5037                  * first the self-refresh mode. The self-refresh enable bit in turn
5038                  * will be checked/applied by the HW only at the next frame start
5039                  * event which is after the vblank start event, so we need to have a
5040                  * wait-for-vblank between disabling the plane and the pipe.
5041                  */
5042                 if (old_crtc_state->base.active) {
5043                         intel_set_memory_cxsr(dev_priv, false);
5044                         dev_priv->wm.vlv.cxsr = false;
5045                         intel_wait_for_vblank(dev, crtc->pipe);
5046                 }
5047         }
5048
5049         /*
5050          * IVB workaround: must disable low power watermarks for at least
5051          * one frame before enabling scaling.  LP watermarks can be re-enabled
5052          * when scaling is disabled.
5053          *
5054          * WaCxSRDisabledForSpriteScaling:ivb
5055          */
5056         if (pipe_config->disable_lp_wm) {
5057                 ilk_disable_lp_wm(dev);
5058                 intel_wait_for_vblank(dev, crtc->pipe);
5059         }
5060
5061         /*
5062          * If we're doing a modeset, we're done.  No need to do any pre-vblank
5063          * watermark programming here.
5064          */
5065         if (needs_modeset(&pipe_config->base))
5066                 return;
5067
5068         /*
5069          * For platforms that support atomic watermarks, program the
5070          * 'intermediate' watermarks immediately.  On pre-gen9 platforms, these
5071          * will be the intermediate values that are safe for both pre- and
5072          * post- vblank; when vblank happens, the 'active' values will be set
5073          * to the final 'target' values and we'll do this again to get the
5074          * optimal watermarks.  For gen9+ platforms, the values we program here
5075          * will be the final target values which will get automatically latched
5076          * at vblank time; no further programming will be necessary.
5077          *
5078          * If a platform hasn't been transitioned to atomic watermarks yet,
5079          * we'll continue to update watermarks the old way, if flags tell
5080          * us to.
5081          */
5082         if (dev_priv->display.initial_watermarks != NULL)
5083                 dev_priv->display.initial_watermarks(pipe_config);
5084         else if (pipe_config->update_wm_pre)
5085                 intel_update_watermarks(&crtc->base);
5086 }
5087
5088 static void intel_crtc_disable_planes(struct drm_crtc *crtc, unsigned plane_mask)
5089 {
5090         struct drm_device *dev = crtc->dev;
5091         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5092         struct drm_plane *p;
5093         int pipe = intel_crtc->pipe;
5094
5095         intel_crtc_dpms_overlay_disable(intel_crtc);
5096
5097         drm_for_each_plane_mask(p, dev, plane_mask)
5098                 to_intel_plane(p)->disable_plane(p, crtc);
5099
5100         /*
5101          * FIXME: Once we grow proper nuclear flip support out of this we need
5102          * to compute the mask of flip planes precisely. For the time being
5103          * consider this a flip to a NULL plane.
5104          */
5105         intel_frontbuffer_flip(to_i915(dev), INTEL_FRONTBUFFER_ALL_MASK(pipe));
5106 }
5107
5108 static void ironlake_crtc_enable(struct drm_crtc *crtc)
5109 {
5110         struct drm_device *dev = crtc->dev;
5111         struct drm_i915_private *dev_priv = to_i915(dev);
5112         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5113         struct intel_encoder *encoder;
5114         int pipe = intel_crtc->pipe;
5115         struct intel_crtc_state *pipe_config =
5116                 to_intel_crtc_state(crtc->state);
5117
5118         if (WARN_ON(intel_crtc->active))
5119                 return;
5120
5121         /*
5122          * Sometimes spurious CPU pipe underruns happen during FDI
5123          * training, at least with VGA+HDMI cloning. Suppress them.
5124          *
5125          * On ILK we get an occasional spurious CPU pipe underruns
5126          * between eDP port A enable and vdd enable. Also PCH port
5127          * enable seems to result in the occasional CPU pipe underrun.
5128          *
5129          * Spurious PCH underruns also occur during PCH enabling.
5130          */
5131         if (intel_crtc->config->has_pch_encoder || IS_GEN5(dev_priv))
5132                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
5133         if (intel_crtc->config->has_pch_encoder)
5134                 intel_set_pch_fifo_underrun_reporting(dev_priv, pipe, false);
5135
5136         if (intel_crtc->config->has_pch_encoder)
5137                 intel_prepare_shared_dpll(intel_crtc);
5138
5139         if (intel_crtc_has_dp_encoder(intel_crtc->config))
5140                 intel_dp_set_m_n(intel_crtc, M1_N1);
5141
5142         intel_set_pipe_timings(intel_crtc);
5143         intel_set_pipe_src_size(intel_crtc);
5144
5145         if (intel_crtc->config->has_pch_encoder) {
5146                 intel_cpu_transcoder_set_m_n(intel_crtc,
5147                                      &intel_crtc->config->fdi_m_n, NULL);
5148         }
5149
5150         ironlake_set_pipeconf(crtc);
5151
5152         intel_crtc->active = true;
5153
5154         for_each_encoder_on_crtc(dev, crtc, encoder)
5155                 if (encoder->pre_enable)
5156                         encoder->pre_enable(encoder);
5157
5158         if (intel_crtc->config->has_pch_encoder) {
5159                 /* Note: FDI PLL enabling _must_ be done before we enable the
5160                  * cpu pipes, hence this is separate from all the other fdi/pch
5161                  * enabling. */
5162                 ironlake_fdi_pll_enable(intel_crtc);
5163         } else {
5164                 assert_fdi_tx_disabled(dev_priv, pipe);
5165                 assert_fdi_rx_disabled(dev_priv, pipe);
5166         }
5167
5168         ironlake_pfit_enable(intel_crtc);
5169
5170         /*
5171          * On ILK+ LUT must be loaded before the pipe is running but with
5172          * clocks enabled
5173          */
5174         intel_color_load_luts(&pipe_config->base);
5175
5176         if (dev_priv->display.initial_watermarks != NULL)
5177                 dev_priv->display.initial_watermarks(intel_crtc->config);
5178         intel_enable_pipe(intel_crtc);
5179
5180         if (intel_crtc->config->has_pch_encoder)
5181                 ironlake_pch_enable(crtc);
5182
5183         assert_vblank_disabled(crtc);
5184         drm_crtc_vblank_on(crtc);
5185
5186         for_each_encoder_on_crtc(dev, crtc, encoder)
5187                 encoder->enable(encoder);
5188
5189         if (HAS_PCH_CPT(dev))
5190                 cpt_verify_modeset(dev, intel_crtc->pipe);
5191
5192         /* Must wait for vblank to avoid spurious PCH FIFO underruns */
5193         if (intel_crtc->config->has_pch_encoder)
5194                 intel_wait_for_vblank(dev, pipe);
5195         intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
5196         intel_set_pch_fifo_underrun_reporting(dev_priv, pipe, true);
5197 }
5198
5199 /* IPS only exists on ULT machines and is tied to pipe A. */
5200 static bool hsw_crtc_supports_ips(struct intel_crtc *crtc)
5201 {
5202         return HAS_IPS(crtc->base.dev) && crtc->pipe == PIPE_A;
5203 }
5204
5205 static void haswell_crtc_enable(struct drm_crtc *crtc)
5206 {
5207         struct drm_device *dev = crtc->dev;
5208         struct drm_i915_private *dev_priv = to_i915(dev);
5209         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5210         struct intel_encoder *encoder;
5211         int pipe = intel_crtc->pipe, hsw_workaround_pipe;
5212         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
5213         struct intel_crtc_state *pipe_config =
5214                 to_intel_crtc_state(crtc->state);
5215
5216         if (WARN_ON(intel_crtc->active))
5217                 return;
5218
5219         if (intel_crtc->config->has_pch_encoder)
5220                 intel_set_pch_fifo_underrun_reporting(dev_priv, TRANSCODER_A,
5221                                                       false);
5222
5223         for_each_encoder_on_crtc(dev, crtc, encoder)
5224                 if (encoder->pre_pll_enable)
5225                         encoder->pre_pll_enable(encoder);
5226
5227         if (intel_crtc->config->shared_dpll)
5228                 intel_enable_shared_dpll(intel_crtc);
5229
5230         if (intel_crtc_has_dp_encoder(intel_crtc->config))
5231                 intel_dp_set_m_n(intel_crtc, M1_N1);
5232
5233         if (!transcoder_is_dsi(cpu_transcoder))
5234                 intel_set_pipe_timings(intel_crtc);
5235
5236         intel_set_pipe_src_size(intel_crtc);
5237
5238         if (cpu_transcoder != TRANSCODER_EDP &&
5239             !transcoder_is_dsi(cpu_transcoder)) {
5240                 I915_WRITE(PIPE_MULT(cpu_transcoder),
5241                            intel_crtc->config->pixel_multiplier - 1);
5242         }
5243
5244         if (intel_crtc->config->has_pch_encoder) {
5245                 intel_cpu_transcoder_set_m_n(intel_crtc,
5246                                      &intel_crtc->config->fdi_m_n, NULL);
5247         }
5248
5249         if (!transcoder_is_dsi(cpu_transcoder))
5250                 haswell_set_pipeconf(crtc);
5251
5252         haswell_set_pipemisc(crtc);
5253
5254         intel_color_set_csc(&pipe_config->base);
5255
5256         intel_crtc->active = true;
5257
5258         if (intel_crtc->config->has_pch_encoder)
5259                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
5260         else
5261                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
5262
5263         for_each_encoder_on_crtc(dev, crtc, encoder) {
5264                 if (encoder->pre_enable)
5265                         encoder->pre_enable(encoder);
5266         }
5267
5268         if (intel_crtc->config->has_pch_encoder)
5269                 dev_priv->display.fdi_link_train(crtc);
5270
5271         if (!transcoder_is_dsi(cpu_transcoder))
5272                 intel_ddi_enable_pipe_clock(intel_crtc);
5273
5274         if (INTEL_INFO(dev)->gen >= 9)
5275                 skylake_pfit_enable(intel_crtc);
5276         else
5277                 ironlake_pfit_enable(intel_crtc);
5278
5279         /*
5280          * On ILK+ LUT must be loaded before the pipe is running but with
5281          * clocks enabled
5282          */
5283         intel_color_load_luts(&pipe_config->base);
5284
5285         intel_ddi_set_pipe_settings(crtc);
5286         if (!transcoder_is_dsi(cpu_transcoder))
5287                 intel_ddi_enable_transcoder_func(crtc);
5288
5289         if (dev_priv->display.initial_watermarks != NULL)
5290                 dev_priv->display.initial_watermarks(pipe_config);
5291         else
5292                 intel_update_watermarks(crtc);
5293
5294         /* XXX: Do the pipe assertions at the right place for BXT DSI. */
5295         if (!transcoder_is_dsi(cpu_transcoder))
5296                 intel_enable_pipe(intel_crtc);
5297
5298         if (intel_crtc->config->has_pch_encoder)
5299                 lpt_pch_enable(crtc);
5300
5301         if (intel_crtc->config->dp_encoder_is_mst)
5302                 intel_ddi_set_vc_payload_alloc(crtc, true);
5303
5304         assert_vblank_disabled(crtc);
5305         drm_crtc_vblank_on(crtc);
5306
5307         for_each_encoder_on_crtc(dev, crtc, encoder) {
5308                 encoder->enable(encoder);
5309                 intel_opregion_notify_encoder(encoder, true);
5310         }
5311
5312         if (intel_crtc->config->has_pch_encoder) {
5313                 intel_wait_for_vblank(dev, pipe);
5314                 intel_wait_for_vblank(dev, pipe);
5315                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
5316                 intel_set_pch_fifo_underrun_reporting(dev_priv, TRANSCODER_A,
5317                                                       true);
5318         }
5319
5320         /* If we change the relative order between pipe/planes enabling, we need
5321          * to change the workaround. */
5322         hsw_workaround_pipe = pipe_config->hsw_workaround_pipe;
5323         if (IS_HASWELL(dev) && hsw_workaround_pipe != INVALID_PIPE) {
5324                 intel_wait_for_vblank(dev, hsw_workaround_pipe);
5325                 intel_wait_for_vblank(dev, hsw_workaround_pipe);
5326         }
5327 }
5328
5329 static void ironlake_pfit_disable(struct intel_crtc *crtc, bool force)
5330 {
5331         struct drm_device *dev = crtc->base.dev;
5332         struct drm_i915_private *dev_priv = to_i915(dev);
5333         int pipe = crtc->pipe;
5334
5335         /* To avoid upsetting the power well on haswell only disable the pfit if
5336          * it's in use. The hw state code will make sure we get this right. */
5337         if (force || crtc->config->pch_pfit.enabled) {
5338                 I915_WRITE(PF_CTL(pipe), 0);
5339                 I915_WRITE(PF_WIN_POS(pipe), 0);
5340                 I915_WRITE(PF_WIN_SZ(pipe), 0);
5341         }
5342 }
5343
5344 static void ironlake_crtc_disable(struct drm_crtc *crtc)
5345 {
5346         struct drm_device *dev = crtc->dev;
5347         struct drm_i915_private *dev_priv = to_i915(dev);
5348         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5349         struct intel_encoder *encoder;
5350         int pipe = intel_crtc->pipe;
5351
5352         /*
5353          * Sometimes spurious CPU pipe underruns happen when the
5354          * pipe is already disabled, but FDI RX/TX is still enabled.
5355          * Happens at least with VGA+HDMI cloning. Suppress them.
5356          */
5357         if (intel_crtc->config->has_pch_encoder) {
5358                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
5359                 intel_set_pch_fifo_underrun_reporting(dev_priv, pipe, false);
5360         }
5361
5362         for_each_encoder_on_crtc(dev, crtc, encoder)
5363                 encoder->disable(encoder);
5364
5365         drm_crtc_vblank_off(crtc);
5366         assert_vblank_disabled(crtc);
5367
5368         intel_disable_pipe(intel_crtc);
5369
5370         ironlake_pfit_disable(intel_crtc, false);
5371
5372         if (intel_crtc->config->has_pch_encoder)
5373                 ironlake_fdi_disable(crtc);
5374
5375         for_each_encoder_on_crtc(dev, crtc, encoder)
5376                 if (encoder->post_disable)
5377                         encoder->post_disable(encoder);
5378
5379         if (intel_crtc->config->has_pch_encoder) {
5380                 ironlake_disable_pch_transcoder(dev_priv, pipe);
5381
5382                 if (HAS_PCH_CPT(dev)) {
5383                         i915_reg_t reg;
5384                         u32 temp;
5385
5386                         /* disable TRANS_DP_CTL */
5387                         reg = TRANS_DP_CTL(pipe);
5388                         temp = I915_READ(reg);
5389                         temp &= ~(TRANS_DP_OUTPUT_ENABLE |
5390                                   TRANS_DP_PORT_SEL_MASK);
5391                         temp |= TRANS_DP_PORT_SEL_NONE;
5392                         I915_WRITE(reg, temp);
5393
5394                         /* disable DPLL_SEL */
5395                         temp = I915_READ(PCH_DPLL_SEL);
5396                         temp &= ~(TRANS_DPLL_ENABLE(pipe) | TRANS_DPLLB_SEL(pipe));
5397                         I915_WRITE(PCH_DPLL_SEL, temp);
5398                 }
5399
5400                 ironlake_fdi_pll_disable(intel_crtc);
5401         }
5402
5403         intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
5404         intel_set_pch_fifo_underrun_reporting(dev_priv, pipe, true);
5405 }
5406
5407 static void haswell_crtc_disable(struct drm_crtc *crtc)
5408 {
5409         struct drm_device *dev = crtc->dev;
5410         struct drm_i915_private *dev_priv = to_i915(dev);
5411         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5412         struct intel_encoder *encoder;
5413         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
5414
5415         if (intel_crtc->config->has_pch_encoder)
5416                 intel_set_pch_fifo_underrun_reporting(dev_priv, TRANSCODER_A,
5417                                                       false);
5418
5419         for_each_encoder_on_crtc(dev, crtc, encoder) {
5420                 intel_opregion_notify_encoder(encoder, false);
5421                 encoder->disable(encoder);
5422         }
5423
5424         drm_crtc_vblank_off(crtc);
5425         assert_vblank_disabled(crtc);
5426
5427         /* XXX: Do the pipe assertions at the right place for BXT DSI. */
5428         if (!transcoder_is_dsi(cpu_transcoder))
5429                 intel_disable_pipe(intel_crtc);
5430
5431         if (intel_crtc->config->dp_encoder_is_mst)
5432                 intel_ddi_set_vc_payload_alloc(crtc, false);
5433
5434         if (!transcoder_is_dsi(cpu_transcoder))
5435                 intel_ddi_disable_transcoder_func(dev_priv, cpu_transcoder);
5436
5437         if (INTEL_INFO(dev)->gen >= 9)
5438                 skylake_scaler_disable(intel_crtc);
5439         else
5440                 ironlake_pfit_disable(intel_crtc, false);
5441
5442         if (!transcoder_is_dsi(cpu_transcoder))
5443                 intel_ddi_disable_pipe_clock(intel_crtc);
5444
5445         for_each_encoder_on_crtc(dev, crtc, encoder)
5446                 if (encoder->post_disable)
5447                         encoder->post_disable(encoder);
5448
5449         if (intel_crtc->config->has_pch_encoder) {
5450                 lpt_disable_pch_transcoder(dev_priv);
5451                 lpt_disable_iclkip(dev_priv);
5452                 intel_ddi_fdi_disable(crtc);
5453
5454                 intel_set_pch_fifo_underrun_reporting(dev_priv, TRANSCODER_A,
5455                                                       true);
5456         }
5457 }
5458
5459 static void i9xx_pfit_enable(struct intel_crtc *crtc)
5460 {
5461         struct drm_device *dev = crtc->base.dev;
5462         struct drm_i915_private *dev_priv = to_i915(dev);
5463         struct intel_crtc_state *pipe_config = crtc->config;
5464
5465         if (!pipe_config->gmch_pfit.control)
5466                 return;
5467
5468         /*
5469          * The panel fitter should only be adjusted whilst the pipe is disabled,
5470          * according to register description and PRM.
5471          */
5472         WARN_ON(I915_READ(PFIT_CONTROL) & PFIT_ENABLE);
5473         assert_pipe_disabled(dev_priv, crtc->pipe);
5474
5475         I915_WRITE(PFIT_PGM_RATIOS, pipe_config->gmch_pfit.pgm_ratios);
5476         I915_WRITE(PFIT_CONTROL, pipe_config->gmch_pfit.control);
5477
5478         /* Border color in case we don't scale up to the full screen. Black by
5479          * default, change to something else for debugging. */
5480         I915_WRITE(BCLRPAT(crtc->pipe), 0);
5481 }
5482
5483 static enum intel_display_power_domain port_to_power_domain(enum port port)
5484 {
5485         switch (port) {
5486         case PORT_A:
5487                 return POWER_DOMAIN_PORT_DDI_A_LANES;
5488         case PORT_B:
5489                 return POWER_DOMAIN_PORT_DDI_B_LANES;
5490         case PORT_C:
5491                 return POWER_DOMAIN_PORT_DDI_C_LANES;
5492         case PORT_D:
5493                 return POWER_DOMAIN_PORT_DDI_D_LANES;
5494         case PORT_E:
5495                 return POWER_DOMAIN_PORT_DDI_E_LANES;
5496         default:
5497                 MISSING_CASE(port);
5498                 return POWER_DOMAIN_PORT_OTHER;
5499         }
5500 }
5501
5502 static enum intel_display_power_domain port_to_aux_power_domain(enum port port)
5503 {
5504         switch (port) {
5505         case PORT_A:
5506                 return POWER_DOMAIN_AUX_A;
5507         case PORT_B:
5508                 return POWER_DOMAIN_AUX_B;
5509         case PORT_C:
5510                 return POWER_DOMAIN_AUX_C;
5511         case PORT_D:
5512                 return POWER_DOMAIN_AUX_D;
5513         case PORT_E:
5514                 /* FIXME: Check VBT for actual wiring of PORT E */
5515                 return POWER_DOMAIN_AUX_D;
5516         default:
5517                 MISSING_CASE(port);
5518                 return POWER_DOMAIN_AUX_A;
5519         }
5520 }
5521
5522 enum intel_display_power_domain
5523 intel_display_port_power_domain(struct intel_encoder *intel_encoder)
5524 {
5525         struct drm_device *dev = intel_encoder->base.dev;
5526         struct intel_digital_port *intel_dig_port;
5527
5528         switch (intel_encoder->type) {
5529         case INTEL_OUTPUT_UNKNOWN:
5530                 /* Only DDI platforms should ever use this output type */
5531                 WARN_ON_ONCE(!HAS_DDI(dev));
5532         case INTEL_OUTPUT_DP:
5533         case INTEL_OUTPUT_HDMI:
5534         case INTEL_OUTPUT_EDP:
5535                 intel_dig_port = enc_to_dig_port(&intel_encoder->base);
5536                 return port_to_power_domain(intel_dig_port->port);
5537         case INTEL_OUTPUT_DP_MST:
5538                 intel_dig_port = enc_to_mst(&intel_encoder->base)->primary;
5539                 return port_to_power_domain(intel_dig_port->port);
5540         case INTEL_OUTPUT_ANALOG:
5541                 return POWER_DOMAIN_PORT_CRT;
5542         case INTEL_OUTPUT_DSI:
5543                 return POWER_DOMAIN_PORT_DSI;
5544         default:
5545                 return POWER_DOMAIN_PORT_OTHER;
5546         }
5547 }
5548
5549 enum intel_display_power_domain
5550 intel_display_port_aux_power_domain(struct intel_encoder *intel_encoder)
5551 {
5552         struct drm_device *dev = intel_encoder->base.dev;
5553         struct intel_digital_port *intel_dig_port;
5554
5555         switch (intel_encoder->type) {
5556         case INTEL_OUTPUT_UNKNOWN:
5557         case INTEL_OUTPUT_HDMI:
5558                 /*
5559                  * Only DDI platforms should ever use these output types.
5560                  * We can get here after the HDMI detect code has already set
5561                  * the type of the shared encoder. Since we can't be sure
5562                  * what's the status of the given connectors, play safe and
5563                  * run the DP detection too.
5564                  */
5565                 WARN_ON_ONCE(!HAS_DDI(dev));
5566         case INTEL_OUTPUT_DP:
5567         case INTEL_OUTPUT_EDP:
5568                 intel_dig_port = enc_to_dig_port(&intel_encoder->base);
5569                 return port_to_aux_power_domain(intel_dig_port->port);
5570         case INTEL_OUTPUT_DP_MST:
5571                 intel_dig_port = enc_to_mst(&intel_encoder->base)->primary;
5572                 return port_to_aux_power_domain(intel_dig_port->port);
5573         default:
5574                 MISSING_CASE(intel_encoder->type);
5575                 return POWER_DOMAIN_AUX_A;
5576         }
5577 }
5578
5579 static unsigned long get_crtc_power_domains(struct drm_crtc *crtc,
5580                                             struct intel_crtc_state *crtc_state)
5581 {
5582         struct drm_device *dev = crtc->dev;
5583         struct drm_encoder *encoder;
5584         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5585         enum pipe pipe = intel_crtc->pipe;
5586         unsigned long mask;
5587         enum transcoder transcoder = crtc_state->cpu_transcoder;
5588
5589         if (!crtc_state->base.active)
5590                 return 0;
5591
5592         mask = BIT(POWER_DOMAIN_PIPE(pipe));
5593         mask |= BIT(POWER_DOMAIN_TRANSCODER(transcoder));
5594         if (crtc_state->pch_pfit.enabled ||
5595             crtc_state->pch_pfit.force_thru)
5596                 mask |= BIT(POWER_DOMAIN_PIPE_PANEL_FITTER(pipe));
5597
5598         drm_for_each_encoder_mask(encoder, dev, crtc_state->base.encoder_mask) {
5599                 struct intel_encoder *intel_encoder = to_intel_encoder(encoder);
5600
5601                 mask |= BIT(intel_display_port_power_domain(intel_encoder));
5602         }
5603
5604         if (crtc_state->shared_dpll)
5605                 mask |= BIT(POWER_DOMAIN_PLLS);
5606
5607         return mask;
5608 }
5609
5610 static unsigned long
5611 modeset_get_crtc_power_domains(struct drm_crtc *crtc,
5612                                struct intel_crtc_state *crtc_state)
5613 {
5614         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
5615         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5616         enum intel_display_power_domain domain;
5617         unsigned long domains, new_domains, old_domains;
5618
5619         old_domains = intel_crtc->enabled_power_domains;
5620         intel_crtc->enabled_power_domains = new_domains =
5621                 get_crtc_power_domains(crtc, crtc_state);
5622
5623         domains = new_domains & ~old_domains;
5624
5625         for_each_power_domain(domain, domains)
5626                 intel_display_power_get(dev_priv, domain);
5627
5628         return old_domains & ~new_domains;
5629 }
5630
5631 static void modeset_put_power_domains(struct drm_i915_private *dev_priv,
5632                                       unsigned long domains)
5633 {
5634         enum intel_display_power_domain domain;
5635
5636         for_each_power_domain(domain, domains)
5637                 intel_display_power_put(dev_priv, domain);
5638 }
5639
5640 static int intel_compute_max_dotclk(struct drm_i915_private *dev_priv)
5641 {
5642         int max_cdclk_freq = dev_priv->max_cdclk_freq;
5643
5644         if (INTEL_INFO(dev_priv)->gen >= 9 ||
5645             IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv))
5646                 return max_cdclk_freq;
5647         else if (IS_CHERRYVIEW(dev_priv))
5648                 return max_cdclk_freq*95/100;
5649         else if (INTEL_INFO(dev_priv)->gen < 4)
5650                 return 2*max_cdclk_freq*90/100;
5651         else
5652                 return max_cdclk_freq*90/100;
5653 }
5654
5655 static int skl_calc_cdclk(int max_pixclk, int vco);
5656
5657 static void intel_update_max_cdclk(struct drm_device *dev)
5658 {
5659         struct drm_i915_private *dev_priv = to_i915(dev);
5660
5661         if (IS_SKYLAKE(dev) || IS_KABYLAKE(dev)) {
5662                 u32 limit = I915_READ(SKL_DFSM) & SKL_DFSM_CDCLK_LIMIT_MASK;
5663                 int max_cdclk, vco;
5664
5665                 vco = dev_priv->skl_preferred_vco_freq;
5666                 WARN_ON(vco != 8100000 && vco != 8640000);
5667
5668                 /*
5669                  * Use the lower (vco 8640) cdclk values as a
5670                  * first guess. skl_calc_cdclk() will correct it
5671                  * if the preferred vco is 8100 instead.
5672                  */
5673                 if (limit == SKL_DFSM_CDCLK_LIMIT_675)
5674                         max_cdclk = 617143;
5675                 else if (limit == SKL_DFSM_CDCLK_LIMIT_540)
5676                         max_cdclk = 540000;
5677                 else if (limit == SKL_DFSM_CDCLK_LIMIT_450)
5678                         max_cdclk = 432000;
5679                 else
5680                         max_cdclk = 308571;
5681
5682                 dev_priv->max_cdclk_freq = skl_calc_cdclk(max_cdclk, vco);
5683         } else if (IS_BROXTON(dev)) {
5684                 dev_priv->max_cdclk_freq = 624000;
5685         } else if (IS_BROADWELL(dev))  {
5686                 /*
5687                  * FIXME with extra cooling we can allow
5688                  * 540 MHz for ULX and 675 Mhz for ULT.
5689                  * How can we know if extra cooling is
5690                  * available? PCI ID, VTB, something else?
5691                  */
5692                 if (I915_READ(FUSE_STRAP) & HSW_CDCLK_LIMIT)
5693                         dev_priv->max_cdclk_freq = 450000;
5694                 else if (IS_BDW_ULX(dev))
5695                         dev_priv->max_cdclk_freq = 450000;
5696                 else if (IS_BDW_ULT(dev))
5697                         dev_priv->max_cdclk_freq = 540000;
5698                 else
5699                         dev_priv->max_cdclk_freq = 675000;
5700         } else if (IS_CHERRYVIEW(dev)) {
5701                 dev_priv->max_cdclk_freq = 320000;
5702         } else if (IS_VALLEYVIEW(dev)) {
5703                 dev_priv->max_cdclk_freq = 400000;
5704         } else {
5705                 /* otherwise assume cdclk is fixed */
5706                 dev_priv->max_cdclk_freq = dev_priv->cdclk_freq;
5707         }
5708
5709         dev_priv->max_dotclk_freq = intel_compute_max_dotclk(dev_priv);
5710
5711         DRM_DEBUG_DRIVER("Max CD clock rate: %d kHz\n",
5712                          dev_priv->max_cdclk_freq);
5713
5714         DRM_DEBUG_DRIVER("Max dotclock rate: %d kHz\n",
5715                          dev_priv->max_dotclk_freq);
5716 }
5717
5718 static void intel_update_cdclk(struct drm_device *dev)
5719 {
5720         struct drm_i915_private *dev_priv = to_i915(dev);
5721
5722         dev_priv->cdclk_freq = dev_priv->display.get_display_clock_speed(dev);
5723
5724         if (INTEL_GEN(dev_priv) >= 9)
5725                 DRM_DEBUG_DRIVER("Current CD clock rate: %d kHz, VCO: %d kHz, ref: %d kHz\n",
5726                                  dev_priv->cdclk_freq, dev_priv->cdclk_pll.vco,
5727                                  dev_priv->cdclk_pll.ref);
5728         else
5729                 DRM_DEBUG_DRIVER("Current CD clock rate: %d kHz\n",
5730                                  dev_priv->cdclk_freq);
5731
5732         /*
5733          * 9:0 CMBUS [sic] CDCLK frequency (cdfreq):
5734          * Programmng [sic] note: bit[9:2] should be programmed to the number
5735          * of cdclk that generates 4MHz reference clock freq which is used to
5736          * generate GMBus clock. This will vary with the cdclk freq.
5737          */
5738         if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
5739                 I915_WRITE(GMBUSFREQ_VLV, DIV_ROUND_UP(dev_priv->cdclk_freq, 1000));
5740 }
5741
5742 /* convert from kHz to .1 fixpoint MHz with -1MHz offset */
5743 static int skl_cdclk_decimal(int cdclk)
5744 {
5745         return DIV_ROUND_CLOSEST(cdclk - 1000, 500);
5746 }
5747
5748 static int bxt_de_pll_vco(struct drm_i915_private *dev_priv, int cdclk)
5749 {
5750         int ratio;
5751
5752         if (cdclk == dev_priv->cdclk_pll.ref)
5753                 return 0;
5754
5755         switch (cdclk) {
5756         default:
5757                 MISSING_CASE(cdclk);
5758         case 144000:
5759         case 288000:
5760         case 384000:
5761         case 576000:
5762                 ratio = 60;
5763                 break;
5764         case 624000:
5765                 ratio = 65;
5766                 break;
5767         }
5768
5769         return dev_priv->cdclk_pll.ref * ratio;
5770 }
5771
5772 static void bxt_de_pll_disable(struct drm_i915_private *dev_priv)
5773 {
5774         I915_WRITE(BXT_DE_PLL_ENABLE, 0);
5775
5776         /* Timeout 200us */
5777         if (intel_wait_for_register(dev_priv,
5778                                     BXT_DE_PLL_ENABLE, BXT_DE_PLL_LOCK, 0,
5779                                     1))
5780                 DRM_ERROR("timeout waiting for DE PLL unlock\n");
5781
5782         dev_priv->cdclk_pll.vco = 0;
5783 }
5784
5785 static void bxt_de_pll_enable(struct drm_i915_private *dev_priv, int vco)
5786 {
5787         int ratio = DIV_ROUND_CLOSEST(vco, dev_priv->cdclk_pll.ref);
5788         u32 val;
5789
5790         val = I915_READ(BXT_DE_PLL_CTL);
5791         val &= ~BXT_DE_PLL_RATIO_MASK;
5792         val |= BXT_DE_PLL_RATIO(ratio);
5793         I915_WRITE(BXT_DE_PLL_CTL, val);
5794
5795         I915_WRITE(BXT_DE_PLL_ENABLE, BXT_DE_PLL_PLL_ENABLE);
5796
5797         /* Timeout 200us */
5798         if (intel_wait_for_register(dev_priv,
5799                                     BXT_DE_PLL_ENABLE,
5800                                     BXT_DE_PLL_LOCK,
5801                                     BXT_DE_PLL_LOCK,
5802                                     1))
5803                 DRM_ERROR("timeout waiting for DE PLL lock\n");
5804
5805         dev_priv->cdclk_pll.vco = vco;
5806 }
5807
5808 static void bxt_set_cdclk(struct drm_i915_private *dev_priv, int cdclk)
5809 {
5810         u32 val, divider;
5811         int vco, ret;
5812
5813         vco = bxt_de_pll_vco(dev_priv, cdclk);
5814
5815         DRM_DEBUG_DRIVER("Changing CDCLK to %d kHz (VCO %d kHz)\n", cdclk, vco);
5816
5817         /* cdclk = vco / 2 / div{1,1.5,2,4} */
5818         switch (DIV_ROUND_CLOSEST(vco, cdclk)) {
5819         case 8:
5820                 divider = BXT_CDCLK_CD2X_DIV_SEL_4;
5821                 break;
5822         case 4:
5823                 divider = BXT_CDCLK_CD2X_DIV_SEL_2;
5824                 break;
5825         case 3:
5826                 divider = BXT_CDCLK_CD2X_DIV_SEL_1_5;
5827                 break;
5828         case 2:
5829                 divider = BXT_CDCLK_CD2X_DIV_SEL_1;
5830                 break;
5831         default:
5832                 WARN_ON(cdclk != dev_priv->cdclk_pll.ref);
5833                 WARN_ON(vco != 0);
5834
5835                 divider = BXT_CDCLK_CD2X_DIV_SEL_1;
5836                 break;
5837         }
5838
5839         /* Inform power controller of upcoming frequency change */
5840         mutex_lock(&dev_priv->rps.hw_lock);
5841         ret = sandybridge_pcode_write(dev_priv, HSW_PCODE_DE_WRITE_FREQ_REQ,
5842                                       0x80000000);
5843         mutex_unlock(&dev_priv->rps.hw_lock);
5844
5845         if (ret) {
5846                 DRM_ERROR("PCode CDCLK freq change notify failed (err %d, freq %d)\n",
5847                           ret, cdclk);
5848                 return;
5849         }
5850
5851         if (dev_priv->cdclk_pll.vco != 0 &&
5852             dev_priv->cdclk_pll.vco != vco)
5853                 bxt_de_pll_disable(dev_priv);
5854
5855         if (dev_priv->cdclk_pll.vco != vco)
5856                 bxt_de_pll_enable(dev_priv, vco);
5857
5858         val = divider | skl_cdclk_decimal(cdclk);
5859         /*
5860          * FIXME if only the cd2x divider needs changing, it could be done
5861          * without shutting off the pipe (if only one pipe is active).
5862          */
5863         val |= BXT_CDCLK_CD2X_PIPE_NONE;
5864         /*
5865          * Disable SSA Precharge when CD clock frequency < 500 MHz,
5866          * enable otherwise.
5867          */
5868         if (cdclk >= 500000)
5869                 val |= BXT_CDCLK_SSA_PRECHARGE_ENABLE;
5870         I915_WRITE(CDCLK_CTL, val);
5871
5872         mutex_lock(&dev_priv->rps.hw_lock);
5873         ret = sandybridge_pcode_write(dev_priv, HSW_PCODE_DE_WRITE_FREQ_REQ,
5874                                       DIV_ROUND_UP(cdclk, 25000));
5875         mutex_unlock(&dev_priv->rps.hw_lock);
5876
5877         if (ret) {
5878                 DRM_ERROR("PCode CDCLK freq set failed, (err %d, freq %d)\n",
5879                           ret, cdclk);
5880                 return;
5881         }
5882
5883         intel_update_cdclk(&dev_priv->drm);
5884 }
5885
5886 static void bxt_sanitize_cdclk(struct drm_i915_private *dev_priv)
5887 {
5888         u32 cdctl, expected;
5889
5890         intel_update_cdclk(&dev_priv->drm);
5891
5892         if (dev_priv->cdclk_pll.vco == 0 ||
5893             dev_priv->cdclk_freq == dev_priv->cdclk_pll.ref)
5894                 goto sanitize;
5895
5896         /* DPLL okay; verify the cdclock
5897          *
5898          * Some BIOS versions leave an incorrect decimal frequency value and
5899          * set reserved MBZ bits in CDCLK_CTL at least during exiting from S4,
5900          * so sanitize this register.
5901          */
5902         cdctl = I915_READ(CDCLK_CTL);
5903         /*
5904          * Let's ignore the pipe field, since BIOS could have configured the
5905          * dividers both synching to an active pipe, or asynchronously
5906          * (PIPE_NONE).
5907          */
5908         cdctl &= ~BXT_CDCLK_CD2X_PIPE_NONE;
5909
5910         expected = (cdctl & BXT_CDCLK_CD2X_DIV_SEL_MASK) |
5911                    skl_cdclk_decimal(dev_priv->cdclk_freq);
5912         /*
5913          * Disable SSA Precharge when CD clock frequency < 500 MHz,
5914          * enable otherwise.
5915          */
5916         if (dev_priv->cdclk_freq >= 500000)
5917                 expected |= BXT_CDCLK_SSA_PRECHARGE_ENABLE;
5918
5919         if (cdctl == expected)
5920                 /* All well; nothing to sanitize */
5921                 return;
5922
5923 sanitize:
5924         DRM_DEBUG_KMS("Sanitizing cdclk programmed by pre-os\n");
5925
5926         /* force cdclk programming */
5927         dev_priv->cdclk_freq = 0;
5928
5929         /* force full PLL disable + enable */
5930         dev_priv->cdclk_pll.vco = -1;
5931 }
5932
5933 void bxt_init_cdclk(struct drm_i915_private *dev_priv)
5934 {
5935         bxt_sanitize_cdclk(dev_priv);
5936
5937         if (dev_priv->cdclk_freq != 0 && dev_priv->cdclk_pll.vco != 0)
5938                 return;
5939
5940         /*
5941          * FIXME:
5942          * - The initial CDCLK needs to be read from VBT.
5943          *   Need to make this change after VBT has changes for BXT.
5944          */
5945         bxt_set_cdclk(dev_priv, bxt_calc_cdclk(0));
5946 }
5947
5948 void bxt_uninit_cdclk(struct drm_i915_private *dev_priv)
5949 {
5950         bxt_set_cdclk(dev_priv, dev_priv->cdclk_pll.ref);
5951 }
5952
5953 static int skl_calc_cdclk(int max_pixclk, int vco)
5954 {
5955         if (vco == 8640000) {
5956                 if (max_pixclk > 540000)
5957                         return 617143;
5958                 else if (max_pixclk > 432000)
5959                         return 540000;
5960                 else if (max_pixclk > 308571)
5961                         return 432000;
5962                 else
5963                         return 308571;
5964         } else {
5965                 if (max_pixclk > 540000)
5966                         return 675000;
5967                 else if (max_pixclk > 450000)
5968                         return 540000;
5969                 else if (max_pixclk > 337500)
5970                         return 450000;
5971                 else
5972                         return 337500;
5973         }
5974 }
5975
5976 static void
5977 skl_dpll0_update(struct drm_i915_private *dev_priv)
5978 {
5979         u32 val;
5980
5981         dev_priv->cdclk_pll.ref = 24000;
5982         dev_priv->cdclk_pll.vco = 0;
5983
5984         val = I915_READ(LCPLL1_CTL);
5985         if ((val & LCPLL_PLL_ENABLE) == 0)
5986                 return;
5987
5988         if (WARN_ON((val & LCPLL_PLL_LOCK) == 0))
5989                 return;
5990
5991         val = I915_READ(DPLL_CTRL1);
5992
5993         if (WARN_ON((val & (DPLL_CTRL1_HDMI_MODE(SKL_DPLL0) |
5994                             DPLL_CTRL1_SSC(SKL_DPLL0) |
5995                             DPLL_CTRL1_OVERRIDE(SKL_DPLL0))) !=
5996                     DPLL_CTRL1_OVERRIDE(SKL_DPLL0)))
5997                 return;
5998
5999         switch (val & DPLL_CTRL1_LINK_RATE_MASK(SKL_DPLL0)) {
6000         case DPLL_CTRL1_LINK_RATE(DPLL_CTRL1_LINK_RATE_810, SKL_DPLL0):
6001         case DPLL_CTRL1_LINK_RATE(DPLL_CTRL1_LINK_RATE_1350, SKL_DPLL0):
6002         case DPLL_CTRL1_LINK_RATE(DPLL_CTRL1_LINK_RATE_1620, SKL_DPLL0):
6003         case DPLL_CTRL1_LINK_RATE(DPLL_CTRL1_LINK_RATE_2700, SKL_DPLL0):
6004                 dev_priv->cdclk_pll.vco = 8100000;
6005                 break;
6006         case DPLL_CTRL1_LINK_RATE(DPLL_CTRL1_LINK_RATE_1080, SKL_DPLL0):
6007         case DPLL_CTRL1_LINK_RATE(DPLL_CTRL1_LINK_RATE_2160, SKL_DPLL0):
6008                 dev_priv->cdclk_pll.vco = 8640000;
6009                 break;
6010         default:
6011                 MISSING_CASE(val & DPLL_CTRL1_LINK_RATE_MASK(SKL_DPLL0));
6012                 break;
6013         }
6014 }
6015
6016 void skl_set_preferred_cdclk_vco(struct drm_i915_private *dev_priv, int vco)
6017 {
6018         bool changed = dev_priv->skl_preferred_vco_freq != vco;
6019
6020         dev_priv->skl_preferred_vco_freq = vco;
6021
6022         if (changed)
6023                 intel_update_max_cdclk(&dev_priv->drm);
6024 }
6025
6026 static void
6027 skl_dpll0_enable(struct drm_i915_private *dev_priv, int vco)
6028 {
6029         int min_cdclk = skl_calc_cdclk(0, vco);
6030         u32 val;
6031
6032         WARN_ON(vco != 8100000 && vco != 8640000);
6033
6034         /* select the minimum CDCLK before enabling DPLL 0 */
6035         val = CDCLK_FREQ_337_308 | skl_cdclk_decimal(min_cdclk);
6036         I915_WRITE(CDCLK_CTL, val);
6037         POSTING_READ(CDCLK_CTL);
6038
6039         /*
6040          * We always enable DPLL0 with the lowest link rate possible, but still
6041          * taking into account the VCO required to operate the eDP panel at the
6042          * desired frequency. The usual DP link rates operate with a VCO of
6043          * 8100 while the eDP 1.4 alternate link rates need a VCO of 8640.
6044          * The modeset code is responsible for the selection of the exact link
6045          * rate later on, with the constraint of choosing a frequency that
6046          * works with vco.
6047          */
6048         val = I915_READ(DPLL_CTRL1);
6049
6050         val &= ~(DPLL_CTRL1_HDMI_MODE(SKL_DPLL0) | DPLL_CTRL1_SSC(SKL_DPLL0) |
6051                  DPLL_CTRL1_LINK_RATE_MASK(SKL_DPLL0));
6052         val |= DPLL_CTRL1_OVERRIDE(SKL_DPLL0);
6053         if (vco == 8640000)
6054                 val |= DPLL_CTRL1_LINK_RATE(DPLL_CTRL1_LINK_RATE_1080,
6055                                             SKL_DPLL0);
6056         else
6057                 val |= DPLL_CTRL1_LINK_RATE(DPLL_CTRL1_LINK_RATE_810,
6058                                             SKL_DPLL0);
6059
6060         I915_WRITE(DPLL_CTRL1, val);
6061         POSTING_READ(DPLL_CTRL1);
6062
6063         I915_WRITE(LCPLL1_CTL, I915_READ(LCPLL1_CTL) | LCPLL_PLL_ENABLE);
6064
6065         if (intel_wait_for_register(dev_priv,
6066                                     LCPLL1_CTL, LCPLL_PLL_LOCK, LCPLL_PLL_LOCK,
6067                                     5))
6068                 DRM_ERROR("DPLL0 not locked\n");
6069
6070         dev_priv->cdclk_pll.vco = vco;
6071
6072         /* We'll want to keep using the current vco from now on. */
6073         skl_set_preferred_cdclk_vco(dev_priv, vco);
6074 }
6075
6076 static void
6077 skl_dpll0_disable(struct drm_i915_private *dev_priv)
6078 {
6079         I915_WRITE(LCPLL1_CTL, I915_READ(LCPLL1_CTL) & ~LCPLL_PLL_ENABLE);
6080         if (intel_wait_for_register(dev_priv,
6081                                    LCPLL1_CTL, LCPLL_PLL_LOCK, 0,
6082                                    1))
6083                 DRM_ERROR("Couldn't disable DPLL0\n");
6084
6085         dev_priv->cdclk_pll.vco = 0;
6086 }
6087
6088 static bool skl_cdclk_pcu_ready(struct drm_i915_private *dev_priv)
6089 {
6090         int ret;
6091         u32 val;
6092
6093         /* inform PCU we want to change CDCLK */
6094         val = SKL_CDCLK_PREPARE_FOR_CHANGE;
6095         mutex_lock(&dev_priv->rps.hw_lock);
6096         ret = sandybridge_pcode_read(dev_priv, SKL_PCODE_CDCLK_CONTROL, &val);
6097         mutex_unlock(&dev_priv->rps.hw_lock);
6098
6099         return ret == 0 && (val & SKL_CDCLK_READY_FOR_CHANGE);
6100 }
6101
6102 static bool skl_cdclk_wait_for_pcu_ready(struct drm_i915_private *dev_priv)
6103 {
6104         return _wait_for(skl_cdclk_pcu_ready(dev_priv), 3000, 10) == 0;
6105 }
6106
6107 static void skl_set_cdclk(struct drm_i915_private *dev_priv, int cdclk, int vco)
6108 {
6109         struct drm_device *dev = &dev_priv->drm;
6110         u32 freq_select, pcu_ack;
6111
6112         WARN_ON((cdclk == 24000) != (vco == 0));
6113
6114         DRM_DEBUG_DRIVER("Changing CDCLK to %d kHz (VCO %d kHz)\n", cdclk, vco);
6115
6116         if (!skl_cdclk_wait_for_pcu_ready(dev_priv)) {
6117                 DRM_ERROR("failed to inform PCU about cdclk change\n");
6118                 return;
6119         }
6120
6121         /* set CDCLK_CTL */
6122         switch (cdclk) {
6123         case 450000:
6124         case 432000:
6125                 freq_select = CDCLK_FREQ_450_432;
6126                 pcu_ack = 1;
6127                 break;
6128         case 540000:
6129                 freq_select = CDCLK_FREQ_540;
6130                 pcu_ack = 2;
6131                 break;
6132         case 308571:
6133         case 337500:
6134         default:
6135                 freq_select = CDCLK_FREQ_337_308;
6136                 pcu_ack = 0;
6137                 break;
6138         case 617143:
6139         case 675000:
6140                 freq_select = CDCLK_FREQ_675_617;
6141                 pcu_ack = 3;
6142                 break;
6143         }
6144
6145         if (dev_priv->cdclk_pll.vco != 0 &&
6146             dev_priv->cdclk_pll.vco != vco)
6147                 skl_dpll0_disable(dev_priv);
6148
6149         if (dev_priv->cdclk_pll.vco != vco)
6150                 skl_dpll0_enable(dev_priv, vco);
6151
6152         I915_WRITE(CDCLK_CTL, freq_select | skl_cdclk_decimal(cdclk));
6153         POSTING_READ(CDCLK_CTL);
6154
6155         /* inform PCU of the change */
6156         mutex_lock(&dev_priv->rps.hw_lock);
6157         sandybridge_pcode_write(dev_priv, SKL_PCODE_CDCLK_CONTROL, pcu_ack);
6158         mutex_unlock(&dev_priv->rps.hw_lock);
6159
6160         intel_update_cdclk(dev);
6161 }
6162
6163 static void skl_sanitize_cdclk(struct drm_i915_private *dev_priv);
6164
6165 void skl_uninit_cdclk(struct drm_i915_private *dev_priv)
6166 {
6167         skl_set_cdclk(dev_priv, dev_priv->cdclk_pll.ref, 0);
6168 }
6169
6170 void skl_init_cdclk(struct drm_i915_private *dev_priv)
6171 {
6172         int cdclk, vco;
6173
6174         skl_sanitize_cdclk(dev_priv);
6175
6176         if (dev_priv->cdclk_freq != 0 && dev_priv->cdclk_pll.vco != 0) {
6177                 /*
6178                  * Use the current vco as our initial
6179                  * guess as to what the preferred vco is.
6180                  */
6181                 if (dev_priv->skl_preferred_vco_freq == 0)
6182                         skl_set_preferred_cdclk_vco(dev_priv,
6183                                                     dev_priv->cdclk_pll.vco);
6184                 return;
6185         }
6186
6187         vco = dev_priv->skl_preferred_vco_freq;
6188         if (vco == 0)
6189                 vco = 8100000;
6190         cdclk = skl_calc_cdclk(0, vco);
6191
6192         skl_set_cdclk(dev_priv, cdclk, vco);
6193 }
6194
6195 static void skl_sanitize_cdclk(struct drm_i915_private *dev_priv)
6196 {
6197         uint32_t cdctl, expected;
6198
6199         /*
6200          * check if the pre-os intialized the display
6201          * There is SWF18 scratchpad register defined which is set by the
6202          * pre-os which can be used by the OS drivers to check the status
6203          */
6204         if ((I915_READ(SWF_ILK(0x18)) & 0x00FFFFFF) == 0)
6205                 goto sanitize;
6206
6207         intel_update_cdclk(&dev_priv->drm);
6208         /* Is PLL enabled and locked ? */
6209         if (dev_priv->cdclk_pll.vco == 0 ||
6210             dev_priv->cdclk_freq == dev_priv->cdclk_pll.ref)
6211                 goto sanitize;
6212
6213         /* DPLL okay; verify the cdclock
6214          *
6215          * Noticed in some instances that the freq selection is correct but
6216          * decimal part is programmed wrong from BIOS where pre-os does not
6217          * enable display. Verify the same as well.
6218          */
6219         cdctl = I915_READ(CDCLK_CTL);
6220         expected = (cdctl & CDCLK_FREQ_SEL_MASK) |
6221                 skl_cdclk_decimal(dev_priv->cdclk_freq);
6222         if (cdctl == expected)
6223                 /* All well; nothing to sanitize */
6224                 return;
6225
6226 sanitize:
6227         DRM_DEBUG_KMS("Sanitizing cdclk programmed by pre-os\n");
6228
6229         /* force cdclk programming */
6230         dev_priv->cdclk_freq = 0;
6231         /* force full PLL disable + enable */
6232         dev_priv->cdclk_pll.vco = -1;
6233 }
6234
6235 /* Adjust CDclk dividers to allow high res or save power if possible */
6236 static void valleyview_set_cdclk(struct drm_device *dev, int cdclk)
6237 {
6238         struct drm_i915_private *dev_priv = to_i915(dev);
6239         u32 val, cmd;
6240
6241         WARN_ON(dev_priv->display.get_display_clock_speed(dev)
6242                                         != dev_priv->cdclk_freq);
6243
6244         if (cdclk >= 320000) /* jump to highest voltage for 400MHz too */
6245                 cmd = 2;
6246         else if (cdclk == 266667)
6247                 cmd = 1;
6248         else
6249                 cmd = 0;
6250
6251         mutex_lock(&dev_priv->rps.hw_lock);
6252         val = vlv_punit_read(dev_priv, PUNIT_REG_DSPFREQ);
6253         val &= ~DSPFREQGUAR_MASK;
6254         val |= (cmd << DSPFREQGUAR_SHIFT);
6255         vlv_punit_write(dev_priv, PUNIT_REG_DSPFREQ, val);
6256         if (wait_for((vlv_punit_read(dev_priv, PUNIT_REG_DSPFREQ) &
6257                       DSPFREQSTAT_MASK) == (cmd << DSPFREQSTAT_SHIFT),
6258                      50)) {
6259                 DRM_ERROR("timed out waiting for CDclk change\n");
6260         }
6261         mutex_unlock(&dev_priv->rps.hw_lock);
6262
6263         mutex_lock(&dev_priv->sb_lock);
6264
6265         if (cdclk == 400000) {
6266                 u32 divider;
6267
6268                 divider = DIV_ROUND_CLOSEST(dev_priv->hpll_freq << 1, cdclk) - 1;
6269
6270                 /* adjust cdclk divider */
6271                 val = vlv_cck_read(dev_priv, CCK_DISPLAY_CLOCK_CONTROL);
6272                 val &= ~CCK_FREQUENCY_VALUES;
6273                 val |= divider;
6274                 vlv_cck_write(dev_priv, CCK_DISPLAY_CLOCK_CONTROL, val);
6275
6276                 if (wait_for((vlv_cck_read(dev_priv, CCK_DISPLAY_CLOCK_CONTROL) &
6277                               CCK_FREQUENCY_STATUS) == (divider << CCK_FREQUENCY_STATUS_SHIFT),
6278                              50))
6279                         DRM_ERROR("timed out waiting for CDclk change\n");
6280         }
6281
6282         /* adjust self-refresh exit latency value */
6283         val = vlv_bunit_read(dev_priv, BUNIT_REG_BISOC);
6284         val &= ~0x7f;
6285
6286         /*
6287          * For high bandwidth configs, we set a higher latency in the bunit
6288          * so that the core display fetch happens in time to avoid underruns.
6289          */
6290         if (cdclk == 400000)
6291                 val |= 4500 / 250; /* 4.5 usec */
6292         else
6293                 val |= 3000 / 250; /* 3.0 usec */
6294         vlv_bunit_write(dev_priv, BUNIT_REG_BISOC, val);
6295
6296         mutex_unlock(&dev_priv->sb_lock);
6297
6298         intel_update_cdclk(dev);
6299 }
6300
6301 static void cherryview_set_cdclk(struct drm_device *dev, int cdclk)
6302 {
6303         struct drm_i915_private *dev_priv = to_i915(dev);
6304         u32 val, cmd;
6305
6306         WARN_ON(dev_priv->display.get_display_clock_speed(dev)
6307                                                 != dev_priv->cdclk_freq);
6308
6309         switch (cdclk) {
6310         case 333333:
6311         case 320000:
6312         case 266667:
6313         case 200000:
6314                 break;
6315         default:
6316                 MISSING_CASE(cdclk);
6317                 return;
6318         }
6319
6320         /*
6321          * Specs are full of misinformation, but testing on actual
6322          * hardware has shown that we just need to write the desired
6323          * CCK divider into the Punit register.
6324          */
6325         cmd = DIV_ROUND_CLOSEST(dev_priv->hpll_freq << 1, cdclk) - 1;
6326
6327         mutex_lock(&dev_priv->rps.hw_lock);
6328         val = vlv_punit_read(dev_priv, PUNIT_REG_DSPFREQ);
6329         val &= ~DSPFREQGUAR_MASK_CHV;
6330         val |= (cmd << DSPFREQGUAR_SHIFT_CHV);
6331         vlv_punit_write(dev_priv, PUNIT_REG_DSPFREQ, val);
6332         if (wait_for((vlv_punit_read(dev_priv, PUNIT_REG_DSPFREQ) &
6333                       DSPFREQSTAT_MASK_CHV) == (cmd << DSPFREQSTAT_SHIFT_CHV),
6334                      50)) {
6335                 DRM_ERROR("timed out waiting for CDclk change\n");
6336         }
6337         mutex_unlock(&dev_priv->rps.hw_lock);
6338
6339         intel_update_cdclk(dev);
6340 }
6341
6342 static int valleyview_calc_cdclk(struct drm_i915_private *dev_priv,
6343                                  int max_pixclk)
6344 {
6345         int freq_320 = (dev_priv->hpll_freq <<  1) % 320000 != 0 ? 333333 : 320000;
6346         int limit = IS_CHERRYVIEW(dev_priv) ? 95 : 90;
6347
6348         /*
6349          * Really only a few cases to deal with, as only 4 CDclks are supported:
6350          *   200MHz
6351          *   267MHz
6352          *   320/333MHz (depends on HPLL freq)
6353          *   400MHz (VLV only)
6354          * So we check to see whether we're above 90% (VLV) or 95% (CHV)
6355          * of the lower bin and adjust if needed.
6356          *
6357          * We seem to get an unstable or solid color picture at 200MHz.
6358          * Not sure what's wrong. For now use 200MHz only when all pipes
6359          * are off.
6360          */
6361         if (!IS_CHERRYVIEW(dev_priv) &&
6362             max_pixclk > freq_320*limit/100)
6363                 return 400000;
6364         else if (max_pixclk > 266667*limit/100)
6365                 return freq_320;
6366         else if (max_pixclk > 0)
6367                 return 266667;
6368         else
6369                 return 200000;
6370 }
6371
6372 static int bxt_calc_cdclk(int max_pixclk)
6373 {
6374         if (max_pixclk > 576000)
6375                 return 624000;
6376         else if (max_pixclk > 384000)
6377                 return 576000;
6378         else if (max_pixclk > 288000)
6379                 return 384000;
6380         else if (max_pixclk > 144000)
6381                 return 288000;
6382         else
6383                 return 144000;
6384 }
6385
6386 /* Compute the max pixel clock for new configuration. */
6387 static int intel_mode_max_pixclk(struct drm_device *dev,
6388                                  struct drm_atomic_state *state)
6389 {
6390         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
6391         struct drm_i915_private *dev_priv = to_i915(dev);
6392         struct drm_crtc *crtc;
6393         struct drm_crtc_state *crtc_state;
6394         unsigned max_pixclk = 0, i;
6395         enum pipe pipe;
6396
6397         memcpy(intel_state->min_pixclk, dev_priv->min_pixclk,
6398                sizeof(intel_state->min_pixclk));
6399
6400         for_each_crtc_in_state(state, crtc, crtc_state, i) {
6401                 int pixclk = 0;
6402
6403                 if (crtc_state->enable)
6404                         pixclk = crtc_state->adjusted_mode.crtc_clock;
6405
6406                 intel_state->min_pixclk[i] = pixclk;
6407         }
6408
6409         for_each_pipe(dev_priv, pipe)
6410                 max_pixclk = max(intel_state->min_pixclk[pipe], max_pixclk);
6411
6412         return max_pixclk;
6413 }
6414
6415 static int valleyview_modeset_calc_cdclk(struct drm_atomic_state *state)
6416 {
6417         struct drm_device *dev = state->dev;
6418         struct drm_i915_private *dev_priv = to_i915(dev);
6419         int max_pixclk = intel_mode_max_pixclk(dev, state);
6420         struct intel_atomic_state *intel_state =
6421                 to_intel_atomic_state(state);
6422
6423         intel_state->cdclk = intel_state->dev_cdclk =
6424                 valleyview_calc_cdclk(dev_priv, max_pixclk);
6425
6426         if (!intel_state->active_crtcs)
6427                 intel_state->dev_cdclk = valleyview_calc_cdclk(dev_priv, 0);
6428
6429         return 0;
6430 }
6431
6432 static int bxt_modeset_calc_cdclk(struct drm_atomic_state *state)
6433 {
6434         int max_pixclk = ilk_max_pixel_rate(state);
6435         struct intel_atomic_state *intel_state =
6436                 to_intel_atomic_state(state);
6437
6438         intel_state->cdclk = intel_state->dev_cdclk =
6439                 bxt_calc_cdclk(max_pixclk);
6440
6441         if (!intel_state->active_crtcs)
6442                 intel_state->dev_cdclk = bxt_calc_cdclk(0);
6443
6444         return 0;
6445 }
6446
6447 static void vlv_program_pfi_credits(struct drm_i915_private *dev_priv)
6448 {
6449         unsigned int credits, default_credits;
6450
6451         if (IS_CHERRYVIEW(dev_priv))
6452                 default_credits = PFI_CREDIT(12);
6453         else
6454                 default_credits = PFI_CREDIT(8);
6455
6456         if (dev_priv->cdclk_freq >= dev_priv->czclk_freq) {
6457                 /* CHV suggested value is 31 or 63 */
6458                 if (IS_CHERRYVIEW(dev_priv))
6459                         credits = PFI_CREDIT_63;
6460                 else
6461                         credits = PFI_CREDIT(15);
6462         } else {
6463                 credits = default_credits;
6464         }
6465
6466         /*
6467          * WA - write default credits before re-programming
6468          * FIXME: should we also set the resend bit here?
6469          */
6470         I915_WRITE(GCI_CONTROL, VGA_FAST_MODE_DISABLE |
6471                    default_credits);
6472
6473         I915_WRITE(GCI_CONTROL, VGA_FAST_MODE_DISABLE |
6474                    credits | PFI_CREDIT_RESEND);
6475
6476         /*
6477          * FIXME is this guaranteed to clear
6478          * immediately or should we poll for it?
6479          */
6480         WARN_ON(I915_READ(GCI_CONTROL) & PFI_CREDIT_RESEND);
6481 }
6482
6483 static void valleyview_modeset_commit_cdclk(struct drm_atomic_state *old_state)
6484 {
6485         struct drm_device *dev = old_state->dev;
6486         struct drm_i915_private *dev_priv = to_i915(dev);
6487         struct intel_atomic_state *old_intel_state =
6488                 to_intel_atomic_state(old_state);
6489         unsigned req_cdclk = old_intel_state->dev_cdclk;
6490
6491         /*
6492          * FIXME: We can end up here with all power domains off, yet
6493          * with a CDCLK frequency other than the minimum. To account
6494          * for this take the PIPE-A power domain, which covers the HW
6495          * blocks needed for the following programming. This can be
6496          * removed once it's guaranteed that we get here either with
6497          * the minimum CDCLK set, or the required power domains
6498          * enabled.
6499          */
6500         intel_display_power_get(dev_priv, POWER_DOMAIN_PIPE_A);
6501
6502         if (IS_CHERRYVIEW(dev))
6503                 cherryview_set_cdclk(dev, req_cdclk);
6504         else
6505                 valleyview_set_cdclk(dev, req_cdclk);
6506
6507         vlv_program_pfi_credits(dev_priv);
6508
6509         intel_display_power_put(dev_priv, POWER_DOMAIN_PIPE_A);
6510 }
6511
6512 static void valleyview_crtc_enable(struct drm_crtc *crtc)
6513 {
6514         struct drm_device *dev = crtc->dev;
6515         struct drm_i915_private *dev_priv = to_i915(dev);
6516         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
6517         struct intel_encoder *encoder;
6518         struct intel_crtc_state *pipe_config =
6519                 to_intel_crtc_state(crtc->state);
6520         int pipe = intel_crtc->pipe;
6521
6522         if (WARN_ON(intel_crtc->active))
6523                 return;
6524
6525         if (intel_crtc_has_dp_encoder(intel_crtc->config))
6526                 intel_dp_set_m_n(intel_crtc, M1_N1);
6527
6528         intel_set_pipe_timings(intel_crtc);
6529         intel_set_pipe_src_size(intel_crtc);
6530
6531         if (IS_CHERRYVIEW(dev) && pipe == PIPE_B) {
6532                 struct drm_i915_private *dev_priv = to_i915(dev);
6533
6534                 I915_WRITE(CHV_BLEND(pipe), CHV_BLEND_LEGACY);
6535                 I915_WRITE(CHV_CANVAS(pipe), 0);
6536         }
6537
6538         i9xx_set_pipeconf(intel_crtc);
6539
6540         intel_crtc->active = true;
6541
6542         intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
6543
6544         for_each_encoder_on_crtc(dev, crtc, encoder)
6545                 if (encoder->pre_pll_enable)
6546                         encoder->pre_pll_enable(encoder);
6547
6548         if (IS_CHERRYVIEW(dev)) {
6549                 chv_prepare_pll(intel_crtc, intel_crtc->config);
6550                 chv_enable_pll(intel_crtc, intel_crtc->config);
6551         } else {
6552                 vlv_prepare_pll(intel_crtc, intel_crtc->config);
6553                 vlv_enable_pll(intel_crtc, intel_crtc->config);
6554         }
6555
6556         for_each_encoder_on_crtc(dev, crtc, encoder)
6557                 if (encoder->pre_enable)
6558                         encoder->pre_enable(encoder);
6559
6560         i9xx_pfit_enable(intel_crtc);
6561
6562         intel_color_load_luts(&pipe_config->base);
6563
6564         intel_update_watermarks(crtc);
6565         intel_enable_pipe(intel_crtc);
6566
6567         assert_vblank_disabled(crtc);
6568         drm_crtc_vblank_on(crtc);
6569
6570         for_each_encoder_on_crtc(dev, crtc, encoder)
6571                 encoder->enable(encoder);
6572 }
6573
6574 static void i9xx_set_pll_dividers(struct intel_crtc *crtc)
6575 {
6576         struct drm_device *dev = crtc->base.dev;
6577         struct drm_i915_private *dev_priv = to_i915(dev);
6578
6579         I915_WRITE(FP0(crtc->pipe), crtc->config->dpll_hw_state.fp0);
6580         I915_WRITE(FP1(crtc->pipe), crtc->config->dpll_hw_state.fp1);
6581 }
6582
6583 static void i9xx_crtc_enable(struct drm_crtc *crtc)
6584 {
6585         struct drm_device *dev = crtc->dev;
6586         struct drm_i915_private *dev_priv = to_i915(dev);
6587         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
6588         struct intel_encoder *encoder;
6589         struct intel_crtc_state *pipe_config =
6590                 to_intel_crtc_state(crtc->state);
6591         enum pipe pipe = intel_crtc->pipe;
6592
6593         if (WARN_ON(intel_crtc->active))
6594                 return;
6595
6596         i9xx_set_pll_dividers(intel_crtc);
6597
6598         if (intel_crtc_has_dp_encoder(intel_crtc->config))
6599                 intel_dp_set_m_n(intel_crtc, M1_N1);
6600
6601         intel_set_pipe_timings(intel_crtc);
6602         intel_set_pipe_src_size(intel_crtc);
6603
6604         i9xx_set_pipeconf(intel_crtc);
6605
6606         intel_crtc->active = true;
6607
6608         if (!IS_GEN2(dev))
6609                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
6610
6611         for_each_encoder_on_crtc(dev, crtc, encoder)
6612                 if (encoder->pre_enable)
6613                         encoder->pre_enable(encoder);
6614
6615         i9xx_enable_pll(intel_crtc);
6616
6617         i9xx_pfit_enable(intel_crtc);
6618
6619         intel_color_load_luts(&pipe_config->base);
6620
6621         intel_update_watermarks(crtc);
6622         intel_enable_pipe(intel_crtc);
6623
6624         assert_vblank_disabled(crtc);
6625         drm_crtc_vblank_on(crtc);
6626
6627         for_each_encoder_on_crtc(dev, crtc, encoder)
6628                 encoder->enable(encoder);
6629 }
6630
6631 static void i9xx_pfit_disable(struct intel_crtc *crtc)
6632 {
6633         struct drm_device *dev = crtc->base.dev;
6634         struct drm_i915_private *dev_priv = to_i915(dev);
6635
6636         if (!crtc->config->gmch_pfit.control)
6637                 return;
6638
6639         assert_pipe_disabled(dev_priv, crtc->pipe);
6640
6641         DRM_DEBUG_DRIVER("disabling pfit, current: 0x%08x\n",
6642                          I915_READ(PFIT_CONTROL));
6643         I915_WRITE(PFIT_CONTROL, 0);
6644 }
6645
6646 static void i9xx_crtc_disable(struct drm_crtc *crtc)
6647 {
6648         struct drm_device *dev = crtc->dev;
6649         struct drm_i915_private *dev_priv = to_i915(dev);
6650         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
6651         struct intel_encoder *encoder;
6652         int pipe = intel_crtc->pipe;
6653
6654         /*
6655          * On gen2 planes are double buffered but the pipe isn't, so we must
6656          * wait for planes to fully turn off before disabling the pipe.
6657          */
6658         if (IS_GEN2(dev))
6659                 intel_wait_for_vblank(dev, pipe);
6660
6661         for_each_encoder_on_crtc(dev, crtc, encoder)
6662                 encoder->disable(encoder);
6663
6664         drm_crtc_vblank_off(crtc);
6665         assert_vblank_disabled(crtc);
6666
6667         intel_disable_pipe(intel_crtc);
6668
6669         i9xx_pfit_disable(intel_crtc);
6670
6671         for_each_encoder_on_crtc(dev, crtc, encoder)
6672                 if (encoder->post_disable)
6673                         encoder->post_disable(encoder);
6674
6675         if (!intel_crtc_has_type(intel_crtc->config, INTEL_OUTPUT_DSI)) {
6676                 if (IS_CHERRYVIEW(dev))
6677                         chv_disable_pll(dev_priv, pipe);
6678                 else if (IS_VALLEYVIEW(dev))
6679                         vlv_disable_pll(dev_priv, pipe);
6680                 else
6681                         i9xx_disable_pll(intel_crtc);
6682         }
6683
6684         for_each_encoder_on_crtc(dev, crtc, encoder)
6685                 if (encoder->post_pll_disable)
6686                         encoder->post_pll_disable(encoder);
6687
6688         if (!IS_GEN2(dev))
6689                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
6690 }
6691
6692 static void intel_crtc_disable_noatomic(struct drm_crtc *crtc)
6693 {
6694         struct intel_encoder *encoder;
6695         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
6696         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
6697         enum intel_display_power_domain domain;
6698         unsigned long domains;
6699
6700         if (!intel_crtc->active)
6701                 return;
6702
6703         if (to_intel_plane_state(crtc->primary->state)->visible) {
6704                 WARN_ON(intel_crtc->flip_work);
6705
6706                 intel_pre_disable_primary_noatomic(crtc);
6707
6708                 intel_crtc_disable_planes(crtc, 1 << drm_plane_index(crtc->primary));
6709                 to_intel_plane_state(crtc->primary->state)->visible = false;
6710         }
6711
6712         dev_priv->display.crtc_disable(crtc);
6713
6714         DRM_DEBUG_KMS("[CRTC:%d:%s] hw state adjusted, was enabled, now disabled\n",
6715                       crtc->base.id, crtc->name);
6716
6717         WARN_ON(drm_atomic_set_mode_for_crtc(crtc->state, NULL) < 0);
6718         crtc->state->active = false;
6719         intel_crtc->active = false;
6720         crtc->enabled = false;
6721         crtc->state->connector_mask = 0;
6722         crtc->state->encoder_mask = 0;
6723
6724         for_each_encoder_on_crtc(crtc->dev, crtc, encoder)
6725                 encoder->base.crtc = NULL;
6726
6727         intel_fbc_disable(intel_crtc);
6728         intel_update_watermarks(crtc);
6729         intel_disable_shared_dpll(intel_crtc);
6730
6731         domains = intel_crtc->enabled_power_domains;
6732         for_each_power_domain(domain, domains)
6733                 intel_display_power_put(dev_priv, domain);
6734         intel_crtc->enabled_power_domains = 0;
6735
6736         dev_priv->active_crtcs &= ~(1 << intel_crtc->pipe);
6737         dev_priv->min_pixclk[intel_crtc->pipe] = 0;
6738 }
6739
6740 /*
6741  * turn all crtc's off, but do not adjust state
6742  * This has to be paired with a call to intel_modeset_setup_hw_state.
6743  */
6744 int intel_display_suspend(struct drm_device *dev)
6745 {
6746         struct drm_i915_private *dev_priv = to_i915(dev);
6747         struct drm_atomic_state *state;
6748         int ret;
6749
6750         state = drm_atomic_helper_suspend(dev);
6751         ret = PTR_ERR_OR_ZERO(state);
6752         if (ret)
6753                 DRM_ERROR("Suspending crtc's failed with %i\n", ret);
6754         else
6755                 dev_priv->modeset_restore_state = state;
6756         return ret;
6757 }
6758
6759 void intel_encoder_destroy(struct drm_encoder *encoder)
6760 {
6761         struct intel_encoder *intel_encoder = to_intel_encoder(encoder);
6762
6763         drm_encoder_cleanup(encoder);
6764         kfree(intel_encoder);
6765 }
6766
6767 /* Cross check the actual hw state with our own modeset state tracking (and it's
6768  * internal consistency). */
6769 static void intel_connector_verify_state(struct intel_connector *connector)
6770 {
6771         struct drm_crtc *crtc = connector->base.state->crtc;
6772
6773         DRM_DEBUG_KMS("[CONNECTOR:%d:%s]\n",
6774                       connector->base.base.id,
6775                       connector->base.name);
6776
6777         if (connector->get_hw_state(connector)) {
6778                 struct intel_encoder *encoder = connector->encoder;
6779                 struct drm_connector_state *conn_state = connector->base.state;
6780
6781                 I915_STATE_WARN(!crtc,
6782                          "connector enabled without attached crtc\n");
6783
6784                 if (!crtc)
6785                         return;
6786
6787                 I915_STATE_WARN(!crtc->state->active,
6788                       "connector is active, but attached crtc isn't\n");
6789
6790                 if (!encoder || encoder->type == INTEL_OUTPUT_DP_MST)
6791                         return;
6792
6793                 I915_STATE_WARN(conn_state->best_encoder != &encoder->base,
6794                         "atomic encoder doesn't match attached encoder\n");
6795
6796                 I915_STATE_WARN(conn_state->crtc != encoder->base.crtc,
6797                         "attached encoder crtc differs from connector crtc\n");
6798         } else {
6799                 I915_STATE_WARN(crtc && crtc->state->active,
6800                         "attached crtc is active, but connector isn't\n");
6801                 I915_STATE_WARN(!crtc && connector->base.state->best_encoder,
6802                         "best encoder set without crtc!\n");
6803         }
6804 }
6805
6806 int intel_connector_init(struct intel_connector *connector)
6807 {
6808         drm_atomic_helper_connector_reset(&connector->base);
6809
6810         if (!connector->base.state)
6811                 return -ENOMEM;
6812
6813         return 0;
6814 }
6815
6816 struct intel_connector *intel_connector_alloc(void)
6817 {
6818         struct intel_connector *connector;
6819
6820         connector = kzalloc(sizeof *connector, GFP_KERNEL);
6821         if (!connector)
6822                 return NULL;
6823
6824         if (intel_connector_init(connector) < 0) {
6825                 kfree(connector);
6826                 return NULL;
6827         }
6828
6829         return connector;
6830 }
6831
6832 /* Simple connector->get_hw_state implementation for encoders that support only
6833  * one connector and no cloning and hence the encoder state determines the state
6834  * of the connector. */
6835 bool intel_connector_get_hw_state(struct intel_connector *connector)
6836 {
6837         enum pipe pipe = 0;
6838         struct intel_encoder *encoder = connector->encoder;
6839
6840         return encoder->get_hw_state(encoder, &pipe);
6841 }
6842
6843 static int pipe_required_fdi_lanes(struct intel_crtc_state *crtc_state)
6844 {
6845         if (crtc_state->base.enable && crtc_state->has_pch_encoder)
6846                 return crtc_state->fdi_lanes;
6847
6848         return 0;
6849 }
6850
6851 static int ironlake_check_fdi_lanes(struct drm_device *dev, enum pipe pipe,
6852                                      struct intel_crtc_state *pipe_config)
6853 {
6854         struct drm_atomic_state *state = pipe_config->base.state;
6855         struct intel_crtc *other_crtc;
6856         struct intel_crtc_state *other_crtc_state;
6857
6858         DRM_DEBUG_KMS("checking fdi config on pipe %c, lanes %i\n",
6859                       pipe_name(pipe), pipe_config->fdi_lanes);
6860         if (pipe_config->fdi_lanes > 4) {
6861                 DRM_DEBUG_KMS("invalid fdi lane config on pipe %c: %i lanes\n",
6862                               pipe_name(pipe), pipe_config->fdi_lanes);
6863                 return -EINVAL;
6864         }
6865
6866         if (IS_HASWELL(dev) || IS_BROADWELL(dev)) {
6867                 if (pipe_config->fdi_lanes > 2) {
6868                         DRM_DEBUG_KMS("only 2 lanes on haswell, required: %i lanes\n",
6869                                       pipe_config->fdi_lanes);
6870                         return -EINVAL;
6871                 } else {
6872                         return 0;
6873                 }
6874         }
6875
6876         if (INTEL_INFO(dev)->num_pipes == 2)
6877                 return 0;
6878
6879         /* Ivybridge 3 pipe is really complicated */
6880         switch (pipe) {
6881         case PIPE_A:
6882                 return 0;
6883         case PIPE_B:
6884                 if (pipe_config->fdi_lanes <= 2)
6885                         return 0;
6886
6887                 other_crtc = to_intel_crtc(intel_get_crtc_for_pipe(dev, PIPE_C));
6888                 other_crtc_state =
6889                         intel_atomic_get_crtc_state(state, other_crtc);
6890                 if (IS_ERR(other_crtc_state))
6891                         return PTR_ERR(other_crtc_state);
6892
6893                 if (pipe_required_fdi_lanes(other_crtc_state) > 0) {
6894                         DRM_DEBUG_KMS("invalid shared fdi lane config on pipe %c: %i lanes\n",
6895                                       pipe_name(pipe), pipe_config->fdi_lanes);
6896                         return -EINVAL;
6897                 }
6898                 return 0;
6899         case PIPE_C:
6900                 if (pipe_config->fdi_lanes > 2) {
6901                         DRM_DEBUG_KMS("only 2 lanes on pipe %c: required %i lanes\n",
6902                                       pipe_name(pipe), pipe_config->fdi_lanes);
6903                         return -EINVAL;
6904                 }
6905
6906                 other_crtc = to_intel_crtc(intel_get_crtc_for_pipe(dev, PIPE_B));
6907                 other_crtc_state =
6908                         intel_atomic_get_crtc_state(state, other_crtc);
6909                 if (IS_ERR(other_crtc_state))
6910                         return PTR_ERR(other_crtc_state);
6911
6912                 if (pipe_required_fdi_lanes(other_crtc_state) > 2) {
6913                         DRM_DEBUG_KMS("fdi link B uses too many lanes to enable link C\n");
6914                         return -EINVAL;
6915                 }
6916                 return 0;
6917         default:
6918                 BUG();
6919         }
6920 }
6921
6922 #define RETRY 1
6923 static int ironlake_fdi_compute_config(struct intel_crtc *intel_crtc,
6924                                        struct intel_crtc_state *pipe_config)
6925 {
6926         struct drm_device *dev = intel_crtc->base.dev;
6927         const struct drm_display_mode *adjusted_mode = &pipe_config->base.adjusted_mode;
6928         int lane, link_bw, fdi_dotclock, ret;
6929         bool needs_recompute = false;
6930
6931 retry:
6932         /* FDI is a binary signal running at ~2.7GHz, encoding
6933          * each output octet as 10 bits. The actual frequency
6934          * is stored as a divider into a 100MHz clock, and the
6935          * mode pixel clock is stored in units of 1KHz.
6936          * Hence the bw of each lane in terms of the mode signal
6937          * is:
6938          */
6939         link_bw = intel_fdi_link_freq(to_i915(dev), pipe_config);
6940
6941         fdi_dotclock = adjusted_mode->crtc_clock;
6942
6943         lane = ironlake_get_lanes_required(fdi_dotclock, link_bw,
6944                                            pipe_config->pipe_bpp);
6945
6946         pipe_config->fdi_lanes = lane;
6947
6948         intel_link_compute_m_n(pipe_config->pipe_bpp, lane, fdi_dotclock,
6949                                link_bw, &pipe_config->fdi_m_n);
6950
6951         ret = ironlake_check_fdi_lanes(dev, intel_crtc->pipe, pipe_config);
6952         if (ret == -EINVAL && pipe_config->pipe_bpp > 6*3) {
6953                 pipe_config->pipe_bpp -= 2*3;
6954                 DRM_DEBUG_KMS("fdi link bw constraint, reducing pipe bpp to %i\n",
6955                               pipe_config->pipe_bpp);
6956                 needs_recompute = true;
6957                 pipe_config->bw_constrained = true;
6958
6959                 goto retry;
6960         }
6961
6962         if (needs_recompute)
6963                 return RETRY;
6964
6965         return ret;
6966 }
6967
6968 static bool pipe_config_supports_ips(struct drm_i915_private *dev_priv,
6969                                      struct intel_crtc_state *pipe_config)
6970 {
6971         if (pipe_config->pipe_bpp > 24)
6972                 return false;
6973
6974         /* HSW can handle pixel rate up to cdclk? */
6975         if (IS_HASWELL(dev_priv))
6976                 return true;
6977
6978         /*
6979          * We compare against max which means we must take
6980          * the increased cdclk requirement into account when
6981          * calculating the new cdclk.
6982          *
6983          * Should measure whether using a lower cdclk w/o IPS
6984          */
6985         return ilk_pipe_pixel_rate(pipe_config) <=
6986                 dev_priv->max_cdclk_freq * 95 / 100;
6987 }
6988
6989 static void hsw_compute_ips_config(struct intel_crtc *crtc,
6990                                    struct intel_crtc_state *pipe_config)
6991 {
6992         struct drm_device *dev = crtc->base.dev;
6993         struct drm_i915_private *dev_priv = to_i915(dev);
6994
6995         pipe_config->ips_enabled = i915.enable_ips &&
6996                 hsw_crtc_supports_ips(crtc) &&
6997                 pipe_config_supports_ips(dev_priv, pipe_config);
6998 }
6999
7000 static bool intel_crtc_supports_double_wide(const struct intel_crtc *crtc)
7001 {
7002         const struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
7003
7004         /* GDG double wide on either pipe, otherwise pipe A only */
7005         return INTEL_INFO(dev_priv)->gen < 4 &&
7006                 (crtc->pipe == PIPE_A || IS_I915G(dev_priv));
7007 }
7008
7009 static int intel_crtc_compute_config(struct intel_crtc *crtc,
7010                                      struct intel_crtc_state *pipe_config)
7011 {
7012         struct drm_device *dev = crtc->base.dev;
7013         struct drm_i915_private *dev_priv = to_i915(dev);
7014         const struct drm_display_mode *adjusted_mode = &pipe_config->base.adjusted_mode;
7015         int clock_limit = dev_priv->max_dotclk_freq;
7016
7017         if (INTEL_INFO(dev)->gen < 4) {
7018                 clock_limit = dev_priv->max_cdclk_freq * 9 / 10;
7019
7020                 /*
7021                  * Enable double wide mode when the dot clock
7022                  * is > 90% of the (display) core speed.
7023                  */
7024                 if (intel_crtc_supports_double_wide(crtc) &&
7025                     adjusted_mode->crtc_clock > clock_limit) {
7026                         clock_limit = dev_priv->max_dotclk_freq;
7027                         pipe_config->double_wide = true;
7028                 }
7029         }
7030
7031         if (adjusted_mode->crtc_clock > clock_limit) {
7032                 DRM_DEBUG_KMS("requested pixel clock (%d kHz) too high (max: %d kHz, double wide: %s)\n",
7033                               adjusted_mode->crtc_clock, clock_limit,
7034                               yesno(pipe_config->double_wide));
7035                 return -EINVAL;
7036         }
7037
7038         /*
7039          * Pipe horizontal size must be even in:
7040          * - DVO ganged mode
7041          * - LVDS dual channel mode
7042          * - Double wide pipe
7043          */
7044         if ((intel_crtc_has_type(pipe_config, INTEL_OUTPUT_LVDS) &&
7045              intel_is_dual_link_lvds(dev)) || pipe_config->double_wide)
7046                 pipe_config->pipe_src_w &= ~1;
7047
7048         /* Cantiga+ cannot handle modes with a hsync front porch of 0.
7049          * WaPruneModeWithIncorrectHsyncOffset:ctg,elk,ilk,snb,ivb,vlv,hsw.
7050          */
7051         if ((INTEL_INFO(dev)->gen > 4 || IS_G4X(dev)) &&
7052                 adjusted_mode->crtc_hsync_start == adjusted_mode->crtc_hdisplay)
7053                 return -EINVAL;
7054
7055         if (HAS_IPS(dev))
7056                 hsw_compute_ips_config(crtc, pipe_config);
7057
7058         if (pipe_config->has_pch_encoder)
7059                 return ironlake_fdi_compute_config(crtc, pipe_config);
7060
7061         return 0;
7062 }
7063
7064 static int skylake_get_display_clock_speed(struct drm_device *dev)
7065 {
7066         struct drm_i915_private *dev_priv = to_i915(dev);
7067         uint32_t cdctl;
7068
7069         skl_dpll0_update(dev_priv);
7070
7071         if (dev_priv->cdclk_pll.vco == 0)
7072                 return dev_priv->cdclk_pll.ref;
7073
7074         cdctl = I915_READ(CDCLK_CTL);
7075
7076         if (dev_priv->cdclk_pll.vco == 8640000) {
7077                 switch (cdctl & CDCLK_FREQ_SEL_MASK) {
7078                 case CDCLK_FREQ_450_432:
7079                         return 432000;
7080                 case CDCLK_FREQ_337_308:
7081                         return 308571;
7082                 case CDCLK_FREQ_540:
7083                         return 540000;
7084                 case CDCLK_FREQ_675_617:
7085                         return 617143;
7086                 default:
7087                         MISSING_CASE(cdctl & CDCLK_FREQ_SEL_MASK);
7088                 }
7089         } else {
7090                 switch (cdctl & CDCLK_FREQ_SEL_MASK) {
7091                 case CDCLK_FREQ_450_432:
7092                         return 450000;
7093                 case CDCLK_FREQ_337_308:
7094                         return 337500;
7095                 case CDCLK_FREQ_540:
7096                         return 540000;
7097                 case CDCLK_FREQ_675_617:
7098                         return 675000;
7099                 default:
7100                         MISSING_CASE(cdctl & CDCLK_FREQ_SEL_MASK);
7101                 }
7102         }
7103
7104         return dev_priv->cdclk_pll.ref;
7105 }
7106
7107 static void bxt_de_pll_update(struct drm_i915_private *dev_priv)
7108 {
7109         u32 val;
7110
7111         dev_priv->cdclk_pll.ref = 19200;
7112         dev_priv->cdclk_pll.vco = 0;
7113
7114         val = I915_READ(BXT_DE_PLL_ENABLE);
7115         if ((val & BXT_DE_PLL_PLL_ENABLE) == 0)
7116                 return;
7117
7118         if (WARN_ON((val & BXT_DE_PLL_LOCK) == 0))
7119                 return;
7120
7121         val = I915_READ(BXT_DE_PLL_CTL);
7122         dev_priv->cdclk_pll.vco = (val & BXT_DE_PLL_RATIO_MASK) *
7123                 dev_priv->cdclk_pll.ref;
7124 }
7125
7126 static int broxton_get_display_clock_speed(struct drm_device *dev)
7127 {
7128         struct drm_i915_private *dev_priv = to_i915(dev);
7129         u32 divider;
7130         int div, vco;
7131
7132         bxt_de_pll_update(dev_priv);
7133
7134         vco = dev_priv->cdclk_pll.vco;
7135         if (vco == 0)
7136                 return dev_priv->cdclk_pll.ref;
7137
7138         divider = I915_READ(CDCLK_CTL) & BXT_CDCLK_CD2X_DIV_SEL_MASK;
7139
7140         switch (divider) {
7141         case BXT_CDCLK_CD2X_DIV_SEL_1:
7142                 div = 2;
7143                 break;
7144         case BXT_CDCLK_CD2X_DIV_SEL_1_5:
7145                 div = 3;
7146                 break;
7147         case BXT_CDCLK_CD2X_DIV_SEL_2:
7148                 div = 4;
7149                 break;
7150         case BXT_CDCLK_CD2X_DIV_SEL_4:
7151                 div = 8;
7152                 break;
7153         default:
7154                 MISSING_CASE(divider);
7155                 return dev_priv->cdclk_pll.ref;
7156         }
7157
7158         return DIV_ROUND_CLOSEST(vco, div);
7159 }
7160
7161 static int broadwell_get_display_clock_speed(struct drm_device *dev)
7162 {
7163         struct drm_i915_private *dev_priv = to_i915(dev);
7164         uint32_t lcpll = I915_READ(LCPLL_CTL);
7165         uint32_t freq = lcpll & LCPLL_CLK_FREQ_MASK;
7166
7167         if (lcpll & LCPLL_CD_SOURCE_FCLK)
7168                 return 800000;
7169         else if (I915_READ(FUSE_STRAP) & HSW_CDCLK_LIMIT)
7170                 return 450000;
7171         else if (freq == LCPLL_CLK_FREQ_450)
7172                 return 450000;
7173         else if (freq == LCPLL_CLK_FREQ_54O_BDW)
7174                 return 540000;
7175         else if (freq == LCPLL_CLK_FREQ_337_5_BDW)
7176                 return 337500;
7177         else
7178                 return 675000;
7179 }
7180
7181 static int haswell_get_display_clock_speed(struct drm_device *dev)
7182 {
7183         struct drm_i915_private *dev_priv = to_i915(dev);
7184         uint32_t lcpll = I915_READ(LCPLL_CTL);
7185         uint32_t freq = lcpll & LCPLL_CLK_FREQ_MASK;
7186
7187         if (lcpll & LCPLL_CD_SOURCE_FCLK)
7188                 return 800000;
7189         else if (I915_READ(FUSE_STRAP) & HSW_CDCLK_LIMIT)
7190                 return 450000;
7191         else if (freq == LCPLL_CLK_FREQ_450)
7192                 return 450000;
7193         else if (IS_HSW_ULT(dev))
7194                 return 337500;
7195         else
7196                 return 540000;
7197 }
7198
7199 static int valleyview_get_display_clock_speed(struct drm_device *dev)
7200 {
7201         return vlv_get_cck_clock_hpll(to_i915(dev), "cdclk",
7202                                       CCK_DISPLAY_CLOCK_CONTROL);
7203 }
7204
7205 static int ilk_get_display_clock_speed(struct drm_device *dev)
7206 {
7207         return 450000;
7208 }
7209
7210 static int i945_get_display_clock_speed(struct drm_device *dev)
7211 {
7212         return 400000;
7213 }
7214
7215 static int i915_get_display_clock_speed(struct drm_device *dev)
7216 {
7217         return 333333;
7218 }
7219
7220 static int i9xx_misc_get_display_clock_speed(struct drm_device *dev)
7221 {
7222         return 200000;
7223 }
7224
7225 static int pnv_get_display_clock_speed(struct drm_device *dev)
7226 {
7227         u16 gcfgc = 0;
7228
7229         pci_read_config_word(dev->pdev, GCFGC, &gcfgc);
7230
7231         switch (gcfgc & GC_DISPLAY_CLOCK_MASK) {
7232         case GC_DISPLAY_CLOCK_267_MHZ_PNV:
7233                 return 266667;
7234         case GC_DISPLAY_CLOCK_333_MHZ_PNV:
7235                 return 333333;
7236         case GC_DISPLAY_CLOCK_444_MHZ_PNV:
7237                 return 444444;
7238         case GC_DISPLAY_CLOCK_200_MHZ_PNV:
7239                 return 200000;
7240         default:
7241                 DRM_ERROR("Unknown pnv display core clock 0x%04x\n", gcfgc);
7242         case GC_DISPLAY_CLOCK_133_MHZ_PNV:
7243                 return 133333;
7244         case GC_DISPLAY_CLOCK_167_MHZ_PNV:
7245                 return 166667;
7246         }
7247 }
7248
7249 static int i915gm_get_display_clock_speed(struct drm_device *dev)
7250 {
7251         u16 gcfgc = 0;
7252
7253         pci_read_config_word(dev->pdev, GCFGC, &gcfgc);
7254
7255         if (gcfgc & GC_LOW_FREQUENCY_ENABLE)
7256                 return 133333;
7257         else {
7258                 switch (gcfgc & GC_DISPLAY_CLOCK_MASK) {
7259                 case GC_DISPLAY_CLOCK_333_MHZ:
7260                         return 333333;
7261                 default:
7262                 case GC_DISPLAY_CLOCK_190_200_MHZ:
7263                         return 190000;
7264                 }
7265         }
7266 }
7267
7268 static int i865_get_display_clock_speed(struct drm_device *dev)
7269 {
7270         return 266667;
7271 }
7272
7273 static int i85x_get_display_clock_speed(struct drm_device *dev)
7274 {
7275         u16 hpllcc = 0;
7276
7277         /*
7278          * 852GM/852GMV only supports 133 MHz and the HPLLCC
7279          * encoding is different :(
7280          * FIXME is this the right way to detect 852GM/852GMV?
7281          */
7282         if (dev->pdev->revision == 0x1)
7283                 return 133333;
7284
7285         pci_bus_read_config_word(dev->pdev->bus,
7286                                  PCI_DEVFN(0, 3), HPLLCC, &hpllcc);
7287
7288         /* Assume that the hardware is in the high speed state.  This
7289          * should be the default.
7290          */
7291         switch (hpllcc & GC_CLOCK_CONTROL_MASK) {
7292         case GC_CLOCK_133_200:
7293         case GC_CLOCK_133_200_2:
7294         case GC_CLOCK_100_200:
7295                 return 200000;
7296         case GC_CLOCK_166_250:
7297                 return 250000;
7298         case GC_CLOCK_100_133:
7299                 return 133333;
7300         case GC_CLOCK_133_266:
7301         case GC_CLOCK_133_266_2:
7302         case GC_CLOCK_166_266:
7303                 return 266667;
7304         }
7305
7306         /* Shouldn't happen */
7307         return 0;
7308 }
7309
7310 static int i830_get_display_clock_speed(struct drm_device *dev)
7311 {
7312         return 133333;
7313 }
7314
7315 static unsigned int intel_hpll_vco(struct drm_device *dev)
7316 {
7317         struct drm_i915_private *dev_priv = to_i915(dev);
7318         static const unsigned int blb_vco[8] = {
7319                 [0] = 3200000,
7320                 [1] = 4000000,
7321                 [2] = 5333333,
7322                 [3] = 4800000,
7323                 [4] = 6400000,
7324         };
7325         static const unsigned int pnv_vco[8] = {
7326                 [0] = 3200000,
7327                 [1] = 4000000,
7328                 [2] = 5333333,
7329                 [3] = 4800000,
7330                 [4] = 2666667,
7331         };
7332         static const unsigned int cl_vco[8] = {
7333                 [0] = 3200000,
7334                 [1] = 4000000,
7335                 [2] = 5333333,
7336                 [3] = 6400000,
7337                 [4] = 3333333,
7338                 [5] = 3566667,
7339                 [6] = 4266667,
7340         };
7341         static const unsigned int elk_vco[8] = {
7342                 [0] = 3200000,
7343                 [1] = 4000000,
7344                 [2] = 5333333,
7345                 [3] = 4800000,
7346         };
7347         static const unsigned int ctg_vco[8] = {
7348                 [0] = 3200000,
7349                 [1] = 4000000,
7350                 [2] = 5333333,
7351                 [3] = 6400000,
7352                 [4] = 2666667,
7353                 [5] = 4266667,
7354         };
7355         const unsigned int *vco_table;
7356         unsigned int vco;
7357         uint8_t tmp = 0;
7358
7359         /* FIXME other chipsets? */
7360         if (IS_GM45(dev))
7361                 vco_table = ctg_vco;
7362         else if (IS_G4X(dev))
7363                 vco_table = elk_vco;
7364         else if (IS_CRESTLINE(dev))
7365                 vco_table = cl_vco;
7366         else if (IS_PINEVIEW(dev))
7367                 vco_table = pnv_vco;
7368         else if (IS_G33(dev))
7369                 vco_table = blb_vco;
7370         else
7371                 return 0;
7372
7373         tmp = I915_READ(IS_MOBILE(dev) ? HPLLVCO_MOBILE : HPLLVCO);
7374
7375         vco = vco_table[tmp & 0x7];
7376         if (vco == 0)
7377                 DRM_ERROR("Bad HPLL VCO (HPLLVCO=0x%02x)\n", tmp);
7378         else
7379                 DRM_DEBUG_KMS("HPLL VCO %u kHz\n", vco);
7380
7381         return vco;
7382 }
7383
7384 static int gm45_get_display_clock_speed(struct drm_device *dev)
7385 {
7386         unsigned int cdclk_sel, vco = intel_hpll_vco(dev);
7387         uint16_t tmp = 0;
7388
7389         pci_read_config_word(dev->pdev, GCFGC, &tmp);
7390
7391         cdclk_sel = (tmp >> 12) & 0x1;
7392
7393         switch (vco) {
7394         case 2666667:
7395         case 4000000:
7396         case 5333333:
7397                 return cdclk_sel ? 333333 : 222222;
7398         case 3200000:
7399                 return cdclk_sel ? 320000 : 228571;
7400         default:
7401                 DRM_ERROR("Unable to determine CDCLK. HPLL VCO=%u, CFGC=0x%04x\n", vco, tmp);
7402                 return 222222;
7403         }
7404 }
7405
7406 static int i965gm_get_display_clock_speed(struct drm_device *dev)
7407 {
7408         static const uint8_t div_3200[] = { 16, 10,  8 };
7409         static const uint8_t div_4000[] = { 20, 12, 10 };
7410         static const uint8_t div_5333[] = { 24, 16, 14 };
7411         const uint8_t *div_table;
7412         unsigned int cdclk_sel, vco = intel_hpll_vco(dev);
7413         uint16_t tmp = 0;
7414
7415         pci_read_config_word(dev->pdev, GCFGC, &tmp);
7416
7417         cdclk_sel = ((tmp >> 8) & 0x1f) - 1;
7418
7419         if (cdclk_sel >= ARRAY_SIZE(div_3200))
7420                 goto fail;
7421
7422         switch (vco) {
7423         case 3200000:
7424                 div_table = div_3200;
7425                 break;
7426         case 4000000:
7427                 div_table = div_4000;
7428                 break;
7429         case 5333333:
7430                 div_table = div_5333;
7431                 break;
7432         default:
7433                 goto fail;
7434         }
7435
7436         return DIV_ROUND_CLOSEST(vco, div_table[cdclk_sel]);
7437
7438 fail:
7439         DRM_ERROR("Unable to determine CDCLK. HPLL VCO=%u kHz, CFGC=0x%04x\n", vco, tmp);
7440         return 200000;
7441 }
7442
7443 static int g33_get_display_clock_speed(struct drm_device *dev)
7444 {
7445         static const uint8_t div_3200[] = { 12, 10,  8,  7, 5, 16 };
7446         static const uint8_t div_4000[] = { 14, 12, 10,  8, 6, 20 };
7447         static const uint8_t div_4800[] = { 20, 14, 12, 10, 8, 24 };
7448         static const uint8_t div_5333[] = { 20, 16, 12, 12, 8, 28 };
7449         const uint8_t *div_table;
7450         unsigned int cdclk_sel, vco = intel_hpll_vco(dev);
7451         uint16_t tmp = 0;
7452
7453         pci_read_config_word(dev->pdev, GCFGC, &tmp);
7454
7455         cdclk_sel = (tmp >> 4) & 0x7;
7456
7457         if (cdclk_sel >= ARRAY_SIZE(div_3200))
7458                 goto fail;
7459
7460         switch (vco) {
7461         case 3200000:
7462                 div_table = div_3200;
7463                 break;
7464         case 4000000:
7465                 div_table = div_4000;
7466                 break;
7467         case 4800000:
7468                 div_table = div_4800;
7469                 break;
7470         case 5333333:
7471                 div_table = div_5333;
7472                 break;
7473         default:
7474                 goto fail;
7475         }
7476
7477         return DIV_ROUND_CLOSEST(vco, div_table[cdclk_sel]);
7478
7479 fail:
7480         DRM_ERROR("Unable to determine CDCLK. HPLL VCO=%u kHz, CFGC=0x%08x\n", vco, tmp);
7481         return 190476;
7482 }
7483
7484 static void
7485 intel_reduce_m_n_ratio(uint32_t *num, uint32_t *den)
7486 {
7487         while (*num > DATA_LINK_M_N_MASK ||
7488                *den > DATA_LINK_M_N_MASK) {
7489                 *num >>= 1;
7490                 *den >>= 1;
7491         }
7492 }
7493
7494 static void compute_m_n(unsigned int m, unsigned int n,
7495                         uint32_t *ret_m, uint32_t *ret_n)
7496 {
7497         *ret_n = min_t(unsigned int, roundup_pow_of_two(n), DATA_LINK_N_MAX);
7498         *ret_m = div_u64((uint64_t) m * *ret_n, n);
7499         intel_reduce_m_n_ratio(ret_m, ret_n);
7500 }
7501
7502 void
7503 intel_link_compute_m_n(int bits_per_pixel, int nlanes,
7504                        int pixel_clock, int link_clock,
7505                        struct intel_link_m_n *m_n)
7506 {
7507         m_n->tu = 64;
7508
7509         compute_m_n(bits_per_pixel * pixel_clock,
7510                     link_clock * nlanes * 8,
7511                     &m_n->gmch_m, &m_n->gmch_n);
7512
7513         compute_m_n(pixel_clock, link_clock,
7514                     &m_n->link_m, &m_n->link_n);
7515 }
7516
7517 static inline bool intel_panel_use_ssc(struct drm_i915_private *dev_priv)
7518 {
7519         if (i915.panel_use_ssc >= 0)
7520                 return i915.panel_use_ssc != 0;
7521         return dev_priv->vbt.lvds_use_ssc
7522                 && !(dev_priv->quirks & QUIRK_LVDS_SSC_DISABLE);
7523 }
7524
7525 static uint32_t pnv_dpll_compute_fp(struct dpll *dpll)
7526 {
7527         return (1 << dpll->n) << 16 | dpll->m2;
7528 }
7529
7530 static uint32_t i9xx_dpll_compute_fp(struct dpll *dpll)
7531 {
7532         return dpll->n << 16 | dpll->m1 << 8 | dpll->m2;
7533 }
7534
7535 static void i9xx_update_pll_dividers(struct intel_crtc *crtc,
7536                                      struct intel_crtc_state *crtc_state,
7537                                      struct dpll *reduced_clock)
7538 {
7539         struct drm_device *dev = crtc->base.dev;
7540         u32 fp, fp2 = 0;
7541
7542         if (IS_PINEVIEW(dev)) {
7543                 fp = pnv_dpll_compute_fp(&crtc_state->dpll);
7544                 if (reduced_clock)
7545                         fp2 = pnv_dpll_compute_fp(reduced_clock);
7546         } else {
7547                 fp = i9xx_dpll_compute_fp(&crtc_state->dpll);
7548                 if (reduced_clock)
7549                         fp2 = i9xx_dpll_compute_fp(reduced_clock);
7550         }
7551
7552         crtc_state->dpll_hw_state.fp0 = fp;
7553
7554         crtc->lowfreq_avail = false;
7555         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS) &&
7556             reduced_clock) {
7557                 crtc_state->dpll_hw_state.fp1 = fp2;
7558                 crtc->lowfreq_avail = true;
7559         } else {
7560                 crtc_state->dpll_hw_state.fp1 = fp;
7561         }
7562 }
7563
7564 static void vlv_pllb_recal_opamp(struct drm_i915_private *dev_priv, enum pipe
7565                 pipe)
7566 {
7567         u32 reg_val;
7568
7569         /*
7570          * PLLB opamp always calibrates to max value of 0x3f, force enable it
7571          * and set it to a reasonable value instead.
7572          */
7573         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW9(1));
7574         reg_val &= 0xffffff00;
7575         reg_val |= 0x00000030;
7576         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW9(1), reg_val);
7577
7578         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_REF_DW13);
7579         reg_val &= 0x8cffffff;
7580         reg_val = 0x8c000000;
7581         vlv_dpio_write(dev_priv, pipe, VLV_REF_DW13, reg_val);
7582
7583         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW9(1));
7584         reg_val &= 0xffffff00;
7585         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW9(1), reg_val);
7586
7587         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_REF_DW13);
7588         reg_val &= 0x00ffffff;
7589         reg_val |= 0xb0000000;
7590         vlv_dpio_write(dev_priv, pipe, VLV_REF_DW13, reg_val);
7591 }
7592
7593 static void intel_pch_transcoder_set_m_n(struct intel_crtc *crtc,
7594                                          struct intel_link_m_n *m_n)
7595 {
7596         struct drm_device *dev = crtc->base.dev;
7597         struct drm_i915_private *dev_priv = to_i915(dev);
7598         int pipe = crtc->pipe;
7599
7600         I915_WRITE(PCH_TRANS_DATA_M1(pipe), TU_SIZE(m_n->tu) | m_n->gmch_m);
7601         I915_WRITE(PCH_TRANS_DATA_N1(pipe), m_n->gmch_n);
7602         I915_WRITE(PCH_TRANS_LINK_M1(pipe), m_n->link_m);
7603         I915_WRITE(PCH_TRANS_LINK_N1(pipe), m_n->link_n);
7604 }
7605
7606 static void intel_cpu_transcoder_set_m_n(struct intel_crtc *crtc,
7607                                          struct intel_link_m_n *m_n,
7608                                          struct intel_link_m_n *m2_n2)
7609 {
7610         struct drm_device *dev = crtc->base.dev;
7611         struct drm_i915_private *dev_priv = to_i915(dev);
7612         int pipe = crtc->pipe;
7613         enum transcoder transcoder = crtc->config->cpu_transcoder;
7614
7615         if (INTEL_INFO(dev)->gen >= 5) {
7616                 I915_WRITE(PIPE_DATA_M1(transcoder), TU_SIZE(m_n->tu) | m_n->gmch_m);
7617                 I915_WRITE(PIPE_DATA_N1(transcoder), m_n->gmch_n);
7618                 I915_WRITE(PIPE_LINK_M1(transcoder), m_n->link_m);
7619                 I915_WRITE(PIPE_LINK_N1(transcoder), m_n->link_n);
7620                 /* M2_N2 registers to be set only for gen < 8 (M2_N2 available
7621                  * for gen < 8) and if DRRS is supported (to make sure the
7622                  * registers are not unnecessarily accessed).
7623                  */
7624                 if (m2_n2 && (IS_CHERRYVIEW(dev) || INTEL_INFO(dev)->gen < 8) &&
7625                         crtc->config->has_drrs) {
7626                         I915_WRITE(PIPE_DATA_M2(transcoder),
7627                                         TU_SIZE(m2_n2->tu) | m2_n2->gmch_m);
7628                         I915_WRITE(PIPE_DATA_N2(transcoder), m2_n2->gmch_n);
7629                         I915_WRITE(PIPE_LINK_M2(transcoder), m2_n2->link_m);
7630                         I915_WRITE(PIPE_LINK_N2(transcoder), m2_n2->link_n);
7631                 }
7632         } else {
7633                 I915_WRITE(PIPE_DATA_M_G4X(pipe), TU_SIZE(m_n->tu) | m_n->gmch_m);
7634                 I915_WRITE(PIPE_DATA_N_G4X(pipe), m_n->gmch_n);
7635                 I915_WRITE(PIPE_LINK_M_G4X(pipe), m_n->link_m);
7636                 I915_WRITE(PIPE_LINK_N_G4X(pipe), m_n->link_n);
7637         }
7638 }
7639
7640 void intel_dp_set_m_n(struct intel_crtc *crtc, enum link_m_n_set m_n)
7641 {
7642         struct intel_link_m_n *dp_m_n, *dp_m2_n2 = NULL;
7643
7644         if (m_n == M1_N1) {
7645                 dp_m_n = &crtc->config->dp_m_n;
7646                 dp_m2_n2 = &crtc->config->dp_m2_n2;
7647         } else if (m_n == M2_N2) {
7648
7649                 /*
7650                  * M2_N2 registers are not supported. Hence m2_n2 divider value
7651                  * needs to be programmed into M1_N1.
7652                  */
7653                 dp_m_n = &crtc->config->dp_m2_n2;
7654         } else {
7655                 DRM_ERROR("Unsupported divider value\n");
7656                 return;
7657         }
7658
7659         if (crtc->config->has_pch_encoder)
7660                 intel_pch_transcoder_set_m_n(crtc, &crtc->config->dp_m_n);
7661         else
7662                 intel_cpu_transcoder_set_m_n(crtc, dp_m_n, dp_m2_n2);
7663 }
7664
7665 static void vlv_compute_dpll(struct intel_crtc *crtc,
7666                              struct intel_crtc_state *pipe_config)
7667 {
7668         pipe_config->dpll_hw_state.dpll = DPLL_INTEGRATED_REF_CLK_VLV |
7669                 DPLL_REF_CLK_ENABLE_VLV | DPLL_VGA_MODE_DIS;
7670         if (crtc->pipe != PIPE_A)
7671                 pipe_config->dpll_hw_state.dpll |= DPLL_INTEGRATED_CRI_CLK_VLV;
7672
7673         /* DPLL not used with DSI, but still need the rest set up */
7674         if (!intel_crtc_has_type(pipe_config, INTEL_OUTPUT_DSI))
7675                 pipe_config->dpll_hw_state.dpll |= DPLL_VCO_ENABLE |
7676                         DPLL_EXT_BUFFER_ENABLE_VLV;
7677
7678         pipe_config->dpll_hw_state.dpll_md =
7679                 (pipe_config->pixel_multiplier - 1) << DPLL_MD_UDI_MULTIPLIER_SHIFT;
7680 }
7681
7682 static void chv_compute_dpll(struct intel_crtc *crtc,
7683                              struct intel_crtc_state *pipe_config)
7684 {
7685         pipe_config->dpll_hw_state.dpll = DPLL_SSC_REF_CLK_CHV |
7686                 DPLL_REF_CLK_ENABLE_VLV | DPLL_VGA_MODE_DIS;
7687         if (crtc->pipe != PIPE_A)
7688                 pipe_config->dpll_hw_state.dpll |= DPLL_INTEGRATED_CRI_CLK_VLV;
7689
7690         /* DPLL not used with DSI, but still need the rest set up */
7691         if (!intel_crtc_has_type(pipe_config, INTEL_OUTPUT_DSI))
7692                 pipe_config->dpll_hw_state.dpll |= DPLL_VCO_ENABLE;
7693
7694         pipe_config->dpll_hw_state.dpll_md =
7695                 (pipe_config->pixel_multiplier - 1) << DPLL_MD_UDI_MULTIPLIER_SHIFT;
7696 }
7697
7698 static void vlv_prepare_pll(struct intel_crtc *crtc,
7699                             const struct intel_crtc_state *pipe_config)
7700 {
7701         struct drm_device *dev = crtc->base.dev;
7702         struct drm_i915_private *dev_priv = to_i915(dev);
7703         enum pipe pipe = crtc->pipe;
7704         u32 mdiv;
7705         u32 bestn, bestm1, bestm2, bestp1, bestp2;
7706         u32 coreclk, reg_val;
7707
7708         /* Enable Refclk */
7709         I915_WRITE(DPLL(pipe),
7710                    pipe_config->dpll_hw_state.dpll &
7711                    ~(DPLL_VCO_ENABLE | DPLL_EXT_BUFFER_ENABLE_VLV));
7712
7713         /* No need to actually set up the DPLL with DSI */
7714         if ((pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE) == 0)
7715                 return;
7716
7717         mutex_lock(&dev_priv->sb_lock);
7718
7719         bestn = pipe_config->dpll.n;
7720         bestm1 = pipe_config->dpll.m1;
7721         bestm2 = pipe_config->dpll.m2;
7722         bestp1 = pipe_config->dpll.p1;
7723         bestp2 = pipe_config->dpll.p2;
7724
7725         /* See eDP HDMI DPIO driver vbios notes doc */
7726
7727         /* PLL B needs special handling */
7728         if (pipe == PIPE_B)
7729                 vlv_pllb_recal_opamp(dev_priv, pipe);
7730
7731         /* Set up Tx target for periodic Rcomp update */
7732         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW9_BCAST, 0x0100000f);
7733
7734         /* Disable target IRef on PLL */
7735         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW8(pipe));
7736         reg_val &= 0x00ffffff;
7737         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW8(pipe), reg_val);
7738
7739         /* Disable fast lock */
7740         vlv_dpio_write(dev_priv, pipe, VLV_CMN_DW0, 0x610);
7741
7742         /* Set idtafcrecal before PLL is enabled */
7743         mdiv = ((bestm1 << DPIO_M1DIV_SHIFT) | (bestm2 & DPIO_M2DIV_MASK));
7744         mdiv |= ((bestp1 << DPIO_P1_SHIFT) | (bestp2 << DPIO_P2_SHIFT));
7745         mdiv |= ((bestn << DPIO_N_SHIFT));
7746         mdiv |= (1 << DPIO_K_SHIFT);
7747
7748         /*
7749          * Post divider depends on pixel clock rate, DAC vs digital (and LVDS,
7750          * but we don't support that).
7751          * Note: don't use the DAC post divider as it seems unstable.
7752          */
7753         mdiv |= (DPIO_POST_DIV_HDMIDP << DPIO_POST_DIV_SHIFT);
7754         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW3(pipe), mdiv);
7755
7756         mdiv |= DPIO_ENABLE_CALIBRATION;
7757         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW3(pipe), mdiv);
7758
7759         /* Set HBR and RBR LPF coefficients */
7760         if (pipe_config->port_clock == 162000 ||
7761             intel_crtc_has_type(crtc->config, INTEL_OUTPUT_ANALOG) ||
7762             intel_crtc_has_type(crtc->config, INTEL_OUTPUT_HDMI))
7763                 vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW10(pipe),
7764                                  0x009f0003);
7765         else
7766                 vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW10(pipe),
7767                                  0x00d0000f);
7768
7769         if (intel_crtc_has_dp_encoder(pipe_config)) {
7770                 /* Use SSC source */
7771                 if (pipe == PIPE_A)
7772                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
7773                                          0x0df40000);
7774                 else
7775                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
7776                                          0x0df70000);
7777         } else { /* HDMI or VGA */
7778                 /* Use bend source */
7779                 if (pipe == PIPE_A)
7780                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
7781                                          0x0df70000);
7782                 else
7783                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
7784                                          0x0df40000);
7785         }
7786
7787         coreclk = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW7(pipe));
7788         coreclk = (coreclk & 0x0000ff00) | 0x01c00000;
7789         if (intel_crtc_has_dp_encoder(crtc->config))
7790                 coreclk |= 0x01000000;
7791         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW7(pipe), coreclk);
7792
7793         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW11(pipe), 0x87871000);
7794         mutex_unlock(&dev_priv->sb_lock);
7795 }
7796
7797 static void chv_prepare_pll(struct intel_crtc *crtc,
7798                             const struct intel_crtc_state *pipe_config)
7799 {
7800         struct drm_device *dev = crtc->base.dev;
7801         struct drm_i915_private *dev_priv = to_i915(dev);
7802         enum pipe pipe = crtc->pipe;
7803         enum dpio_channel port = vlv_pipe_to_channel(pipe);
7804         u32 loopfilter, tribuf_calcntr;
7805         u32 bestn, bestm1, bestm2, bestp1, bestp2, bestm2_frac;
7806         u32 dpio_val;
7807         int vco;
7808
7809         /* Enable Refclk and SSC */
7810         I915_WRITE(DPLL(pipe),
7811                    pipe_config->dpll_hw_state.dpll & ~DPLL_VCO_ENABLE);
7812
7813         /* No need to actually set up the DPLL with DSI */
7814         if ((pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE) == 0)
7815                 return;
7816
7817         bestn = pipe_config->dpll.n;
7818         bestm2_frac = pipe_config->dpll.m2 & 0x3fffff;
7819         bestm1 = pipe_config->dpll.m1;
7820         bestm2 = pipe_config->dpll.m2 >> 22;
7821         bestp1 = pipe_config->dpll.p1;
7822         bestp2 = pipe_config->dpll.p2;
7823         vco = pipe_config->dpll.vco;
7824         dpio_val = 0;
7825         loopfilter = 0;
7826
7827         mutex_lock(&dev_priv->sb_lock);
7828
7829         /* p1 and p2 divider */
7830         vlv_dpio_write(dev_priv, pipe, CHV_CMN_DW13(port),
7831                         5 << DPIO_CHV_S1_DIV_SHIFT |
7832                         bestp1 << DPIO_CHV_P1_DIV_SHIFT |
7833                         bestp2 << DPIO_CHV_P2_DIV_SHIFT |
7834                         1 << DPIO_CHV_K_DIV_SHIFT);
7835
7836         /* Feedback post-divider - m2 */
7837         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW0(port), bestm2);
7838
7839         /* Feedback refclk divider - n and m1 */
7840         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW1(port),
7841                         DPIO_CHV_M1_DIV_BY_2 |
7842                         1 << DPIO_CHV_N_DIV_SHIFT);
7843
7844         /* M2 fraction division */
7845         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW2(port), bestm2_frac);
7846
7847         /* M2 fraction division enable */
7848         dpio_val = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW3(port));
7849         dpio_val &= ~(DPIO_CHV_FEEDFWD_GAIN_MASK | DPIO_CHV_FRAC_DIV_EN);
7850         dpio_val |= (2 << DPIO_CHV_FEEDFWD_GAIN_SHIFT);
7851         if (bestm2_frac)
7852                 dpio_val |= DPIO_CHV_FRAC_DIV_EN;
7853         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW3(port), dpio_val);
7854
7855         /* Program digital lock detect threshold */
7856         dpio_val = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW9(port));
7857         dpio_val &= ~(DPIO_CHV_INT_LOCK_THRESHOLD_MASK |
7858                                         DPIO_CHV_INT_LOCK_THRESHOLD_SEL_COARSE);
7859         dpio_val |= (0x5 << DPIO_CHV_INT_LOCK_THRESHOLD_SHIFT);
7860         if (!bestm2_frac)
7861                 dpio_val |= DPIO_CHV_INT_LOCK_THRESHOLD_SEL_COARSE;
7862         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW9(port), dpio_val);
7863
7864         /* Loop filter */
7865         if (vco == 5400000) {
7866                 loopfilter |= (0x3 << DPIO_CHV_PROP_COEFF_SHIFT);
7867                 loopfilter |= (0x8 << DPIO_CHV_INT_COEFF_SHIFT);
7868                 loopfilter |= (0x1 << DPIO_CHV_GAIN_CTRL_SHIFT);
7869                 tribuf_calcntr = 0x9;
7870         } else if (vco <= 6200000) {
7871                 loopfilter |= (0x5 << DPIO_CHV_PROP_COEFF_SHIFT);
7872                 loopfilter |= (0xB << DPIO_CHV_INT_COEFF_SHIFT);
7873                 loopfilter |= (0x3 << DPIO_CHV_GAIN_CTRL_SHIFT);
7874                 tribuf_calcntr = 0x9;
7875         } else if (vco <= 6480000) {
7876                 loopfilter |= (0x4 << DPIO_CHV_PROP_COEFF_SHIFT);
7877                 loopfilter |= (0x9 << DPIO_CHV_INT_COEFF_SHIFT);
7878                 loopfilter |= (0x3 << DPIO_CHV_GAIN_CTRL_SHIFT);
7879                 tribuf_calcntr = 0x8;
7880         } else {
7881                 /* Not supported. Apply the same limits as in the max case */
7882                 loopfilter |= (0x4 << DPIO_CHV_PROP_COEFF_SHIFT);
7883                 loopfilter |= (0x9 << DPIO_CHV_INT_COEFF_SHIFT);
7884                 loopfilter |= (0x3 << DPIO_CHV_GAIN_CTRL_SHIFT);
7885                 tribuf_calcntr = 0;
7886         }
7887         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW6(port), loopfilter);
7888
7889         dpio_val = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW8(port));
7890         dpio_val &= ~DPIO_CHV_TDC_TARGET_CNT_MASK;
7891         dpio_val |= (tribuf_calcntr << DPIO_CHV_TDC_TARGET_CNT_SHIFT);
7892         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW8(port), dpio_val);
7893
7894         /* AFC Recal */
7895         vlv_dpio_write(dev_priv, pipe, CHV_CMN_DW14(port),
7896                         vlv_dpio_read(dev_priv, pipe, CHV_CMN_DW14(port)) |
7897                         DPIO_AFC_RECAL);
7898
7899         mutex_unlock(&dev_priv->sb_lock);
7900 }
7901
7902 /**
7903  * vlv_force_pll_on - forcibly enable just the PLL
7904  * @dev_priv: i915 private structure
7905  * @pipe: pipe PLL to enable
7906  * @dpll: PLL configuration
7907  *
7908  * Enable the PLL for @pipe using the supplied @dpll config. To be used
7909  * in cases where we need the PLL enabled even when @pipe is not going to
7910  * be enabled.
7911  */
7912 int vlv_force_pll_on(struct drm_device *dev, enum pipe pipe,
7913                      const struct dpll *dpll)
7914 {
7915         struct intel_crtc *crtc =
7916                 to_intel_crtc(intel_get_crtc_for_pipe(dev, pipe));
7917         struct intel_crtc_state *pipe_config;
7918
7919         pipe_config = kzalloc(sizeof(*pipe_config), GFP_KERNEL);
7920         if (!pipe_config)
7921                 return -ENOMEM;
7922
7923         pipe_config->base.crtc = &crtc->base;
7924         pipe_config->pixel_multiplier = 1;
7925         pipe_config->dpll = *dpll;
7926
7927         if (IS_CHERRYVIEW(dev)) {
7928                 chv_compute_dpll(crtc, pipe_config);
7929                 chv_prepare_pll(crtc, pipe_config);
7930                 chv_enable_pll(crtc, pipe_config);
7931         } else {
7932                 vlv_compute_dpll(crtc, pipe_config);
7933                 vlv_prepare_pll(crtc, pipe_config);
7934                 vlv_enable_pll(crtc, pipe_config);
7935         }
7936
7937         kfree(pipe_config);
7938
7939         return 0;
7940 }
7941
7942 /**
7943  * vlv_force_pll_off - forcibly disable just the PLL
7944  * @dev_priv: i915 private structure
7945  * @pipe: pipe PLL to disable
7946  *
7947  * Disable the PLL for @pipe. To be used in cases where we need
7948  * the PLL enabled even when @pipe is not going to be enabled.
7949  */
7950 void vlv_force_pll_off(struct drm_device *dev, enum pipe pipe)
7951 {
7952         if (IS_CHERRYVIEW(dev))
7953                 chv_disable_pll(to_i915(dev), pipe);
7954         else
7955                 vlv_disable_pll(to_i915(dev), pipe);
7956 }
7957
7958 static void i9xx_compute_dpll(struct intel_crtc *crtc,
7959                               struct intel_crtc_state *crtc_state,
7960                               struct dpll *reduced_clock)
7961 {
7962         struct drm_device *dev = crtc->base.dev;
7963         struct drm_i915_private *dev_priv = to_i915(dev);
7964         u32 dpll;
7965         struct dpll *clock = &crtc_state->dpll;
7966
7967         i9xx_update_pll_dividers(crtc, crtc_state, reduced_clock);
7968
7969         dpll = DPLL_VGA_MODE_DIS;
7970
7971         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS))
7972                 dpll |= DPLLB_MODE_LVDS;
7973         else
7974                 dpll |= DPLLB_MODE_DAC_SERIAL;
7975
7976         if (IS_I945G(dev) || IS_I945GM(dev) || IS_G33(dev)) {
7977                 dpll |= (crtc_state->pixel_multiplier - 1)
7978                         << SDVO_MULTIPLIER_SHIFT_HIRES;
7979         }
7980
7981         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_SDVO) ||
7982             intel_crtc_has_type(crtc_state, INTEL_OUTPUT_HDMI))
7983                 dpll |= DPLL_SDVO_HIGH_SPEED;
7984
7985         if (intel_crtc_has_dp_encoder(crtc_state))
7986                 dpll |= DPLL_SDVO_HIGH_SPEED;
7987
7988         /* compute bitmask from p1 value */
7989         if (IS_PINEVIEW(dev))
7990                 dpll |= (1 << (clock->p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT_PINEVIEW;
7991         else {
7992                 dpll |= (1 << (clock->p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT;
7993                 if (IS_G4X(dev) && reduced_clock)
7994                         dpll |= (1 << (reduced_clock->p1 - 1)) << DPLL_FPA1_P1_POST_DIV_SHIFT;
7995         }
7996         switch (clock->p2) {
7997         case 5:
7998                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_5;
7999                 break;
8000         case 7:
8001                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_7;
8002                 break;
8003         case 10:
8004                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_10;
8005                 break;
8006         case 14:
8007                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_14;
8008                 break;
8009         }
8010         if (INTEL_INFO(dev)->gen >= 4)
8011                 dpll |= (6 << PLL_LOAD_PULSE_PHASE_SHIFT);
8012
8013         if (crtc_state->sdvo_tv_clock)
8014                 dpll |= PLL_REF_INPUT_TVCLKINBC;
8015         else if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS) &&
8016                  intel_panel_use_ssc(dev_priv))
8017                 dpll |= PLLB_REF_INPUT_SPREADSPECTRUMIN;
8018         else
8019                 dpll |= PLL_REF_INPUT_DREFCLK;
8020
8021         dpll |= DPLL_VCO_ENABLE;
8022         crtc_state->dpll_hw_state.dpll = dpll;
8023
8024         if (INTEL_INFO(dev)->gen >= 4) {
8025                 u32 dpll_md = (crtc_state->pixel_multiplier - 1)
8026                         << DPLL_MD_UDI_MULTIPLIER_SHIFT;
8027                 crtc_state->dpll_hw_state.dpll_md = dpll_md;
8028         }
8029 }
8030
8031 static void i8xx_compute_dpll(struct intel_crtc *crtc,
8032                               struct intel_crtc_state *crtc_state,
8033                               struct dpll *reduced_clock)
8034 {
8035         struct drm_device *dev = crtc->base.dev;
8036         struct drm_i915_private *dev_priv = to_i915(dev);
8037         u32 dpll;
8038         struct dpll *clock = &crtc_state->dpll;
8039
8040         i9xx_update_pll_dividers(crtc, crtc_state, reduced_clock);
8041
8042         dpll = DPLL_VGA_MODE_DIS;
8043
8044         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
8045                 dpll |= (1 << (clock->p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT;
8046         } else {
8047                 if (clock->p1 == 2)
8048                         dpll |= PLL_P1_DIVIDE_BY_TWO;
8049                 else
8050                         dpll |= (clock->p1 - 2) << DPLL_FPA01_P1_POST_DIV_SHIFT;
8051                 if (clock->p2 == 4)
8052                         dpll |= PLL_P2_DIVIDE_BY_4;
8053         }
8054
8055         if (!IS_I830(dev) && intel_crtc_has_type(crtc_state, INTEL_OUTPUT_DVO))
8056                 dpll |= DPLL_DVO_2X_MODE;
8057
8058         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS) &&
8059             intel_panel_use_ssc(dev_priv))
8060                 dpll |= PLLB_REF_INPUT_SPREADSPECTRUMIN;
8061         else
8062                 dpll |= PLL_REF_INPUT_DREFCLK;
8063
8064         dpll |= DPLL_VCO_ENABLE;
8065         crtc_state->dpll_hw_state.dpll = dpll;
8066 }
8067
8068 static void intel_set_pipe_timings(struct intel_crtc *intel_crtc)
8069 {
8070         struct drm_device *dev = intel_crtc->base.dev;
8071         struct drm_i915_private *dev_priv = to_i915(dev);
8072         enum pipe pipe = intel_crtc->pipe;
8073         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
8074         const struct drm_display_mode *adjusted_mode = &intel_crtc->config->base.adjusted_mode;
8075         uint32_t crtc_vtotal, crtc_vblank_end;
8076         int vsyncshift = 0;
8077
8078         /* We need to be careful not to changed the adjusted mode, for otherwise
8079          * the hw state checker will get angry at the mismatch. */
8080         crtc_vtotal = adjusted_mode->crtc_vtotal;
8081         crtc_vblank_end = adjusted_mode->crtc_vblank_end;
8082
8083         if (adjusted_mode->flags & DRM_MODE_FLAG_INTERLACE) {
8084                 /* the chip adds 2 halflines automatically */
8085                 crtc_vtotal -= 1;
8086                 crtc_vblank_end -= 1;
8087
8088                 if (intel_crtc_has_type(intel_crtc->config, INTEL_OUTPUT_SDVO))
8089                         vsyncshift = (adjusted_mode->crtc_htotal - 1) / 2;
8090                 else
8091                         vsyncshift = adjusted_mode->crtc_hsync_start -
8092                                 adjusted_mode->crtc_htotal / 2;
8093                 if (vsyncshift < 0)
8094                         vsyncshift += adjusted_mode->crtc_htotal;
8095         }
8096
8097         if (INTEL_INFO(dev)->gen > 3)
8098                 I915_WRITE(VSYNCSHIFT(cpu_transcoder), vsyncshift);
8099
8100         I915_WRITE(HTOTAL(cpu_transcoder),
8101                    (adjusted_mode->crtc_hdisplay - 1) |
8102                    ((adjusted_mode->crtc_htotal - 1) << 16));
8103         I915_WRITE(HBLANK(cpu_transcoder),
8104                    (adjusted_mode->crtc_hblank_start - 1) |
8105                    ((adjusted_mode->crtc_hblank_end - 1) << 16));
8106         I915_WRITE(HSYNC(cpu_transcoder),
8107                    (adjusted_mode->crtc_hsync_start - 1) |
8108                    ((adjusted_mode->crtc_hsync_end - 1) << 16));
8109
8110         I915_WRITE(VTOTAL(cpu_transcoder),
8111                    (adjusted_mode->crtc_vdisplay - 1) |
8112                    ((crtc_vtotal - 1) << 16));
8113         I915_WRITE(VBLANK(cpu_transcoder),
8114                    (adjusted_mode->crtc_vblank_start - 1) |
8115                    ((crtc_vblank_end - 1) << 16));
8116         I915_WRITE(VSYNC(cpu_transcoder),
8117                    (adjusted_mode->crtc_vsync_start - 1) |
8118                    ((adjusted_mode->crtc_vsync_end - 1) << 16));
8119
8120         /* Workaround: when the EDP input selection is B, the VTOTAL_B must be
8121          * programmed with the VTOTAL_EDP value. Same for VTOTAL_C. This is
8122          * documented on the DDI_FUNC_CTL register description, EDP Input Select
8123          * bits. */
8124         if (IS_HASWELL(dev) && cpu_transcoder == TRANSCODER_EDP &&
8125             (pipe == PIPE_B || pipe == PIPE_C))
8126                 I915_WRITE(VTOTAL(pipe), I915_READ(VTOTAL(cpu_transcoder)));
8127
8128 }
8129
8130 static void intel_set_pipe_src_size(struct intel_crtc *intel_crtc)
8131 {
8132         struct drm_device *dev = intel_crtc->base.dev;
8133         struct drm_i915_private *dev_priv = to_i915(dev);
8134         enum pipe pipe = intel_crtc->pipe;
8135
8136         /* pipesrc controls the size that is scaled from, which should
8137          * always be the user's requested size.
8138          */
8139         I915_WRITE(PIPESRC(pipe),
8140                    ((intel_crtc->config->pipe_src_w - 1) << 16) |
8141                    (intel_crtc->config->pipe_src_h - 1));
8142 }
8143
8144 static void intel_get_pipe_timings(struct intel_crtc *crtc,
8145                                    struct intel_crtc_state *pipe_config)
8146 {
8147         struct drm_device *dev = crtc->base.dev;
8148         struct drm_i915_private *dev_priv = to_i915(dev);
8149         enum transcoder cpu_transcoder = pipe_config->cpu_transcoder;
8150         uint32_t tmp;
8151
8152         tmp = I915_READ(HTOTAL(cpu_transcoder));
8153         pipe_config->base.adjusted_mode.crtc_hdisplay = (tmp & 0xffff) + 1;
8154         pipe_config->base.adjusted_mode.crtc_htotal = ((tmp >> 16) & 0xffff) + 1;
8155         tmp = I915_READ(HBLANK(cpu_transcoder));
8156         pipe_config->base.adjusted_mode.crtc_hblank_start = (tmp & 0xffff) + 1;
8157         pipe_config->base.adjusted_mode.crtc_hblank_end = ((tmp >> 16) & 0xffff) + 1;
8158         tmp = I915_READ(HSYNC(cpu_transcoder));
8159         pipe_config->base.adjusted_mode.crtc_hsync_start = (tmp & 0xffff) + 1;
8160         pipe_config->base.adjusted_mode.crtc_hsync_end = ((tmp >> 16) & 0xffff) + 1;
8161
8162         tmp = I915_READ(VTOTAL(cpu_transcoder));
8163         pipe_config->base.adjusted_mode.crtc_vdisplay = (tmp & 0xffff) + 1;
8164         pipe_config->base.adjusted_mode.crtc_vtotal = ((tmp >> 16) & 0xffff) + 1;
8165         tmp = I915_READ(VBLANK(cpu_transcoder));
8166         pipe_config->base.adjusted_mode.crtc_vblank_start = (tmp & 0xffff) + 1;
8167         pipe_config->base.adjusted_mode.crtc_vblank_end = ((tmp >> 16) & 0xffff) + 1;
8168         tmp = I915_READ(VSYNC(cpu_transcoder));
8169         pipe_config->base.adjusted_mode.crtc_vsync_start = (tmp & 0xffff) + 1;
8170         pipe_config->base.adjusted_mode.crtc_vsync_end = ((tmp >> 16) & 0xffff) + 1;
8171
8172         if (I915_READ(PIPECONF(cpu_transcoder)) & PIPECONF_INTERLACE_MASK) {
8173                 pipe_config->base.adjusted_mode.flags |= DRM_MODE_FLAG_INTERLACE;
8174                 pipe_config->base.adjusted_mode.crtc_vtotal += 1;
8175                 pipe_config->base.adjusted_mode.crtc_vblank_end += 1;
8176         }
8177 }
8178
8179 static void intel_get_pipe_src_size(struct intel_crtc *crtc,
8180                                     struct intel_crtc_state *pipe_config)
8181 {
8182         struct drm_device *dev = crtc->base.dev;
8183         struct drm_i915_private *dev_priv = to_i915(dev);
8184         u32 tmp;
8185
8186         tmp = I915_READ(PIPESRC(crtc->pipe));
8187         pipe_config->pipe_src_h = (tmp & 0xffff) + 1;
8188         pipe_config->pipe_src_w = ((tmp >> 16) & 0xffff) + 1;
8189
8190         pipe_config->base.mode.vdisplay = pipe_config->pipe_src_h;
8191         pipe_config->base.mode.hdisplay = pipe_config->pipe_src_w;
8192 }
8193
8194 void intel_mode_from_pipe_config(struct drm_display_mode *mode,
8195                                  struct intel_crtc_state *pipe_config)
8196 {
8197         mode->hdisplay = pipe_config->base.adjusted_mode.crtc_hdisplay;
8198         mode->htotal = pipe_config->base.adjusted_mode.crtc_htotal;
8199         mode->hsync_start = pipe_config->base.adjusted_mode.crtc_hsync_start;
8200         mode->hsync_end = pipe_config->base.adjusted_mode.crtc_hsync_end;
8201
8202         mode->vdisplay = pipe_config->base.adjusted_mode.crtc_vdisplay;
8203         mode->vtotal = pipe_config->base.adjusted_mode.crtc_vtotal;
8204         mode->vsync_start = pipe_config->base.adjusted_mode.crtc_vsync_start;
8205         mode->vsync_end = pipe_config->base.adjusted_mode.crtc_vsync_end;
8206
8207         mode->flags = pipe_config->base.adjusted_mode.flags;
8208         mode->type = DRM_MODE_TYPE_DRIVER;
8209
8210         mode->clock = pipe_config->base.adjusted_mode.crtc_clock;
8211         mode->flags |= pipe_config->base.adjusted_mode.flags;
8212
8213         mode->hsync = drm_mode_hsync(mode);
8214         mode->vrefresh = drm_mode_vrefresh(mode);
8215         drm_mode_set_name(mode);
8216 }
8217
8218 static void i9xx_set_pipeconf(struct intel_crtc *intel_crtc)
8219 {
8220         struct drm_device *dev = intel_crtc->base.dev;
8221         struct drm_i915_private *dev_priv = to_i915(dev);
8222         uint32_t pipeconf;
8223
8224         pipeconf = 0;
8225
8226         if ((intel_crtc->pipe == PIPE_A && dev_priv->quirks & QUIRK_PIPEA_FORCE) ||
8227             (intel_crtc->pipe == PIPE_B && dev_priv->quirks & QUIRK_PIPEB_FORCE))
8228                 pipeconf |= I915_READ(PIPECONF(intel_crtc->pipe)) & PIPECONF_ENABLE;
8229
8230         if (intel_crtc->config->double_wide)
8231                 pipeconf |= PIPECONF_DOUBLE_WIDE;
8232
8233         /* only g4x and later have fancy bpc/dither controls */
8234         if (IS_G4X(dev) || IS_VALLEYVIEW(dev) || IS_CHERRYVIEW(dev)) {
8235                 /* Bspec claims that we can't use dithering for 30bpp pipes. */
8236                 if (intel_crtc->config->dither && intel_crtc->config->pipe_bpp != 30)
8237                         pipeconf |= PIPECONF_DITHER_EN |
8238                                     PIPECONF_DITHER_TYPE_SP;
8239
8240                 switch (intel_crtc->config->pipe_bpp) {
8241                 case 18:
8242                         pipeconf |= PIPECONF_6BPC;
8243                         break;
8244                 case 24:
8245                         pipeconf |= PIPECONF_8BPC;
8246                         break;
8247                 case 30:
8248                         pipeconf |= PIPECONF_10BPC;
8249                         break;
8250                 default:
8251                         /* Case prevented by intel_choose_pipe_bpp_dither. */
8252                         BUG();
8253                 }
8254         }
8255
8256         if (HAS_PIPE_CXSR(dev)) {
8257                 if (intel_crtc->lowfreq_avail) {
8258                         DRM_DEBUG_KMS("enabling CxSR downclocking\n");
8259                         pipeconf |= PIPECONF_CXSR_DOWNCLOCK;
8260                 } else {
8261                         DRM_DEBUG_KMS("disabling CxSR downclocking\n");
8262                 }
8263         }
8264
8265         if (intel_crtc->config->base.adjusted_mode.flags & DRM_MODE_FLAG_INTERLACE) {
8266                 if (INTEL_INFO(dev)->gen < 4 ||
8267                     intel_crtc_has_type(intel_crtc->config, INTEL_OUTPUT_SDVO))
8268                         pipeconf |= PIPECONF_INTERLACE_W_FIELD_INDICATION;
8269                 else
8270                         pipeconf |= PIPECONF_INTERLACE_W_SYNC_SHIFT;
8271         } else
8272                 pipeconf |= PIPECONF_PROGRESSIVE;
8273
8274         if ((IS_VALLEYVIEW(dev) || IS_CHERRYVIEW(dev)) &&
8275              intel_crtc->config->limited_color_range)
8276                 pipeconf |= PIPECONF_COLOR_RANGE_SELECT;
8277
8278         I915_WRITE(PIPECONF(intel_crtc->pipe), pipeconf);
8279         POSTING_READ(PIPECONF(intel_crtc->pipe));
8280 }
8281
8282 static int i8xx_crtc_compute_clock(struct intel_crtc *crtc,
8283                                    struct intel_crtc_state *crtc_state)
8284 {
8285         struct drm_device *dev = crtc->base.dev;
8286         struct drm_i915_private *dev_priv = to_i915(dev);
8287         const struct intel_limit *limit;
8288         int refclk = 48000;
8289
8290         memset(&crtc_state->dpll_hw_state, 0,
8291                sizeof(crtc_state->dpll_hw_state));
8292
8293         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
8294                 if (intel_panel_use_ssc(dev_priv)) {
8295                         refclk = dev_priv->vbt.lvds_ssc_freq;
8296                         DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n", refclk);
8297                 }
8298
8299                 limit = &intel_limits_i8xx_lvds;
8300         } else if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_DVO)) {
8301                 limit = &intel_limits_i8xx_dvo;
8302         } else {
8303                 limit = &intel_limits_i8xx_dac;
8304         }
8305
8306         if (!crtc_state->clock_set &&
8307             !i9xx_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
8308                                  refclk, NULL, &crtc_state->dpll)) {
8309                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
8310                 return -EINVAL;
8311         }
8312
8313         i8xx_compute_dpll(crtc, crtc_state, NULL);
8314
8315         return 0;
8316 }
8317
8318 static int g4x_crtc_compute_clock(struct intel_crtc *crtc,
8319                                   struct intel_crtc_state *crtc_state)
8320 {
8321         struct drm_device *dev = crtc->base.dev;
8322         struct drm_i915_private *dev_priv = to_i915(dev);
8323         const struct intel_limit *limit;
8324         int refclk = 96000;
8325
8326         memset(&crtc_state->dpll_hw_state, 0,
8327                sizeof(crtc_state->dpll_hw_state));
8328
8329         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
8330                 if (intel_panel_use_ssc(dev_priv)) {
8331                         refclk = dev_priv->vbt.lvds_ssc_freq;
8332                         DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n", refclk);
8333                 }
8334
8335                 if (intel_is_dual_link_lvds(dev))
8336                         limit = &intel_limits_g4x_dual_channel_lvds;
8337                 else
8338                         limit = &intel_limits_g4x_single_channel_lvds;
8339         } else if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_HDMI) ||
8340                    intel_crtc_has_type(crtc_state, INTEL_OUTPUT_ANALOG)) {
8341                 limit = &intel_limits_g4x_hdmi;
8342         } else if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_SDVO)) {
8343                 limit = &intel_limits_g4x_sdvo;
8344         } else {
8345                 /* The option is for other outputs */
8346                 limit = &intel_limits_i9xx_sdvo;
8347         }
8348
8349         if (!crtc_state->clock_set &&
8350             !g4x_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
8351                                 refclk, NULL, &crtc_state->dpll)) {
8352                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
8353                 return -EINVAL;
8354         }
8355
8356         i9xx_compute_dpll(crtc, crtc_state, NULL);
8357
8358         return 0;
8359 }
8360
8361 static int pnv_crtc_compute_clock(struct intel_crtc *crtc,
8362                                   struct intel_crtc_state *crtc_state)
8363 {
8364         struct drm_device *dev = crtc->base.dev;
8365         struct drm_i915_private *dev_priv = to_i915(dev);
8366         const struct intel_limit *limit;
8367         int refclk = 96000;
8368
8369         memset(&crtc_state->dpll_hw_state, 0,
8370                sizeof(crtc_state->dpll_hw_state));
8371
8372         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
8373                 if (intel_panel_use_ssc(dev_priv)) {
8374                         refclk = dev_priv->vbt.lvds_ssc_freq;
8375                         DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n", refclk);
8376                 }
8377
8378                 limit = &intel_limits_pineview_lvds;
8379         } else {
8380                 limit = &intel_limits_pineview_sdvo;
8381         }
8382
8383         if (!crtc_state->clock_set &&
8384             !pnv_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
8385                                 refclk, NULL, &crtc_state->dpll)) {
8386                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
8387                 return -EINVAL;
8388         }
8389
8390         i9xx_compute_dpll(crtc, crtc_state, NULL);
8391
8392         return 0;
8393 }
8394
8395 static int i9xx_crtc_compute_clock(struct intel_crtc *crtc,
8396                                    struct intel_crtc_state *crtc_state)
8397 {
8398         struct drm_device *dev = crtc->base.dev;
8399         struct drm_i915_private *dev_priv = to_i915(dev);
8400         const struct intel_limit *limit;
8401         int refclk = 96000;
8402
8403         memset(&crtc_state->dpll_hw_state, 0,
8404                sizeof(crtc_state->dpll_hw_state));
8405
8406         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
8407                 if (intel_panel_use_ssc(dev_priv)) {
8408                         refclk = dev_priv->vbt.lvds_ssc_freq;
8409                         DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n", refclk);
8410                 }
8411
8412                 limit = &intel_limits_i9xx_lvds;
8413         } else {
8414                 limit = &intel_limits_i9xx_sdvo;
8415         }
8416
8417         if (!crtc_state->clock_set &&
8418             !i9xx_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
8419                                  refclk, NULL, &crtc_state->dpll)) {
8420                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
8421                 return -EINVAL;
8422         }
8423
8424         i9xx_compute_dpll(crtc, crtc_state, NULL);
8425
8426         return 0;
8427 }
8428
8429 static int chv_crtc_compute_clock(struct intel_crtc *crtc,
8430                                   struct intel_crtc_state *crtc_state)
8431 {
8432         int refclk = 100000;
8433         const struct intel_limit *limit = &intel_limits_chv;
8434
8435         memset(&crtc_state->dpll_hw_state, 0,
8436                sizeof(crtc_state->dpll_hw_state));
8437
8438         if (!crtc_state->clock_set &&
8439             !chv_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
8440                                 refclk, NULL, &crtc_state->dpll)) {
8441                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
8442                 return -EINVAL;
8443         }
8444
8445         chv_compute_dpll(crtc, crtc_state);
8446
8447         return 0;
8448 }
8449
8450 static int vlv_crtc_compute_clock(struct intel_crtc *crtc,
8451                                   struct intel_crtc_state *crtc_state)
8452 {
8453         int refclk = 100000;
8454         const struct intel_limit *limit = &intel_limits_vlv;
8455
8456         memset(&crtc_state->dpll_hw_state, 0,
8457                sizeof(crtc_state->dpll_hw_state));
8458
8459         if (!crtc_state->clock_set &&
8460             !vlv_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
8461                                 refclk, NULL, &crtc_state->dpll)) {
8462                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
8463                 return -EINVAL;
8464         }
8465
8466         vlv_compute_dpll(crtc, crtc_state);
8467
8468         return 0;
8469 }
8470
8471 static void i9xx_get_pfit_config(struct intel_crtc *crtc,
8472                                  struct intel_crtc_state *pipe_config)
8473 {
8474         struct drm_device *dev = crtc->base.dev;
8475         struct drm_i915_private *dev_priv = to_i915(dev);
8476         uint32_t tmp;
8477
8478         if (INTEL_INFO(dev)->gen <= 3 && (IS_I830(dev) || !IS_MOBILE(dev)))
8479                 return;
8480
8481         tmp = I915_READ(PFIT_CONTROL);
8482         if (!(tmp & PFIT_ENABLE))
8483                 return;
8484
8485         /* Check whether the pfit is attached to our pipe. */
8486         if (INTEL_INFO(dev)->gen < 4) {
8487                 if (crtc->pipe != PIPE_B)
8488                         return;
8489         } else {
8490                 if ((tmp & PFIT_PIPE_MASK) != (crtc->pipe << PFIT_PIPE_SHIFT))
8491                         return;
8492         }
8493
8494         pipe_config->gmch_pfit.control = tmp;
8495         pipe_config->gmch_pfit.pgm_ratios = I915_READ(PFIT_PGM_RATIOS);
8496 }
8497
8498 static void vlv_crtc_clock_get(struct intel_crtc *crtc,
8499                                struct intel_crtc_state *pipe_config)
8500 {
8501         struct drm_device *dev = crtc->base.dev;
8502         struct drm_i915_private *dev_priv = to_i915(dev);
8503         int pipe = pipe_config->cpu_transcoder;
8504         struct dpll clock;
8505         u32 mdiv;
8506         int refclk = 100000;
8507
8508         /* In case of DSI, DPLL will not be used */
8509         if ((pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE) == 0)
8510                 return;
8511
8512         mutex_lock(&dev_priv->sb_lock);
8513         mdiv = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW3(pipe));
8514         mutex_unlock(&dev_priv->sb_lock);
8515
8516         clock.m1 = (mdiv >> DPIO_M1DIV_SHIFT) & 7;
8517         clock.m2 = mdiv & DPIO_M2DIV_MASK;
8518         clock.n = (mdiv >> DPIO_N_SHIFT) & 0xf;
8519         clock.p1 = (mdiv >> DPIO_P1_SHIFT) & 7;
8520         clock.p2 = (mdiv >> DPIO_P2_SHIFT) & 0x1f;
8521
8522         pipe_config->port_clock = vlv_calc_dpll_params(refclk, &clock);
8523 }
8524
8525 static void
8526 i9xx_get_initial_plane_config(struct intel_crtc *crtc,
8527                               struct intel_initial_plane_config *plane_config)
8528 {
8529         struct drm_device *dev = crtc->base.dev;
8530         struct drm_i915_private *dev_priv = to_i915(dev);
8531         u32 val, base, offset;
8532         int pipe = crtc->pipe, plane = crtc->plane;
8533         int fourcc, pixel_format;
8534         unsigned int aligned_height;
8535         struct drm_framebuffer *fb;
8536         struct intel_framebuffer *intel_fb;
8537
8538         val = I915_READ(DSPCNTR(plane));
8539         if (!(val & DISPLAY_PLANE_ENABLE))
8540                 return;
8541
8542         intel_fb = kzalloc(sizeof(*intel_fb), GFP_KERNEL);
8543         if (!intel_fb) {
8544                 DRM_DEBUG_KMS("failed to alloc fb\n");
8545                 return;
8546         }
8547
8548         fb = &intel_fb->base;
8549
8550         if (INTEL_INFO(dev)->gen >= 4) {
8551                 if (val & DISPPLANE_TILED) {
8552                         plane_config->tiling = I915_TILING_X;
8553                         fb->modifier[0] = I915_FORMAT_MOD_X_TILED;
8554                 }
8555         }
8556
8557         pixel_format = val & DISPPLANE_PIXFORMAT_MASK;
8558         fourcc = i9xx_format_to_fourcc(pixel_format);
8559         fb->pixel_format = fourcc;
8560         fb->bits_per_pixel = drm_format_plane_cpp(fourcc, 0) * 8;
8561
8562         if (INTEL_INFO(dev)->gen >= 4) {
8563                 if (plane_config->tiling)
8564                         offset = I915_READ(DSPTILEOFF(plane));
8565                 else
8566                         offset = I915_READ(DSPLINOFF(plane));
8567                 base = I915_READ(DSPSURF(plane)) & 0xfffff000;
8568         } else {
8569                 base = I915_READ(DSPADDR(plane));
8570         }
8571         plane_config->base = base;
8572
8573         val = I915_READ(PIPESRC(pipe));
8574         fb->width = ((val >> 16) & 0xfff) + 1;
8575         fb->height = ((val >> 0) & 0xfff) + 1;
8576
8577         val = I915_READ(DSPSTRIDE(pipe));
8578         fb->pitches[0] = val & 0xffffffc0;
8579
8580         aligned_height = intel_fb_align_height(dev, fb->height,
8581                                                fb->pixel_format,
8582                                                fb->modifier[0]);
8583
8584         plane_config->size = fb->pitches[0] * aligned_height;
8585
8586         DRM_DEBUG_KMS("pipe/plane %c/%d with fb: size=%dx%d@%d, offset=%x, pitch %d, size 0x%x\n",
8587                       pipe_name(pipe), plane, fb->width, fb->height,
8588                       fb->bits_per_pixel, base, fb->pitches[0],
8589                       plane_config->size);
8590
8591         plane_config->fb = intel_fb;
8592 }
8593
8594 static void chv_crtc_clock_get(struct intel_crtc *crtc,
8595                                struct intel_crtc_state *pipe_config)
8596 {
8597         struct drm_device *dev = crtc->base.dev;
8598         struct drm_i915_private *dev_priv = to_i915(dev);
8599         int pipe = pipe_config->cpu_transcoder;
8600         enum dpio_channel port = vlv_pipe_to_channel(pipe);
8601         struct dpll clock;
8602         u32 cmn_dw13, pll_dw0, pll_dw1, pll_dw2, pll_dw3;
8603         int refclk = 100000;
8604
8605         /* In case of DSI, DPLL will not be used */
8606         if ((pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE) == 0)
8607                 return;
8608
8609         mutex_lock(&dev_priv->sb_lock);
8610         cmn_dw13 = vlv_dpio_read(dev_priv, pipe, CHV_CMN_DW13(port));
8611         pll_dw0 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW0(port));
8612         pll_dw1 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW1(port));
8613         pll_dw2 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW2(port));
8614         pll_dw3 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW3(port));
8615         mutex_unlock(&dev_priv->sb_lock);
8616
8617         clock.m1 = (pll_dw1 & 0x7) == DPIO_CHV_M1_DIV_BY_2 ? 2 : 0;
8618         clock.m2 = (pll_dw0 & 0xff) << 22;
8619         if (pll_dw3 & DPIO_CHV_FRAC_DIV_EN)
8620                 clock.m2 |= pll_dw2 & 0x3fffff;
8621         clock.n = (pll_dw1 >> DPIO_CHV_N_DIV_SHIFT) & 0xf;
8622         clock.p1 = (cmn_dw13 >> DPIO_CHV_P1_DIV_SHIFT) & 0x7;
8623         clock.p2 = (cmn_dw13 >> DPIO_CHV_P2_DIV_SHIFT) & 0x1f;
8624
8625         pipe_config->port_clock = chv_calc_dpll_params(refclk, &clock);
8626 }
8627
8628 static bool i9xx_get_pipe_config(struct intel_crtc *crtc,
8629                                  struct intel_crtc_state *pipe_config)
8630 {
8631         struct drm_device *dev = crtc->base.dev;
8632         struct drm_i915_private *dev_priv = to_i915(dev);
8633         enum intel_display_power_domain power_domain;
8634         uint32_t tmp;
8635         bool ret;
8636
8637         power_domain = POWER_DOMAIN_PIPE(crtc->pipe);
8638         if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
8639                 return false;
8640
8641         pipe_config->cpu_transcoder = (enum transcoder) crtc->pipe;
8642         pipe_config->shared_dpll = NULL;
8643
8644         ret = false;
8645
8646         tmp = I915_READ(PIPECONF(crtc->pipe));
8647         if (!(tmp & PIPECONF_ENABLE))
8648                 goto out;
8649
8650         if (IS_G4X(dev) || IS_VALLEYVIEW(dev) || IS_CHERRYVIEW(dev)) {
8651                 switch (tmp & PIPECONF_BPC_MASK) {
8652                 case PIPECONF_6BPC:
8653                         pipe_config->pipe_bpp = 18;
8654                         break;
8655                 case PIPECONF_8BPC:
8656                         pipe_config->pipe_bpp = 24;
8657                         break;
8658                 case PIPECONF_10BPC:
8659                         pipe_config->pipe_bpp = 30;
8660                         break;
8661                 default:
8662                         break;
8663                 }
8664         }
8665
8666         if ((IS_VALLEYVIEW(dev) || IS_CHERRYVIEW(dev)) &&
8667             (tmp & PIPECONF_COLOR_RANGE_SELECT))
8668                 pipe_config->limited_color_range = true;
8669
8670         if (INTEL_INFO(dev)->gen < 4)
8671                 pipe_config->double_wide = tmp & PIPECONF_DOUBLE_WIDE;
8672
8673         intel_get_pipe_timings(crtc, pipe_config);
8674         intel_get_pipe_src_size(crtc, pipe_config);
8675
8676         i9xx_get_pfit_config(crtc, pipe_config);
8677
8678         if (INTEL_INFO(dev)->gen >= 4) {
8679                 /* No way to read it out on pipes B and C */
8680                 if (IS_CHERRYVIEW(dev) && crtc->pipe != PIPE_A)
8681                         tmp = dev_priv->chv_dpll_md[crtc->pipe];
8682                 else
8683                         tmp = I915_READ(DPLL_MD(crtc->pipe));
8684                 pipe_config->pixel_multiplier =
8685                         ((tmp & DPLL_MD_UDI_MULTIPLIER_MASK)
8686                          >> DPLL_MD_UDI_MULTIPLIER_SHIFT) + 1;
8687                 pipe_config->dpll_hw_state.dpll_md = tmp;
8688         } else if (IS_I945G(dev) || IS_I945GM(dev) || IS_G33(dev)) {
8689                 tmp = I915_READ(DPLL(crtc->pipe));
8690                 pipe_config->pixel_multiplier =
8691                         ((tmp & SDVO_MULTIPLIER_MASK)
8692                          >> SDVO_MULTIPLIER_SHIFT_HIRES) + 1;
8693         } else {
8694                 /* Note that on i915G/GM the pixel multiplier is in the sdvo
8695                  * port and will be fixed up in the encoder->get_config
8696                  * function. */
8697                 pipe_config->pixel_multiplier = 1;
8698         }
8699         pipe_config->dpll_hw_state.dpll = I915_READ(DPLL(crtc->pipe));
8700         if (!IS_VALLEYVIEW(dev) && !IS_CHERRYVIEW(dev)) {
8701                 /*
8702                  * DPLL_DVO_2X_MODE must be enabled for both DPLLs
8703                  * on 830. Filter it out here so that we don't
8704                  * report errors due to that.
8705                  */
8706                 if (IS_I830(dev))
8707                         pipe_config->dpll_hw_state.dpll &= ~DPLL_DVO_2X_MODE;
8708
8709                 pipe_config->dpll_hw_state.fp0 = I915_READ(FP0(crtc->pipe));
8710                 pipe_config->dpll_hw_state.fp1 = I915_READ(FP1(crtc->pipe));
8711         } else {
8712                 /* Mask out read-only status bits. */
8713                 pipe_config->dpll_hw_state.dpll &= ~(DPLL_LOCK_VLV |
8714                                                      DPLL_PORTC_READY_MASK |
8715                                                      DPLL_PORTB_READY_MASK);
8716         }
8717
8718         if (IS_CHERRYVIEW(dev))
8719                 chv_crtc_clock_get(crtc, pipe_config);
8720         else if (IS_VALLEYVIEW(dev))
8721                 vlv_crtc_clock_get(crtc, pipe_config);
8722         else
8723                 i9xx_crtc_clock_get(crtc, pipe_config);
8724
8725         /*
8726          * Normally the dotclock is filled in by the encoder .get_config()
8727          * but in case the pipe is enabled w/o any ports we need a sane
8728          * default.
8729          */
8730         pipe_config->base.adjusted_mode.crtc_clock =
8731                 pipe_config->port_clock / pipe_config->pixel_multiplier;
8732
8733         ret = true;
8734
8735 out:
8736         intel_display_power_put(dev_priv, power_domain);
8737
8738         return ret;
8739 }
8740
8741 static void ironlake_init_pch_refclk(struct drm_device *dev)
8742 {
8743         struct drm_i915_private *dev_priv = to_i915(dev);
8744         struct intel_encoder *encoder;
8745         int i;
8746         u32 val, final;
8747         bool has_lvds = false;
8748         bool has_cpu_edp = false;
8749         bool has_panel = false;
8750         bool has_ck505 = false;
8751         bool can_ssc = false;
8752         bool using_ssc_source = false;
8753
8754         /* We need to take the global config into account */
8755         for_each_intel_encoder(dev, encoder) {
8756                 switch (encoder->type) {
8757                 case INTEL_OUTPUT_LVDS:
8758                         has_panel = true;
8759                         has_lvds = true;
8760                         break;
8761                 case INTEL_OUTPUT_EDP:
8762                         has_panel = true;
8763                         if (enc_to_dig_port(&encoder->base)->port == PORT_A)
8764                                 has_cpu_edp = true;
8765                         break;
8766                 default:
8767                         break;
8768                 }
8769         }
8770
8771         if (HAS_PCH_IBX(dev)) {
8772                 has_ck505 = dev_priv->vbt.display_clock_mode;
8773                 can_ssc = has_ck505;
8774         } else {
8775                 has_ck505 = false;
8776                 can_ssc = true;
8777         }
8778
8779         /* Check if any DPLLs are using the SSC source */
8780         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
8781                 u32 temp = I915_READ(PCH_DPLL(i));
8782
8783                 if (!(temp & DPLL_VCO_ENABLE))
8784                         continue;
8785
8786                 if ((temp & PLL_REF_INPUT_MASK) ==
8787                     PLLB_REF_INPUT_SPREADSPECTRUMIN) {
8788                         using_ssc_source = true;
8789                         break;
8790                 }
8791         }
8792
8793         DRM_DEBUG_KMS("has_panel %d has_lvds %d has_ck505 %d using_ssc_source %d\n",
8794                       has_panel, has_lvds, has_ck505, using_ssc_source);
8795
8796         /* Ironlake: try to setup display ref clock before DPLL
8797          * enabling. This is only under driver's control after
8798          * PCH B stepping, previous chipset stepping should be
8799          * ignoring this setting.
8800          */
8801         val = I915_READ(PCH_DREF_CONTROL);
8802
8803         /* As we must carefully and slowly disable/enable each source in turn,
8804          * compute the final state we want first and check if we need to
8805          * make any changes at all.
8806          */
8807         final = val;
8808         final &= ~DREF_NONSPREAD_SOURCE_MASK;
8809         if (has_ck505)
8810                 final |= DREF_NONSPREAD_CK505_ENABLE;
8811         else
8812                 final |= DREF_NONSPREAD_SOURCE_ENABLE;
8813
8814         final &= ~DREF_SSC_SOURCE_MASK;
8815         final &= ~DREF_CPU_SOURCE_OUTPUT_MASK;
8816         final &= ~DREF_SSC1_ENABLE;
8817
8818         if (has_panel) {
8819                 final |= DREF_SSC_SOURCE_ENABLE;
8820
8821                 if (intel_panel_use_ssc(dev_priv) && can_ssc)
8822                         final |= DREF_SSC1_ENABLE;
8823
8824                 if (has_cpu_edp) {
8825                         if (intel_panel_use_ssc(dev_priv) && can_ssc)
8826                                 final |= DREF_CPU_SOURCE_OUTPUT_DOWNSPREAD;
8827                         else
8828                                 final |= DREF_CPU_SOURCE_OUTPUT_NONSPREAD;
8829                 } else
8830                         final |= DREF_CPU_SOURCE_OUTPUT_DISABLE;
8831         } else if (using_ssc_source) {
8832                 final |= DREF_SSC_SOURCE_ENABLE;
8833                 final |= DREF_SSC1_ENABLE;
8834         }
8835
8836         if (final == val)
8837                 return;
8838
8839         /* Always enable nonspread source */
8840         val &= ~DREF_NONSPREAD_SOURCE_MASK;
8841
8842         if (has_ck505)
8843                 val |= DREF_NONSPREAD_CK505_ENABLE;
8844         else
8845                 val |= DREF_NONSPREAD_SOURCE_ENABLE;
8846
8847         if (has_panel) {
8848                 val &= ~DREF_SSC_SOURCE_MASK;
8849                 val |= DREF_SSC_SOURCE_ENABLE;
8850
8851                 /* SSC must be turned on before enabling the CPU output  */
8852                 if (intel_panel_use_ssc(dev_priv) && can_ssc) {
8853                         DRM_DEBUG_KMS("Using SSC on panel\n");
8854                         val |= DREF_SSC1_ENABLE;
8855                 } else
8856                         val &= ~DREF_SSC1_ENABLE;
8857
8858                 /* Get SSC going before enabling the outputs */
8859                 I915_WRITE(PCH_DREF_CONTROL, val);
8860                 POSTING_READ(PCH_DREF_CONTROL);
8861                 udelay(200);
8862
8863                 val &= ~DREF_CPU_SOURCE_OUTPUT_MASK;
8864
8865                 /* Enable CPU source on CPU attached eDP */
8866                 if (has_cpu_edp) {
8867                         if (intel_panel_use_ssc(dev_priv) && can_ssc) {
8868                                 DRM_DEBUG_KMS("Using SSC on eDP\n");
8869                                 val |= DREF_CPU_SOURCE_OUTPUT_DOWNSPREAD;
8870                         } else
8871                                 val |= DREF_CPU_SOURCE_OUTPUT_NONSPREAD;
8872                 } else
8873                         val |= DREF_CPU_SOURCE_OUTPUT_DISABLE;
8874
8875                 I915_WRITE(PCH_DREF_CONTROL, val);
8876                 POSTING_READ(PCH_DREF_CONTROL);
8877                 udelay(200);
8878         } else {
8879                 DRM_DEBUG_KMS("Disabling CPU source output\n");
8880
8881                 val &= ~DREF_CPU_SOURCE_OUTPUT_MASK;
8882
8883                 /* Turn off CPU output */
8884                 val |= DREF_CPU_SOURCE_OUTPUT_DISABLE;
8885
8886                 I915_WRITE(PCH_DREF_CONTROL, val);
8887                 POSTING_READ(PCH_DREF_CONTROL);
8888                 udelay(200);
8889
8890                 if (!using_ssc_source) {
8891                         DRM_DEBUG_KMS("Disabling SSC source\n");
8892
8893                         /* Turn off the SSC source */
8894                         val &= ~DREF_SSC_SOURCE_MASK;
8895                         val |= DREF_SSC_SOURCE_DISABLE;
8896
8897                         /* Turn off SSC1 */
8898                         val &= ~DREF_SSC1_ENABLE;
8899
8900                         I915_WRITE(PCH_DREF_CONTROL, val);
8901                         POSTING_READ(PCH_DREF_CONTROL);
8902                         udelay(200);
8903                 }
8904         }
8905
8906         BUG_ON(val != final);
8907 }
8908
8909 static void lpt_reset_fdi_mphy(struct drm_i915_private *dev_priv)
8910 {
8911         uint32_t tmp;
8912
8913         tmp = I915_READ(SOUTH_CHICKEN2);
8914         tmp |= FDI_MPHY_IOSFSB_RESET_CTL;
8915         I915_WRITE(SOUTH_CHICKEN2, tmp);
8916
8917         if (wait_for_us(I915_READ(SOUTH_CHICKEN2) &
8918                         FDI_MPHY_IOSFSB_RESET_STATUS, 100))
8919                 DRM_ERROR("FDI mPHY reset assert timeout\n");
8920
8921         tmp = I915_READ(SOUTH_CHICKEN2);
8922         tmp &= ~FDI_MPHY_IOSFSB_RESET_CTL;
8923         I915_WRITE(SOUTH_CHICKEN2, tmp);
8924
8925         if (wait_for_us((I915_READ(SOUTH_CHICKEN2) &
8926                          FDI_MPHY_IOSFSB_RESET_STATUS) == 0, 100))
8927                 DRM_ERROR("FDI mPHY reset de-assert timeout\n");
8928 }
8929
8930 /* WaMPhyProgramming:hsw */
8931 static void lpt_program_fdi_mphy(struct drm_i915_private *dev_priv)
8932 {
8933         uint32_t tmp;
8934
8935         tmp = intel_sbi_read(dev_priv, 0x8008, SBI_MPHY);
8936         tmp &= ~(0xFF << 24);
8937         tmp |= (0x12 << 24);
8938         intel_sbi_write(dev_priv, 0x8008, tmp, SBI_MPHY);
8939
8940         tmp = intel_sbi_read(dev_priv, 0x2008, SBI_MPHY);
8941         tmp |= (1 << 11);
8942         intel_sbi_write(dev_priv, 0x2008, tmp, SBI_MPHY);
8943
8944         tmp = intel_sbi_read(dev_priv, 0x2108, SBI_MPHY);
8945         tmp |= (1 << 11);
8946         intel_sbi_write(dev_priv, 0x2108, tmp, SBI_MPHY);
8947
8948         tmp = intel_sbi_read(dev_priv, 0x206C, SBI_MPHY);
8949         tmp |= (1 << 24) | (1 << 21) | (1 << 18);
8950         intel_sbi_write(dev_priv, 0x206C, tmp, SBI_MPHY);
8951
8952         tmp = intel_sbi_read(dev_priv, 0x216C, SBI_MPHY);
8953         tmp |= (1 << 24) | (1 << 21) | (1 << 18);
8954         intel_sbi_write(dev_priv, 0x216C, tmp, SBI_MPHY);
8955
8956         tmp = intel_sbi_read(dev_priv, 0x2080, SBI_MPHY);
8957         tmp &= ~(7 << 13);
8958         tmp |= (5 << 13);
8959         intel_sbi_write(dev_priv, 0x2080, tmp, SBI_MPHY);
8960
8961         tmp = intel_sbi_read(dev_priv, 0x2180, SBI_MPHY);
8962         tmp &= ~(7 << 13);
8963         tmp |= (5 << 13);
8964         intel_sbi_write(dev_priv, 0x2180, tmp, SBI_MPHY);
8965
8966         tmp = intel_sbi_read(dev_priv, 0x208C, SBI_MPHY);
8967         tmp &= ~0xFF;
8968         tmp |= 0x1C;
8969         intel_sbi_write(dev_priv, 0x208C, tmp, SBI_MPHY);
8970
8971         tmp = intel_sbi_read(dev_priv, 0x218C, SBI_MPHY);
8972         tmp &= ~0xFF;
8973         tmp |= 0x1C;
8974         intel_sbi_write(dev_priv, 0x218C, tmp, SBI_MPHY);
8975
8976         tmp = intel_sbi_read(dev_priv, 0x2098, SBI_MPHY);
8977         tmp &= ~(0xFF << 16);
8978         tmp |= (0x1C << 16);
8979         intel_sbi_write(dev_priv, 0x2098, tmp, SBI_MPHY);
8980
8981         tmp = intel_sbi_read(dev_priv, 0x2198, SBI_MPHY);
8982         tmp &= ~(0xFF << 16);
8983         tmp |= (0x1C << 16);
8984         intel_sbi_write(dev_priv, 0x2198, tmp, SBI_MPHY);
8985
8986         tmp = intel_sbi_read(dev_priv, 0x20C4, SBI_MPHY);
8987         tmp |= (1 << 27);
8988         intel_sbi_write(dev_priv, 0x20C4, tmp, SBI_MPHY);
8989
8990         tmp = intel_sbi_read(dev_priv, 0x21C4, SBI_MPHY);
8991         tmp |= (1 << 27);
8992         intel_sbi_write(dev_priv, 0x21C4, tmp, SBI_MPHY);
8993
8994         tmp = intel_sbi_read(dev_priv, 0x20EC, SBI_MPHY);
8995         tmp &= ~(0xF << 28);
8996         tmp |= (4 << 28);
8997         intel_sbi_write(dev_priv, 0x20EC, tmp, SBI_MPHY);
8998
8999         tmp = intel_sbi_read(dev_priv, 0x21EC, SBI_MPHY);
9000         tmp &= ~(0xF << 28);
9001         tmp |= (4 << 28);
9002         intel_sbi_write(dev_priv, 0x21EC, tmp, SBI_MPHY);
9003 }
9004
9005 /* Implements 3 different sequences from BSpec chapter "Display iCLK
9006  * Programming" based on the parameters passed:
9007  * - Sequence to enable CLKOUT_DP
9008  * - Sequence to enable CLKOUT_DP without spread
9009  * - Sequence to enable CLKOUT_DP for FDI usage and configure PCH FDI I/O
9010  */
9011 static void lpt_enable_clkout_dp(struct drm_device *dev, bool with_spread,
9012                                  bool with_fdi)
9013 {
9014         struct drm_i915_private *dev_priv = to_i915(dev);
9015         uint32_t reg, tmp;
9016
9017         if (WARN(with_fdi && !with_spread, "FDI requires downspread\n"))
9018                 with_spread = true;
9019         if (WARN(HAS_PCH_LPT_LP(dev) && with_fdi, "LP PCH doesn't have FDI\n"))
9020                 with_fdi = false;
9021
9022         mutex_lock(&dev_priv->sb_lock);
9023
9024         tmp = intel_sbi_read(dev_priv, SBI_SSCCTL, SBI_ICLK);
9025         tmp &= ~SBI_SSCCTL_DISABLE;
9026         tmp |= SBI_SSCCTL_PATHALT;
9027         intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
9028
9029         udelay(24);
9030
9031         if (with_spread) {
9032                 tmp = intel_sbi_read(dev_priv, SBI_SSCCTL, SBI_ICLK);
9033                 tmp &= ~SBI_SSCCTL_PATHALT;
9034                 intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
9035
9036                 if (with_fdi) {
9037                         lpt_reset_fdi_mphy(dev_priv);
9038                         lpt_program_fdi_mphy(dev_priv);
9039                 }
9040         }
9041
9042         reg = HAS_PCH_LPT_LP(dev) ? SBI_GEN0 : SBI_DBUFF0;
9043         tmp = intel_sbi_read(dev_priv, reg, SBI_ICLK);
9044         tmp |= SBI_GEN0_CFG_BUFFENABLE_DISABLE;
9045         intel_sbi_write(dev_priv, reg, tmp, SBI_ICLK);
9046
9047         mutex_unlock(&dev_priv->sb_lock);
9048 }
9049
9050 /* Sequence to disable CLKOUT_DP */
9051 static void lpt_disable_clkout_dp(struct drm_device *dev)
9052 {
9053         struct drm_i915_private *dev_priv = to_i915(dev);
9054         uint32_t reg, tmp;
9055
9056         mutex_lock(&dev_priv->sb_lock);
9057
9058         reg = HAS_PCH_LPT_LP(dev) ? SBI_GEN0 : SBI_DBUFF0;
9059         tmp = intel_sbi_read(dev_priv, reg, SBI_ICLK);
9060         tmp &= ~SBI_GEN0_CFG_BUFFENABLE_DISABLE;
9061         intel_sbi_write(dev_priv, reg, tmp, SBI_ICLK);
9062
9063         tmp = intel_sbi_read(dev_priv, SBI_SSCCTL, SBI_ICLK);
9064         if (!(tmp & SBI_SSCCTL_DISABLE)) {
9065                 if (!(tmp & SBI_SSCCTL_PATHALT)) {
9066                         tmp |= SBI_SSCCTL_PATHALT;
9067                         intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
9068                         udelay(32);
9069                 }
9070                 tmp |= SBI_SSCCTL_DISABLE;
9071                 intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
9072         }
9073
9074         mutex_unlock(&dev_priv->sb_lock);
9075 }
9076
9077 #define BEND_IDX(steps) ((50 + (steps)) / 5)
9078
9079 static const uint16_t sscdivintphase[] = {
9080         [BEND_IDX( 50)] = 0x3B23,
9081         [BEND_IDX( 45)] = 0x3B23,
9082         [BEND_IDX( 40)] = 0x3C23,
9083         [BEND_IDX( 35)] = 0x3C23,
9084         [BEND_IDX( 30)] = 0x3D23,
9085         [BEND_IDX( 25)] = 0x3D23,
9086         [BEND_IDX( 20)] = 0x3E23,
9087         [BEND_IDX( 15)] = 0x3E23,
9088         [BEND_IDX( 10)] = 0x3F23,
9089         [BEND_IDX(  5)] = 0x3F23,
9090         [BEND_IDX(  0)] = 0x0025,
9091         [BEND_IDX( -5)] = 0x0025,
9092         [BEND_IDX(-10)] = 0x0125,
9093         [BEND_IDX(-15)] = 0x0125,
9094         [BEND_IDX(-20)] = 0x0225,
9095         [BEND_IDX(-25)] = 0x0225,
9096         [BEND_IDX(-30)] = 0x0325,
9097         [BEND_IDX(-35)] = 0x0325,
9098         [BEND_IDX(-40)] = 0x0425,
9099         [BEND_IDX(-45)] = 0x0425,
9100         [BEND_IDX(-50)] = 0x0525,
9101 };
9102
9103 /*
9104  * Bend CLKOUT_DP
9105  * steps -50 to 50 inclusive, in steps of 5
9106  * < 0 slow down the clock, > 0 speed up the clock, 0 == no bend (135MHz)
9107  * change in clock period = -(steps / 10) * 5.787 ps
9108  */
9109 static void lpt_bend_clkout_dp(struct drm_i915_private *dev_priv, int steps)
9110 {
9111         uint32_t tmp;
9112         int idx = BEND_IDX(steps);
9113
9114         if (WARN_ON(steps % 5 != 0))
9115                 return;
9116
9117         if (WARN_ON(idx >= ARRAY_SIZE(sscdivintphase)))
9118                 return;
9119
9120         mutex_lock(&dev_priv->sb_lock);
9121
9122         if (steps % 10 != 0)
9123                 tmp = 0xAAAAAAAB;
9124         else
9125                 tmp = 0x00000000;
9126         intel_sbi_write(dev_priv, SBI_SSCDITHPHASE, tmp, SBI_ICLK);
9127
9128         tmp = intel_sbi_read(dev_priv, SBI_SSCDIVINTPHASE, SBI_ICLK);
9129         tmp &= 0xffff0000;
9130         tmp |= sscdivintphase[idx];
9131         intel_sbi_write(dev_priv, SBI_SSCDIVINTPHASE, tmp, SBI_ICLK);
9132
9133         mutex_unlock(&dev_priv->sb_lock);
9134 }
9135
9136 #undef BEND_IDX
9137
9138 static void lpt_init_pch_refclk(struct drm_device *dev)
9139 {
9140         struct intel_encoder *encoder;
9141         bool has_vga = false;
9142
9143         for_each_intel_encoder(dev, encoder) {
9144                 switch (encoder->type) {
9145                 case INTEL_OUTPUT_ANALOG:
9146                         has_vga = true;
9147                         break;
9148                 default:
9149                         break;
9150                 }
9151         }
9152
9153         if (has_vga) {
9154                 lpt_bend_clkout_dp(to_i915(dev), 0);
9155                 lpt_enable_clkout_dp(dev, true, true);
9156         } else {
9157                 lpt_disable_clkout_dp(dev);
9158         }
9159 }
9160
9161 /*
9162  * Initialize reference clocks when the driver loads
9163  */
9164 void intel_init_pch_refclk(struct drm_device *dev)
9165 {
9166         if (HAS_PCH_IBX(dev) || HAS_PCH_CPT(dev))
9167                 ironlake_init_pch_refclk(dev);
9168         else if (HAS_PCH_LPT(dev))
9169                 lpt_init_pch_refclk(dev);
9170 }
9171
9172 static void ironlake_set_pipeconf(struct drm_crtc *crtc)
9173 {
9174         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
9175         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
9176         int pipe = intel_crtc->pipe;
9177         uint32_t val;
9178
9179         val = 0;
9180
9181         switch (intel_crtc->config->pipe_bpp) {
9182         case 18:
9183                 val |= PIPECONF_6BPC;
9184                 break;
9185         case 24:
9186                 val |= PIPECONF_8BPC;
9187                 break;
9188         case 30:
9189                 val |= PIPECONF_10BPC;
9190                 break;
9191         case 36:
9192                 val |= PIPECONF_12BPC;
9193                 break;
9194         default:
9195                 /* Case prevented by intel_choose_pipe_bpp_dither. */
9196                 BUG();
9197         }
9198
9199         if (intel_crtc->config->dither)
9200                 val |= (PIPECONF_DITHER_EN | PIPECONF_DITHER_TYPE_SP);
9201
9202         if (intel_crtc->config->base.adjusted_mode.flags & DRM_MODE_FLAG_INTERLACE)
9203                 val |= PIPECONF_INTERLACED_ILK;
9204         else
9205                 val |= PIPECONF_PROGRESSIVE;
9206
9207         if (intel_crtc->config->limited_color_range)
9208                 val |= PIPECONF_COLOR_RANGE_SELECT;
9209
9210         I915_WRITE(PIPECONF(pipe), val);
9211         POSTING_READ(PIPECONF(pipe));
9212 }
9213
9214 static void haswell_set_pipeconf(struct drm_crtc *crtc)
9215 {
9216         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
9217         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
9218         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
9219         u32 val = 0;
9220
9221         if (IS_HASWELL(dev_priv) && intel_crtc->config->dither)
9222                 val |= (PIPECONF_DITHER_EN | PIPECONF_DITHER_TYPE_SP);
9223
9224         if (intel_crtc->config->base.adjusted_mode.flags & DRM_MODE_FLAG_INTERLACE)
9225                 val |= PIPECONF_INTERLACED_ILK;
9226         else
9227                 val |= PIPECONF_PROGRESSIVE;
9228
9229         I915_WRITE(PIPECONF(cpu_transcoder), val);
9230         POSTING_READ(PIPECONF(cpu_transcoder));
9231 }
9232
9233 static void haswell_set_pipemisc(struct drm_crtc *crtc)
9234 {
9235         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
9236         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
9237
9238         if (IS_BROADWELL(dev_priv) || INTEL_INFO(dev_priv)->gen >= 9) {
9239                 u32 val = 0;
9240
9241                 switch (intel_crtc->config->pipe_bpp) {
9242                 case 18:
9243                         val |= PIPEMISC_DITHER_6_BPC;
9244                         break;
9245                 case 24:
9246                         val |= PIPEMISC_DITHER_8_BPC;
9247                         break;
9248                 case 30:
9249                         val |= PIPEMISC_DITHER_10_BPC;
9250                         break;
9251                 case 36:
9252                         val |= PIPEMISC_DITHER_12_BPC;
9253                         break;
9254                 default:
9255                         /* Case prevented by pipe_config_set_bpp. */
9256                         BUG();
9257                 }
9258
9259                 if (intel_crtc->config->dither)
9260                         val |= PIPEMISC_DITHER_ENABLE | PIPEMISC_DITHER_TYPE_SP;
9261
9262                 I915_WRITE(PIPEMISC(intel_crtc->pipe), val);
9263         }
9264 }
9265
9266 int ironlake_get_lanes_required(int target_clock, int link_bw, int bpp)
9267 {
9268         /*
9269          * Account for spread spectrum to avoid
9270          * oversubscribing the link. Max center spread
9271          * is 2.5%; use 5% for safety's sake.
9272          */
9273         u32 bps = target_clock * bpp * 21 / 20;
9274         return DIV_ROUND_UP(bps, link_bw * 8);
9275 }
9276
9277 static bool ironlake_needs_fb_cb_tune(struct dpll *dpll, int factor)
9278 {
9279         return i9xx_dpll_compute_m(dpll) < factor * dpll->n;
9280 }
9281
9282 static void ironlake_compute_dpll(struct intel_crtc *intel_crtc,
9283                                   struct intel_crtc_state *crtc_state,
9284                                   struct dpll *reduced_clock)
9285 {
9286         struct drm_crtc *crtc = &intel_crtc->base;
9287         struct drm_device *dev = crtc->dev;
9288         struct drm_i915_private *dev_priv = to_i915(dev);
9289         u32 dpll, fp, fp2;
9290         int factor;
9291
9292         /* Enable autotuning of the PLL clock (if permissible) */
9293         factor = 21;
9294         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
9295                 if ((intel_panel_use_ssc(dev_priv) &&
9296                      dev_priv->vbt.lvds_ssc_freq == 100000) ||
9297                     (HAS_PCH_IBX(dev) && intel_is_dual_link_lvds(dev)))
9298                         factor = 25;
9299         } else if (crtc_state->sdvo_tv_clock)
9300                 factor = 20;
9301
9302         fp = i9xx_dpll_compute_fp(&crtc_state->dpll);
9303
9304         if (ironlake_needs_fb_cb_tune(&crtc_state->dpll, factor))
9305                 fp |= FP_CB_TUNE;
9306
9307         if (reduced_clock) {
9308                 fp2 = i9xx_dpll_compute_fp(reduced_clock);
9309
9310                 if (reduced_clock->m < factor * reduced_clock->n)
9311                         fp2 |= FP_CB_TUNE;
9312         } else {
9313                 fp2 = fp;
9314         }
9315
9316         dpll = 0;
9317
9318         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS))
9319                 dpll |= DPLLB_MODE_LVDS;
9320         else
9321                 dpll |= DPLLB_MODE_DAC_SERIAL;
9322
9323         dpll |= (crtc_state->pixel_multiplier - 1)
9324                 << PLL_REF_SDVO_HDMI_MULTIPLIER_SHIFT;
9325
9326         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_SDVO) ||
9327             intel_crtc_has_type(crtc_state, INTEL_OUTPUT_HDMI))
9328                 dpll |= DPLL_SDVO_HIGH_SPEED;
9329
9330         if (intel_crtc_has_dp_encoder(crtc_state))
9331                 dpll |= DPLL_SDVO_HIGH_SPEED;
9332
9333         /* compute bitmask from p1 value */
9334         dpll |= (1 << (crtc_state->dpll.p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT;
9335         /* also FPA1 */
9336         dpll |= (1 << (crtc_state->dpll.p1 - 1)) << DPLL_FPA1_P1_POST_DIV_SHIFT;
9337
9338         switch (crtc_state->dpll.p2) {
9339         case 5:
9340                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_5;
9341                 break;
9342         case 7:
9343                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_7;
9344                 break;
9345         case 10:
9346                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_10;
9347                 break;
9348         case 14:
9349                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_14;
9350                 break;
9351         }
9352
9353         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS) &&
9354             intel_panel_use_ssc(dev_priv))
9355                 dpll |= PLLB_REF_INPUT_SPREADSPECTRUMIN;
9356         else
9357                 dpll |= PLL_REF_INPUT_DREFCLK;
9358
9359         dpll |= DPLL_VCO_ENABLE;
9360
9361         crtc_state->dpll_hw_state.dpll = dpll;
9362         crtc_state->dpll_hw_state.fp0 = fp;
9363         crtc_state->dpll_hw_state.fp1 = fp2;
9364 }
9365
9366 static int ironlake_crtc_compute_clock(struct intel_crtc *crtc,
9367                                        struct intel_crtc_state *crtc_state)
9368 {
9369         struct drm_device *dev = crtc->base.dev;
9370         struct drm_i915_private *dev_priv = to_i915(dev);
9371         struct dpll reduced_clock;
9372         bool has_reduced_clock = false;
9373         struct intel_shared_dpll *pll;
9374         const struct intel_limit *limit;
9375         int refclk = 120000;
9376
9377         memset(&crtc_state->dpll_hw_state, 0,
9378                sizeof(crtc_state->dpll_hw_state));
9379
9380         crtc->lowfreq_avail = false;
9381
9382         /* CPU eDP is the only output that doesn't need a PCH PLL of its own. */
9383         if (!crtc_state->has_pch_encoder)
9384                 return 0;
9385
9386         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
9387                 if (intel_panel_use_ssc(dev_priv)) {
9388                         DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n",
9389                                       dev_priv->vbt.lvds_ssc_freq);
9390                         refclk = dev_priv->vbt.lvds_ssc_freq;
9391                 }
9392
9393                 if (intel_is_dual_link_lvds(dev)) {
9394                         if (refclk == 100000)
9395                                 limit = &intel_limits_ironlake_dual_lvds_100m;
9396                         else
9397                                 limit = &intel_limits_ironlake_dual_lvds;
9398                 } else {
9399                         if (refclk == 100000)
9400                                 limit = &intel_limits_ironlake_single_lvds_100m;
9401                         else
9402                                 limit = &intel_limits_ironlake_single_lvds;
9403                 }
9404         } else {
9405                 limit = &intel_limits_ironlake_dac;
9406         }
9407
9408         if (!crtc_state->clock_set &&
9409             !g4x_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
9410                                 refclk, NULL, &crtc_state->dpll)) {
9411                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
9412                 return -EINVAL;
9413         }
9414
9415         ironlake_compute_dpll(crtc, crtc_state,
9416                               has_reduced_clock ? &reduced_clock : NULL);
9417
9418         pll = intel_get_shared_dpll(crtc, crtc_state, NULL);
9419         if (pll == NULL) {
9420                 DRM_DEBUG_DRIVER("failed to find PLL for pipe %c\n",
9421                                  pipe_name(crtc->pipe));
9422                 return -EINVAL;
9423         }
9424
9425         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS) &&
9426             has_reduced_clock)
9427                 crtc->lowfreq_avail = true;
9428
9429         return 0;
9430 }
9431
9432 static void intel_pch_transcoder_get_m_n(struct intel_crtc *crtc,
9433                                          struct intel_link_m_n *m_n)
9434 {
9435         struct drm_device *dev = crtc->base.dev;
9436         struct drm_i915_private *dev_priv = to_i915(dev);
9437         enum pipe pipe = crtc->pipe;
9438
9439         m_n->link_m = I915_READ(PCH_TRANS_LINK_M1(pipe));
9440         m_n->link_n = I915_READ(PCH_TRANS_LINK_N1(pipe));
9441         m_n->gmch_m = I915_READ(PCH_TRANS_DATA_M1(pipe))
9442                 & ~TU_SIZE_MASK;
9443         m_n->gmch_n = I915_READ(PCH_TRANS_DATA_N1(pipe));
9444         m_n->tu = ((I915_READ(PCH_TRANS_DATA_M1(pipe))
9445                     & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
9446 }
9447
9448 static void intel_cpu_transcoder_get_m_n(struct intel_crtc *crtc,
9449                                          enum transcoder transcoder,
9450                                          struct intel_link_m_n *m_n,
9451                                          struct intel_link_m_n *m2_n2)
9452 {
9453         struct drm_device *dev = crtc->base.dev;
9454         struct drm_i915_private *dev_priv = to_i915(dev);
9455         enum pipe pipe = crtc->pipe;
9456
9457         if (INTEL_INFO(dev)->gen >= 5) {
9458                 m_n->link_m = I915_READ(PIPE_LINK_M1(transcoder));
9459                 m_n->link_n = I915_READ(PIPE_LINK_N1(transcoder));
9460                 m_n->gmch_m = I915_READ(PIPE_DATA_M1(transcoder))
9461                         & ~TU_SIZE_MASK;
9462                 m_n->gmch_n = I915_READ(PIPE_DATA_N1(transcoder));
9463                 m_n->tu = ((I915_READ(PIPE_DATA_M1(transcoder))
9464                             & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
9465                 /* Read M2_N2 registers only for gen < 8 (M2_N2 available for
9466                  * gen < 8) and if DRRS is supported (to make sure the
9467                  * registers are not unnecessarily read).
9468                  */
9469                 if (m2_n2 && INTEL_INFO(dev)->gen < 8 &&
9470                         crtc->config->has_drrs) {
9471                         m2_n2->link_m = I915_READ(PIPE_LINK_M2(transcoder));
9472                         m2_n2->link_n = I915_READ(PIPE_LINK_N2(transcoder));
9473                         m2_n2->gmch_m = I915_READ(PIPE_DATA_M2(transcoder))
9474                                         & ~TU_SIZE_MASK;
9475                         m2_n2->gmch_n = I915_READ(PIPE_DATA_N2(transcoder));
9476                         m2_n2->tu = ((I915_READ(PIPE_DATA_M2(transcoder))
9477                                         & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
9478                 }
9479         } else {
9480                 m_n->link_m = I915_READ(PIPE_LINK_M_G4X(pipe));
9481                 m_n->link_n = I915_READ(PIPE_LINK_N_G4X(pipe));
9482                 m_n->gmch_m = I915_READ(PIPE_DATA_M_G4X(pipe))
9483                         & ~TU_SIZE_MASK;
9484                 m_n->gmch_n = I915_READ(PIPE_DATA_N_G4X(pipe));
9485                 m_n->tu = ((I915_READ(PIPE_DATA_M_G4X(pipe))
9486                             & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
9487         }
9488 }
9489
9490 void intel_dp_get_m_n(struct intel_crtc *crtc,
9491                       struct intel_crtc_state *pipe_config)
9492 {
9493         if (pipe_config->has_pch_encoder)
9494                 intel_pch_transcoder_get_m_n(crtc, &pipe_config->dp_m_n);
9495         else
9496                 intel_cpu_transcoder_get_m_n(crtc, pipe_config->cpu_transcoder,
9497                                              &pipe_config->dp_m_n,
9498                                              &pipe_config->dp_m2_n2);
9499 }
9500
9501 static void ironlake_get_fdi_m_n_config(struct intel_crtc *crtc,
9502                                         struct intel_crtc_state *pipe_config)
9503 {
9504         intel_cpu_transcoder_get_m_n(crtc, pipe_config->cpu_transcoder,
9505                                      &pipe_config->fdi_m_n, NULL);
9506 }
9507
9508 static void skylake_get_pfit_config(struct intel_crtc *crtc,
9509                                     struct intel_crtc_state *pipe_config)
9510 {
9511         struct drm_device *dev = crtc->base.dev;
9512         struct drm_i915_private *dev_priv = to_i915(dev);
9513         struct intel_crtc_scaler_state *scaler_state = &pipe_config->scaler_state;
9514         uint32_t ps_ctrl = 0;
9515         int id = -1;
9516         int i;
9517
9518         /* find scaler attached to this pipe */
9519         for (i = 0; i < crtc->num_scalers; i++) {
9520                 ps_ctrl = I915_READ(SKL_PS_CTRL(crtc->pipe, i));
9521                 if (ps_ctrl & PS_SCALER_EN && !(ps_ctrl & PS_PLANE_SEL_MASK)) {
9522                         id = i;
9523                         pipe_config->pch_pfit.enabled = true;
9524                         pipe_config->pch_pfit.pos = I915_READ(SKL_PS_WIN_POS(crtc->pipe, i));
9525                         pipe_config->pch_pfit.size = I915_READ(SKL_PS_WIN_SZ(crtc->pipe, i));
9526                         break;
9527                 }
9528         }
9529
9530         scaler_state->scaler_id = id;
9531         if (id >= 0) {
9532                 scaler_state->scaler_users |= (1 << SKL_CRTC_INDEX);
9533         } else {
9534                 scaler_state->scaler_users &= ~(1 << SKL_CRTC_INDEX);
9535         }
9536 }
9537
9538 static void
9539 skylake_get_initial_plane_config(struct intel_crtc *crtc,
9540                                  struct intel_initial_plane_config *plane_config)
9541 {
9542         struct drm_device *dev = crtc->base.dev;
9543         struct drm_i915_private *dev_priv = to_i915(dev);
9544         u32 val, base, offset, stride_mult, tiling;
9545         int pipe = crtc->pipe;
9546         int fourcc, pixel_format;
9547         unsigned int aligned_height;
9548         struct drm_framebuffer *fb;
9549         struct intel_framebuffer *intel_fb;
9550
9551         intel_fb = kzalloc(sizeof(*intel_fb), GFP_KERNEL);
9552         if (!intel_fb) {
9553                 DRM_DEBUG_KMS("failed to alloc fb\n");
9554                 return;
9555         }
9556
9557         fb = &intel_fb->base;
9558
9559         val = I915_READ(PLANE_CTL(pipe, 0));
9560         if (!(val & PLANE_CTL_ENABLE))
9561                 goto error;
9562
9563         pixel_format = val & PLANE_CTL_FORMAT_MASK;
9564         fourcc = skl_format_to_fourcc(pixel_format,
9565                                       val & PLANE_CTL_ORDER_RGBX,
9566                                       val & PLANE_CTL_ALPHA_MASK);
9567         fb->pixel_format = fourcc;
9568         fb->bits_per_pixel = drm_format_plane_cpp(fourcc, 0) * 8;
9569
9570         tiling = val & PLANE_CTL_TILED_MASK;
9571         switch (tiling) {
9572         case PLANE_CTL_TILED_LINEAR:
9573                 fb->modifier[0] = DRM_FORMAT_MOD_NONE;
9574                 break;
9575         case PLANE_CTL_TILED_X:
9576                 plane_config->tiling = I915_TILING_X;
9577                 fb->modifier[0] = I915_FORMAT_MOD_X_TILED;
9578                 break;
9579         case PLANE_CTL_TILED_Y:
9580                 fb->modifier[0] = I915_FORMAT_MOD_Y_TILED;
9581                 break;
9582         case PLANE_CTL_TILED_YF:
9583                 fb->modifier[0] = I915_FORMAT_MOD_Yf_TILED;
9584                 break;
9585         default:
9586                 MISSING_CASE(tiling);
9587                 goto error;
9588         }
9589
9590         base = I915_READ(PLANE_SURF(pipe, 0)) & 0xfffff000;
9591         plane_config->base = base;
9592
9593         offset = I915_READ(PLANE_OFFSET(pipe, 0));
9594
9595         val = I915_READ(PLANE_SIZE(pipe, 0));
9596         fb->height = ((val >> 16) & 0xfff) + 1;
9597         fb->width = ((val >> 0) & 0x1fff) + 1;
9598
9599         val = I915_READ(PLANE_STRIDE(pipe, 0));
9600         stride_mult = intel_fb_stride_alignment(dev_priv, fb->modifier[0],
9601                                                 fb->pixel_format);
9602         fb->pitches[0] = (val & 0x3ff) * stride_mult;
9603
9604         aligned_height = intel_fb_align_height(dev, fb->height,
9605                                                fb->pixel_format,
9606                                                fb->modifier[0]);
9607
9608         plane_config->size = fb->pitches[0] * aligned_height;
9609
9610         DRM_DEBUG_KMS("pipe %c with fb: size=%dx%d@%d, offset=%x, pitch %d, size 0x%x\n",
9611                       pipe_name(pipe), fb->width, fb->height,
9612                       fb->bits_per_pixel, base, fb->pitches[0],
9613                       plane_config->size);
9614
9615         plane_config->fb = intel_fb;
9616         return;
9617
9618 error:
9619         kfree(fb);
9620 }
9621
9622 static void ironlake_get_pfit_config(struct intel_crtc *crtc,
9623                                      struct intel_crtc_state *pipe_config)
9624 {
9625         struct drm_device *dev = crtc->base.dev;
9626         struct drm_i915_private *dev_priv = to_i915(dev);
9627         uint32_t tmp;
9628
9629         tmp = I915_READ(PF_CTL(crtc->pipe));
9630
9631         if (tmp & PF_ENABLE) {
9632                 pipe_config->pch_pfit.enabled = true;
9633                 pipe_config->pch_pfit.pos = I915_READ(PF_WIN_POS(crtc->pipe));
9634                 pipe_config->pch_pfit.size = I915_READ(PF_WIN_SZ(crtc->pipe));
9635
9636                 /* We currently do not free assignements of panel fitters on
9637                  * ivb/hsw (since we don't use the higher upscaling modes which
9638                  * differentiates them) so just WARN about this case for now. */
9639                 if (IS_GEN7(dev)) {
9640                         WARN_ON((tmp & PF_PIPE_SEL_MASK_IVB) !=
9641                                 PF_PIPE_SEL_IVB(crtc->pipe));
9642                 }
9643         }
9644 }
9645
9646 static void
9647 ironlake_get_initial_plane_config(struct intel_crtc *crtc,
9648                                   struct intel_initial_plane_config *plane_config)
9649 {
9650         struct drm_device *dev = crtc->base.dev;
9651         struct drm_i915_private *dev_priv = to_i915(dev);
9652         u32 val, base, offset;
9653         int pipe = crtc->pipe;
9654         int fourcc, pixel_format;
9655         unsigned int aligned_height;
9656         struct drm_framebuffer *fb;
9657         struct intel_framebuffer *intel_fb;
9658
9659         val = I915_READ(DSPCNTR(pipe));
9660         if (!(val & DISPLAY_PLANE_ENABLE))
9661                 return;
9662
9663         intel_fb = kzalloc(sizeof(*intel_fb), GFP_KERNEL);
9664         if (!intel_fb) {
9665                 DRM_DEBUG_KMS("failed to alloc fb\n");
9666                 return;
9667         }
9668
9669         fb = &intel_fb->base;
9670
9671         if (INTEL_INFO(dev)->gen >= 4) {
9672                 if (val & DISPPLANE_TILED) {
9673                         plane_config->tiling = I915_TILING_X;
9674                         fb->modifier[0] = I915_FORMAT_MOD_X_TILED;
9675                 }
9676         }
9677
9678         pixel_format = val & DISPPLANE_PIXFORMAT_MASK;
9679         fourcc = i9xx_format_to_fourcc(pixel_format);
9680         fb->pixel_format = fourcc;
9681         fb->bits_per_pixel = drm_format_plane_cpp(fourcc, 0) * 8;
9682
9683         base = I915_READ(DSPSURF(pipe)) & 0xfffff000;
9684         if (IS_HASWELL(dev) || IS_BROADWELL(dev)) {
9685                 offset = I915_READ(DSPOFFSET(pipe));
9686         } else {
9687                 if (plane_config->tiling)
9688                         offset = I915_READ(DSPTILEOFF(pipe));
9689                 else
9690                         offset = I915_READ(DSPLINOFF(pipe));
9691         }
9692         plane_config->base = base;
9693
9694         val = I915_READ(PIPESRC(pipe));
9695         fb->width = ((val >> 16) & 0xfff) + 1;
9696         fb->height = ((val >> 0) & 0xfff) + 1;
9697
9698         val = I915_READ(DSPSTRIDE(pipe));
9699         fb->pitches[0] = val & 0xffffffc0;
9700
9701         aligned_height = intel_fb_align_height(dev, fb->height,
9702                                                fb->pixel_format,
9703                                                fb->modifier[0]);
9704
9705         plane_config->size = fb->pitches[0] * aligned_height;
9706
9707         DRM_DEBUG_KMS("pipe %c with fb: size=%dx%d@%d, offset=%x, pitch %d, size 0x%x\n",
9708                       pipe_name(pipe), fb->width, fb->height,
9709                       fb->bits_per_pixel, base, fb->pitches[0],
9710                       plane_config->size);
9711
9712         plane_config->fb = intel_fb;
9713 }
9714
9715 static bool ironlake_get_pipe_config(struct intel_crtc *crtc,
9716                                      struct intel_crtc_state *pipe_config)
9717 {
9718         struct drm_device *dev = crtc->base.dev;
9719         struct drm_i915_private *dev_priv = to_i915(dev);
9720         enum intel_display_power_domain power_domain;
9721         uint32_t tmp;
9722         bool ret;
9723
9724         power_domain = POWER_DOMAIN_PIPE(crtc->pipe);
9725         if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
9726                 return false;
9727
9728         pipe_config->cpu_transcoder = (enum transcoder) crtc->pipe;
9729         pipe_config->shared_dpll = NULL;
9730
9731         ret = false;
9732         tmp = I915_READ(PIPECONF(crtc->pipe));
9733         if (!(tmp & PIPECONF_ENABLE))
9734                 goto out;
9735
9736         switch (tmp & PIPECONF_BPC_MASK) {
9737         case PIPECONF_6BPC:
9738                 pipe_config->pipe_bpp = 18;
9739                 break;
9740         case PIPECONF_8BPC:
9741                 pipe_config->pipe_bpp = 24;
9742                 break;
9743         case PIPECONF_10BPC:
9744                 pipe_config->pipe_bpp = 30;
9745                 break;
9746         case PIPECONF_12BPC:
9747                 pipe_config->pipe_bpp = 36;
9748                 break;
9749         default:
9750                 break;
9751         }
9752
9753         if (tmp & PIPECONF_COLOR_RANGE_SELECT)
9754                 pipe_config->limited_color_range = true;
9755
9756         if (I915_READ(PCH_TRANSCONF(crtc->pipe)) & TRANS_ENABLE) {
9757                 struct intel_shared_dpll *pll;
9758                 enum intel_dpll_id pll_id;
9759
9760                 pipe_config->has_pch_encoder = true;
9761
9762                 tmp = I915_READ(FDI_RX_CTL(crtc->pipe));
9763                 pipe_config->fdi_lanes = ((FDI_DP_PORT_WIDTH_MASK & tmp) >>
9764                                           FDI_DP_PORT_WIDTH_SHIFT) + 1;
9765
9766                 ironlake_get_fdi_m_n_config(crtc, pipe_config);
9767
9768                 if (HAS_PCH_IBX(dev_priv)) {
9769                         /*
9770                          * The pipe->pch transcoder and pch transcoder->pll
9771                          * mapping is fixed.
9772                          */
9773                         pll_id = (enum intel_dpll_id) crtc->pipe;
9774                 } else {
9775                         tmp = I915_READ(PCH_DPLL_SEL);
9776                         if (tmp & TRANS_DPLLB_SEL(crtc->pipe))
9777                                 pll_id = DPLL_ID_PCH_PLL_B;
9778                         else
9779                                 pll_id= DPLL_ID_PCH_PLL_A;
9780                 }
9781
9782                 pipe_config->shared_dpll =
9783                         intel_get_shared_dpll_by_id(dev_priv, pll_id);
9784                 pll = pipe_config->shared_dpll;
9785
9786                 WARN_ON(!pll->funcs.get_hw_state(dev_priv, pll,
9787                                                  &pipe_config->dpll_hw_state));
9788
9789                 tmp = pipe_config->dpll_hw_state.dpll;
9790                 pipe_config->pixel_multiplier =
9791                         ((tmp & PLL_REF_SDVO_HDMI_MULTIPLIER_MASK)
9792                          >> PLL_REF_SDVO_HDMI_MULTIPLIER_SHIFT) + 1;
9793
9794                 ironlake_pch_clock_get(crtc, pipe_config);
9795         } else {
9796                 pipe_config->pixel_multiplier = 1;
9797         }
9798
9799         intel_get_pipe_timings(crtc, pipe_config);
9800         intel_get_pipe_src_size(crtc, pipe_config);
9801
9802         ironlake_get_pfit_config(crtc, pipe_config);
9803
9804         ret = true;
9805
9806 out:
9807         intel_display_power_put(dev_priv, power_domain);
9808
9809         return ret;
9810 }
9811
9812 static void assert_can_disable_lcpll(struct drm_i915_private *dev_priv)
9813 {
9814         struct drm_device *dev = &dev_priv->drm;
9815         struct intel_crtc *crtc;
9816
9817         for_each_intel_crtc(dev, crtc)
9818                 I915_STATE_WARN(crtc->active, "CRTC for pipe %c enabled\n",
9819                      pipe_name(crtc->pipe));
9820
9821         I915_STATE_WARN(I915_READ(HSW_PWR_WELL_DRIVER), "Power well on\n");
9822         I915_STATE_WARN(I915_READ(SPLL_CTL) & SPLL_PLL_ENABLE, "SPLL enabled\n");
9823         I915_STATE_WARN(I915_READ(WRPLL_CTL(0)) & WRPLL_PLL_ENABLE, "WRPLL1 enabled\n");
9824         I915_STATE_WARN(I915_READ(WRPLL_CTL(1)) & WRPLL_PLL_ENABLE, "WRPLL2 enabled\n");
9825         I915_STATE_WARN(I915_READ(PP_STATUS(0)) & PP_ON, "Panel power on\n");
9826         I915_STATE_WARN(I915_READ(BLC_PWM_CPU_CTL2) & BLM_PWM_ENABLE,
9827              "CPU PWM1 enabled\n");
9828         if (IS_HASWELL(dev))
9829                 I915_STATE_WARN(I915_READ(HSW_BLC_PWM2_CTL) & BLM_PWM_ENABLE,
9830                      "CPU PWM2 enabled\n");
9831         I915_STATE_WARN(I915_READ(BLC_PWM_PCH_CTL1) & BLM_PCH_PWM_ENABLE,
9832              "PCH PWM1 enabled\n");
9833         I915_STATE_WARN(I915_READ(UTIL_PIN_CTL) & UTIL_PIN_ENABLE,
9834              "Utility pin enabled\n");
9835         I915_STATE_WARN(I915_READ(PCH_GTC_CTL) & PCH_GTC_ENABLE, "PCH GTC enabled\n");
9836
9837         /*
9838          * In theory we can still leave IRQs enabled, as long as only the HPD
9839          * interrupts remain enabled. We used to check for that, but since it's
9840          * gen-specific and since we only disable LCPLL after we fully disable
9841          * the interrupts, the check below should be enough.
9842          */
9843         I915_STATE_WARN(intel_irqs_enabled(dev_priv), "IRQs enabled\n");
9844 }
9845
9846 static uint32_t hsw_read_dcomp(struct drm_i915_private *dev_priv)
9847 {
9848         struct drm_device *dev = &dev_priv->drm;
9849
9850         if (IS_HASWELL(dev))
9851                 return I915_READ(D_COMP_HSW);
9852         else
9853                 return I915_READ(D_COMP_BDW);
9854 }
9855
9856 static void hsw_write_dcomp(struct drm_i915_private *dev_priv, uint32_t val)
9857 {
9858         struct drm_device *dev = &dev_priv->drm;
9859
9860         if (IS_HASWELL(dev)) {
9861                 mutex_lock(&dev_priv->rps.hw_lock);
9862                 if (sandybridge_pcode_write(dev_priv, GEN6_PCODE_WRITE_D_COMP,
9863                                             val))
9864                         DRM_ERROR("Failed to write to D_COMP\n");
9865                 mutex_unlock(&dev_priv->rps.hw_lock);
9866         } else {
9867                 I915_WRITE(D_COMP_BDW, val);
9868                 POSTING_READ(D_COMP_BDW);
9869         }
9870 }
9871
9872 /*
9873  * This function implements pieces of two sequences from BSpec:
9874  * - Sequence for display software to disable LCPLL
9875  * - Sequence for display software to allow package C8+
9876  * The steps implemented here are just the steps that actually touch the LCPLL
9877  * register. Callers should take care of disabling all the display engine
9878  * functions, doing the mode unset, fixing interrupts, etc.
9879  */
9880 static void hsw_disable_lcpll(struct drm_i915_private *dev_priv,
9881                               bool switch_to_fclk, bool allow_power_down)
9882 {
9883         uint32_t val;
9884
9885         assert_can_disable_lcpll(dev_priv);
9886
9887         val = I915_READ(LCPLL_CTL);
9888
9889         if (switch_to_fclk) {
9890                 val |= LCPLL_CD_SOURCE_FCLK;
9891                 I915_WRITE(LCPLL_CTL, val);
9892
9893                 if (wait_for_us(I915_READ(LCPLL_CTL) &
9894                                 LCPLL_CD_SOURCE_FCLK_DONE, 1))
9895                         DRM_ERROR("Switching to FCLK failed\n");
9896
9897                 val = I915_READ(LCPLL_CTL);
9898         }
9899
9900         val |= LCPLL_PLL_DISABLE;
9901         I915_WRITE(LCPLL_CTL, val);
9902         POSTING_READ(LCPLL_CTL);
9903
9904         if (intel_wait_for_register(dev_priv, LCPLL_CTL, LCPLL_PLL_LOCK, 0, 1))
9905                 DRM_ERROR("LCPLL still locked\n");
9906
9907         val = hsw_read_dcomp(dev_priv);
9908         val |= D_COMP_COMP_DISABLE;
9909         hsw_write_dcomp(dev_priv, val);
9910         ndelay(100);
9911
9912         if (wait_for((hsw_read_dcomp(dev_priv) & D_COMP_RCOMP_IN_PROGRESS) == 0,
9913                      1))
9914                 DRM_ERROR("D_COMP RCOMP still in progress\n");
9915
9916         if (allow_power_down) {
9917                 val = I915_READ(LCPLL_CTL);
9918                 val |= LCPLL_POWER_DOWN_ALLOW;
9919                 I915_WRITE(LCPLL_CTL, val);
9920                 POSTING_READ(LCPLL_CTL);
9921         }
9922 }
9923
9924 /*
9925  * Fully restores LCPLL, disallowing power down and switching back to LCPLL
9926  * source.
9927  */
9928 static void hsw_restore_lcpll(struct drm_i915_private *dev_priv)
9929 {
9930         uint32_t val;
9931
9932         val = I915_READ(LCPLL_CTL);
9933
9934         if ((val & (LCPLL_PLL_LOCK | LCPLL_PLL_DISABLE | LCPLL_CD_SOURCE_FCLK |
9935                     LCPLL_POWER_DOWN_ALLOW)) == LCPLL_PLL_LOCK)
9936                 return;
9937
9938         /*
9939          * Make sure we're not on PC8 state before disabling PC8, otherwise
9940          * we'll hang the machine. To prevent PC8 state, just enable force_wake.
9941          */
9942         intel_uncore_forcewake_get(dev_priv, FORCEWAKE_ALL);
9943
9944         if (val & LCPLL_POWER_DOWN_ALLOW) {
9945                 val &= ~LCPLL_POWER_DOWN_ALLOW;
9946                 I915_WRITE(LCPLL_CTL, val);
9947                 POSTING_READ(LCPLL_CTL);
9948         }
9949
9950         val = hsw_read_dcomp(dev_priv);
9951         val |= D_COMP_COMP_FORCE;
9952         val &= ~D_COMP_COMP_DISABLE;
9953         hsw_write_dcomp(dev_priv, val);
9954
9955         val = I915_READ(LCPLL_CTL);
9956         val &= ~LCPLL_PLL_DISABLE;
9957         I915_WRITE(LCPLL_CTL, val);
9958
9959         if (intel_wait_for_register(dev_priv,
9960                                     LCPLL_CTL, LCPLL_PLL_LOCK, LCPLL_PLL_LOCK,
9961                                     5))
9962                 DRM_ERROR("LCPLL not locked yet\n");
9963
9964         if (val & LCPLL_CD_SOURCE_FCLK) {
9965                 val = I915_READ(LCPLL_CTL);
9966                 val &= ~LCPLL_CD_SOURCE_FCLK;
9967                 I915_WRITE(LCPLL_CTL, val);
9968
9969                 if (wait_for_us((I915_READ(LCPLL_CTL) &
9970                                  LCPLL_CD_SOURCE_FCLK_DONE) == 0, 1))
9971                         DRM_ERROR("Switching back to LCPLL failed\n");
9972         }
9973
9974         intel_uncore_forcewake_put(dev_priv, FORCEWAKE_ALL);
9975         intel_update_cdclk(&dev_priv->drm);
9976 }
9977
9978 /*
9979  * Package states C8 and deeper are really deep PC states that can only be
9980  * reached when all the devices on the system allow it, so even if the graphics
9981  * device allows PC8+, it doesn't mean the system will actually get to these
9982  * states. Our driver only allows PC8+ when going into runtime PM.
9983  *
9984  * The requirements for PC8+ are that all the outputs are disabled, the power
9985  * well is disabled and most interrupts are disabled, and these are also
9986  * requirements for runtime PM. When these conditions are met, we manually do
9987  * the other conditions: disable the interrupts, clocks and switch LCPLL refclk
9988  * to Fclk. If we're in PC8+ and we get an non-hotplug interrupt, we can hard
9989  * hang the machine.
9990  *
9991  * When we really reach PC8 or deeper states (not just when we allow it) we lose
9992  * the state of some registers, so when we come back from PC8+ we need to
9993  * restore this state. We don't get into PC8+ if we're not in RC6, so we don't
9994  * need to take care of the registers kept by RC6. Notice that this happens even
9995  * if we don't put the device in PCI D3 state (which is what currently happens
9996  * because of the runtime PM support).
9997  *
9998  * For more, read "Display Sequences for Package C8" on the hardware
9999  * documentation.
10000  */
10001 void hsw_enable_pc8(struct drm_i915_private *dev_priv)
10002 {
10003         struct drm_device *dev = &dev_priv->drm;
10004         uint32_t val;
10005
10006         DRM_DEBUG_KMS("Enabling package C8+\n");
10007
10008         if (HAS_PCH_LPT_LP(dev)) {
10009                 val = I915_READ(SOUTH_DSPCLK_GATE_D);
10010                 val &= ~PCH_LP_PARTITION_LEVEL_DISABLE;
10011                 I915_WRITE(SOUTH_DSPCLK_GATE_D, val);
10012         }
10013
10014         lpt_disable_clkout_dp(dev);
10015         hsw_disable_lcpll(dev_priv, true, true);
10016 }
10017
10018 void hsw_disable_pc8(struct drm_i915_private *dev_priv)
10019 {
10020         struct drm_device *dev = &dev_priv->drm;
10021         uint32_t val;
10022
10023         DRM_DEBUG_KMS("Disabling package C8+\n");
10024
10025         hsw_restore_lcpll(dev_priv);
10026         lpt_init_pch_refclk(dev);
10027
10028         if (HAS_PCH_LPT_LP(dev)) {
10029                 val = I915_READ(SOUTH_DSPCLK_GATE_D);
10030                 val |= PCH_LP_PARTITION_LEVEL_DISABLE;
10031                 I915_WRITE(SOUTH_DSPCLK_GATE_D, val);
10032         }
10033 }
10034
10035 static void bxt_modeset_commit_cdclk(struct drm_atomic_state *old_state)
10036 {
10037         struct drm_device *dev = old_state->dev;
10038         struct intel_atomic_state *old_intel_state =
10039                 to_intel_atomic_state(old_state);
10040         unsigned int req_cdclk = old_intel_state->dev_cdclk;
10041
10042         bxt_set_cdclk(to_i915(dev), req_cdclk);
10043 }
10044
10045 /* compute the max rate for new configuration */
10046 static int ilk_max_pixel_rate(struct drm_atomic_state *state)
10047 {
10048         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
10049         struct drm_i915_private *dev_priv = to_i915(state->dev);
10050         struct drm_crtc *crtc;
10051         struct drm_crtc_state *cstate;
10052         struct intel_crtc_state *crtc_state;
10053         unsigned max_pixel_rate = 0, i;
10054         enum pipe pipe;
10055
10056         memcpy(intel_state->min_pixclk, dev_priv->min_pixclk,
10057                sizeof(intel_state->min_pixclk));
10058
10059         for_each_crtc_in_state(state, crtc, cstate, i) {
10060                 int pixel_rate;
10061
10062                 crtc_state = to_intel_crtc_state(cstate);
10063                 if (!crtc_state->base.enable) {
10064                         intel_state->min_pixclk[i] = 0;
10065                         continue;
10066                 }
10067
10068                 pixel_rate = ilk_pipe_pixel_rate(crtc_state);
10069
10070                 /* pixel rate mustn't exceed 95% of cdclk with IPS on BDW */
10071                 if (IS_BROADWELL(dev_priv) && crtc_state->ips_enabled)
10072                         pixel_rate = DIV_ROUND_UP(pixel_rate * 100, 95);
10073
10074                 intel_state->min_pixclk[i] = pixel_rate;
10075         }
10076
10077         for_each_pipe(dev_priv, pipe)
10078                 max_pixel_rate = max(intel_state->min_pixclk[pipe], max_pixel_rate);
10079
10080         return max_pixel_rate;
10081 }
10082
10083 static void broadwell_set_cdclk(struct drm_device *dev, int cdclk)
10084 {
10085         struct drm_i915_private *dev_priv = to_i915(dev);
10086         uint32_t val, data;
10087         int ret;
10088
10089         if (WARN((I915_READ(LCPLL_CTL) &
10090                   (LCPLL_PLL_DISABLE | LCPLL_PLL_LOCK |
10091                    LCPLL_CD_CLOCK_DISABLE | LCPLL_ROOT_CD_CLOCK_DISABLE |
10092                    LCPLL_CD2X_CLOCK_DISABLE | LCPLL_POWER_DOWN_ALLOW |
10093                    LCPLL_CD_SOURCE_FCLK)) != LCPLL_PLL_LOCK,
10094                  "trying to change cdclk frequency with cdclk not enabled\n"))
10095                 return;
10096
10097         mutex_lock(&dev_priv->rps.hw_lock);
10098         ret = sandybridge_pcode_write(dev_priv,
10099                                       BDW_PCODE_DISPLAY_FREQ_CHANGE_REQ, 0x0);
10100         mutex_unlock(&dev_priv->rps.hw_lock);
10101         if (ret) {
10102                 DRM_ERROR("failed to inform pcode about cdclk change\n");
10103                 return;
10104         }
10105
10106         val = I915_READ(LCPLL_CTL);
10107         val |= LCPLL_CD_SOURCE_FCLK;
10108         I915_WRITE(LCPLL_CTL, val);
10109
10110         if (wait_for_us(I915_READ(LCPLL_CTL) &
10111                         LCPLL_CD_SOURCE_FCLK_DONE, 1))
10112                 DRM_ERROR("Switching to FCLK failed\n");
10113
10114         val = I915_READ(LCPLL_CTL);
10115         val &= ~LCPLL_CLK_FREQ_MASK;
10116
10117         switch (cdclk) {
10118         case 450000:
10119                 val |= LCPLL_CLK_FREQ_450;
10120                 data = 0;
10121                 break;
10122         case 540000:
10123                 val |= LCPLL_CLK_FREQ_54O_BDW;
10124                 data = 1;
10125                 break;
10126         case 337500:
10127                 val |= LCPLL_CLK_FREQ_337_5_BDW;
10128                 data = 2;
10129                 break;
10130         case 675000:
10131                 val |= LCPLL_CLK_FREQ_675_BDW;
10132                 data = 3;
10133                 break;
10134         default:
10135                 WARN(1, "invalid cdclk frequency\n");
10136                 return;
10137         }
10138
10139         I915_WRITE(LCPLL_CTL, val);
10140
10141         val = I915_READ(LCPLL_CTL);
10142         val &= ~LCPLL_CD_SOURCE_FCLK;
10143         I915_WRITE(LCPLL_CTL, val);
10144
10145         if (wait_for_us((I915_READ(LCPLL_CTL) &
10146                         LCPLL_CD_SOURCE_FCLK_DONE) == 0, 1))
10147                 DRM_ERROR("Switching back to LCPLL failed\n");
10148
10149         mutex_lock(&dev_priv->rps.hw_lock);
10150         sandybridge_pcode_write(dev_priv, HSW_PCODE_DE_WRITE_FREQ_REQ, data);
10151         mutex_unlock(&dev_priv->rps.hw_lock);
10152
10153         I915_WRITE(CDCLK_FREQ, DIV_ROUND_CLOSEST(cdclk, 1000) - 1);
10154
10155         intel_update_cdclk(dev);
10156
10157         WARN(cdclk != dev_priv->cdclk_freq,
10158              "cdclk requested %d kHz but got %d kHz\n",
10159              cdclk, dev_priv->cdclk_freq);
10160 }
10161
10162 static int broadwell_calc_cdclk(int max_pixclk)
10163 {
10164         if (max_pixclk > 540000)
10165                 return 675000;
10166         else if (max_pixclk > 450000)
10167                 return 540000;
10168         else if (max_pixclk > 337500)
10169                 return 450000;
10170         else
10171                 return 337500;
10172 }
10173
10174 static int broadwell_modeset_calc_cdclk(struct drm_atomic_state *state)
10175 {
10176         struct drm_i915_private *dev_priv = to_i915(state->dev);
10177         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
10178         int max_pixclk = ilk_max_pixel_rate(state);
10179         int cdclk;
10180
10181         /*
10182          * FIXME should also account for plane ratio
10183          * once 64bpp pixel formats are supported.
10184          */
10185         cdclk = broadwell_calc_cdclk(max_pixclk);
10186
10187         if (cdclk > dev_priv->max_cdclk_freq) {
10188                 DRM_DEBUG_KMS("requested cdclk (%d kHz) exceeds max (%d kHz)\n",
10189                               cdclk, dev_priv->max_cdclk_freq);
10190                 return -EINVAL;
10191         }
10192
10193         intel_state->cdclk = intel_state->dev_cdclk = cdclk;
10194         if (!intel_state->active_crtcs)
10195                 intel_state->dev_cdclk = broadwell_calc_cdclk(0);
10196
10197         return 0;
10198 }
10199
10200 static void broadwell_modeset_commit_cdclk(struct drm_atomic_state *old_state)
10201 {
10202         struct drm_device *dev = old_state->dev;
10203         struct intel_atomic_state *old_intel_state =
10204                 to_intel_atomic_state(old_state);
10205         unsigned req_cdclk = old_intel_state->dev_cdclk;
10206
10207         broadwell_set_cdclk(dev, req_cdclk);
10208 }
10209
10210 static int skl_modeset_calc_cdclk(struct drm_atomic_state *state)
10211 {
10212         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
10213         struct drm_i915_private *dev_priv = to_i915(state->dev);
10214         const int max_pixclk = ilk_max_pixel_rate(state);
10215         int vco = intel_state->cdclk_pll_vco;
10216         int cdclk;
10217
10218         /*
10219          * FIXME should also account for plane ratio
10220          * once 64bpp pixel formats are supported.
10221          */
10222         cdclk = skl_calc_cdclk(max_pixclk, vco);
10223
10224         /*
10225          * FIXME move the cdclk caclulation to
10226          * compute_config() so we can fail gracegully.
10227          */
10228         if (cdclk > dev_priv->max_cdclk_freq) {
10229                 DRM_ERROR("requested cdclk (%d kHz) exceeds max (%d kHz)\n",
10230                           cdclk, dev_priv->max_cdclk_freq);
10231                 cdclk = dev_priv->max_cdclk_freq;
10232         }
10233
10234         intel_state->cdclk = intel_state->dev_cdclk = cdclk;
10235         if (!intel_state->active_crtcs)
10236                 intel_state->dev_cdclk = skl_calc_cdclk(0, vco);
10237
10238         return 0;
10239 }
10240
10241 static void skl_modeset_commit_cdclk(struct drm_atomic_state *old_state)
10242 {
10243         struct drm_i915_private *dev_priv = to_i915(old_state->dev);
10244         struct intel_atomic_state *intel_state = to_intel_atomic_state(old_state);
10245         unsigned int req_cdclk = intel_state->dev_cdclk;
10246         unsigned int req_vco = intel_state->cdclk_pll_vco;
10247
10248         skl_set_cdclk(dev_priv, req_cdclk, req_vco);
10249 }
10250
10251 static int haswell_crtc_compute_clock(struct intel_crtc *crtc,
10252                                       struct intel_crtc_state *crtc_state)
10253 {
10254         if (!intel_crtc_has_type(crtc_state, INTEL_OUTPUT_DSI)) {
10255                 if (!intel_ddi_pll_select(crtc, crtc_state))
10256                         return -EINVAL;
10257         }
10258
10259         crtc->lowfreq_avail = false;
10260
10261         return 0;
10262 }
10263
10264 static void bxt_get_ddi_pll(struct drm_i915_private *dev_priv,
10265                                 enum port port,
10266                                 struct intel_crtc_state *pipe_config)
10267 {
10268         enum intel_dpll_id id;
10269
10270         switch (port) {
10271         case PORT_A:
10272                 pipe_config->ddi_pll_sel = SKL_DPLL0;
10273                 id = DPLL_ID_SKL_DPLL0;
10274                 break;
10275         case PORT_B:
10276                 pipe_config->ddi_pll_sel = SKL_DPLL1;
10277                 id = DPLL_ID_SKL_DPLL1;
10278                 break;
10279         case PORT_C:
10280                 pipe_config->ddi_pll_sel = SKL_DPLL2;
10281                 id = DPLL_ID_SKL_DPLL2;
10282                 break;
10283         default:
10284                 DRM_ERROR("Incorrect port type\n");
10285                 return;
10286         }
10287
10288         pipe_config->shared_dpll = intel_get_shared_dpll_by_id(dev_priv, id);
10289 }
10290
10291 static void skylake_get_ddi_pll(struct drm_i915_private *dev_priv,
10292                                 enum port port,
10293                                 struct intel_crtc_state *pipe_config)
10294 {
10295         enum intel_dpll_id id;
10296         u32 temp;
10297
10298         temp = I915_READ(DPLL_CTRL2) & DPLL_CTRL2_DDI_CLK_SEL_MASK(port);
10299         pipe_config->ddi_pll_sel = temp >> (port * 3 + 1);
10300
10301         switch (pipe_config->ddi_pll_sel) {
10302         case SKL_DPLL0:
10303                 id = DPLL_ID_SKL_DPLL0;
10304                 break;
10305         case SKL_DPLL1:
10306                 id = DPLL_ID_SKL_DPLL1;
10307                 break;
10308         case SKL_DPLL2:
10309                 id = DPLL_ID_SKL_DPLL2;
10310                 break;
10311         case SKL_DPLL3:
10312                 id = DPLL_ID_SKL_DPLL3;
10313                 break;
10314         default:
10315                 MISSING_CASE(pipe_config->ddi_pll_sel);
10316                 return;
10317         }
10318
10319         pipe_config->shared_dpll = intel_get_shared_dpll_by_id(dev_priv, id);
10320 }
10321
10322 static void haswell_get_ddi_pll(struct drm_i915_private *dev_priv,
10323                                 enum port port,
10324                                 struct intel_crtc_state *pipe_config)
10325 {
10326         enum intel_dpll_id id;
10327
10328         pipe_config->ddi_pll_sel = I915_READ(PORT_CLK_SEL(port));
10329
10330         switch (pipe_config->ddi_pll_sel) {
10331         case PORT_CLK_SEL_WRPLL1:
10332                 id = DPLL_ID_WRPLL1;
10333                 break;
10334         case PORT_CLK_SEL_WRPLL2:
10335                 id = DPLL_ID_WRPLL2;
10336                 break;
10337         case PORT_CLK_SEL_SPLL:
10338                 id = DPLL_ID_SPLL;
10339                 break;
10340         case PORT_CLK_SEL_LCPLL_810:
10341                 id = DPLL_ID_LCPLL_810;
10342                 break;
10343         case PORT_CLK_SEL_LCPLL_1350:
10344                 id = DPLL_ID_LCPLL_1350;
10345                 break;
10346         case PORT_CLK_SEL_LCPLL_2700:
10347                 id = DPLL_ID_LCPLL_2700;
10348                 break;
10349         default:
10350                 MISSING_CASE(pipe_config->ddi_pll_sel);
10351                 /* fall through */
10352         case PORT_CLK_SEL_NONE:
10353                 return;
10354         }
10355
10356         pipe_config->shared_dpll = intel_get_shared_dpll_by_id(dev_priv, id);
10357 }
10358
10359 static bool hsw_get_transcoder_state(struct intel_crtc *crtc,
10360                                      struct intel_crtc_state *pipe_config,
10361                                      unsigned long *power_domain_mask)
10362 {
10363         struct drm_device *dev = crtc->base.dev;
10364         struct drm_i915_private *dev_priv = to_i915(dev);
10365         enum intel_display_power_domain power_domain;
10366         u32 tmp;
10367
10368         /*
10369          * The pipe->transcoder mapping is fixed with the exception of the eDP
10370          * transcoder handled below.
10371          */
10372         pipe_config->cpu_transcoder = (enum transcoder) crtc->pipe;
10373
10374         /*
10375          * XXX: Do intel_display_power_get_if_enabled before reading this (for
10376          * consistency and less surprising code; it's in always on power).
10377          */
10378         tmp = I915_READ(TRANS_DDI_FUNC_CTL(TRANSCODER_EDP));
10379         if (tmp & TRANS_DDI_FUNC_ENABLE) {
10380                 enum pipe trans_edp_pipe;
10381                 switch (tmp & TRANS_DDI_EDP_INPUT_MASK) {
10382                 default:
10383                         WARN(1, "unknown pipe linked to edp transcoder\n");
10384                 case TRANS_DDI_EDP_INPUT_A_ONOFF:
10385                 case TRANS_DDI_EDP_INPUT_A_ON:
10386                         trans_edp_pipe = PIPE_A;
10387                         break;
10388                 case TRANS_DDI_EDP_INPUT_B_ONOFF:
10389                         trans_edp_pipe = PIPE_B;
10390                         break;
10391                 case TRANS_DDI_EDP_INPUT_C_ONOFF:
10392                         trans_edp_pipe = PIPE_C;
10393                         break;
10394                 }
10395
10396                 if (trans_edp_pipe == crtc->pipe)
10397                         pipe_config->cpu_transcoder = TRANSCODER_EDP;
10398         }
10399
10400         power_domain = POWER_DOMAIN_TRANSCODER(pipe_config->cpu_transcoder);
10401         if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
10402                 return false;
10403         *power_domain_mask |= BIT(power_domain);
10404
10405         tmp = I915_READ(PIPECONF(pipe_config->cpu_transcoder));
10406
10407         return tmp & PIPECONF_ENABLE;
10408 }
10409
10410 static bool bxt_get_dsi_transcoder_state(struct intel_crtc *crtc,
10411                                          struct intel_crtc_state *pipe_config,
10412                                          unsigned long *power_domain_mask)
10413 {
10414         struct drm_device *dev = crtc->base.dev;
10415         struct drm_i915_private *dev_priv = to_i915(dev);
10416         enum intel_display_power_domain power_domain;
10417         enum port port;
10418         enum transcoder cpu_transcoder;
10419         u32 tmp;
10420
10421         for_each_port_masked(port, BIT(PORT_A) | BIT(PORT_C)) {
10422                 if (port == PORT_A)
10423                         cpu_transcoder = TRANSCODER_DSI_A;
10424                 else
10425                         cpu_transcoder = TRANSCODER_DSI_C;
10426
10427                 power_domain = POWER_DOMAIN_TRANSCODER(cpu_transcoder);
10428                 if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
10429                         continue;
10430                 *power_domain_mask |= BIT(power_domain);
10431
10432                 /*
10433                  * The PLL needs to be enabled with a valid divider
10434                  * configuration, otherwise accessing DSI registers will hang
10435                  * the machine. See BSpec North Display Engine
10436                  * registers/MIPI[BXT]. We can break out here early, since we
10437                  * need the same DSI PLL to be enabled for both DSI ports.
10438                  */
10439                 if (!intel_dsi_pll_is_enabled(dev_priv))
10440                         break;
10441
10442                 /* XXX: this works for video mode only */
10443                 tmp = I915_READ(BXT_MIPI_PORT_CTRL(port));
10444                 if (!(tmp & DPI_ENABLE))
10445                         continue;
10446
10447                 tmp = I915_READ(MIPI_CTRL(port));
10448                 if ((tmp & BXT_PIPE_SELECT_MASK) != BXT_PIPE_SELECT(crtc->pipe))
10449                         continue;
10450
10451                 pipe_config->cpu_transcoder = cpu_transcoder;
10452                 break;
10453         }
10454
10455         return transcoder_is_dsi(pipe_config->cpu_transcoder);
10456 }
10457
10458 static void haswell_get_ddi_port_state(struct intel_crtc *crtc,
10459                                        struct intel_crtc_state *pipe_config)
10460 {
10461         struct drm_device *dev = crtc->base.dev;
10462         struct drm_i915_private *dev_priv = to_i915(dev);
10463         struct intel_shared_dpll *pll;
10464         enum port port;
10465         uint32_t tmp;
10466
10467         tmp = I915_READ(TRANS_DDI_FUNC_CTL(pipe_config->cpu_transcoder));
10468
10469         port = (tmp & TRANS_DDI_PORT_MASK) >> TRANS_DDI_PORT_SHIFT;
10470
10471         if (IS_SKYLAKE(dev) || IS_KABYLAKE(dev))
10472                 skylake_get_ddi_pll(dev_priv, port, pipe_config);
10473         else if (IS_BROXTON(dev))
10474                 bxt_get_ddi_pll(dev_priv, port, pipe_config);
10475         else
10476                 haswell_get_ddi_pll(dev_priv, port, pipe_config);
10477
10478         pll = pipe_config->shared_dpll;
10479         if (pll) {
10480                 WARN_ON(!pll->funcs.get_hw_state(dev_priv, pll,
10481                                                  &pipe_config->dpll_hw_state));
10482         }
10483
10484         /*
10485          * Haswell has only FDI/PCH transcoder A. It is which is connected to
10486          * DDI E. So just check whether this pipe is wired to DDI E and whether
10487          * the PCH transcoder is on.
10488          */
10489         if (INTEL_INFO(dev)->gen < 9 &&
10490             (port == PORT_E) && I915_READ(LPT_TRANSCONF) & TRANS_ENABLE) {
10491                 pipe_config->has_pch_encoder = true;
10492
10493                 tmp = I915_READ(FDI_RX_CTL(PIPE_A));
10494                 pipe_config->fdi_lanes = ((FDI_DP_PORT_WIDTH_MASK & tmp) >>
10495                                           FDI_DP_PORT_WIDTH_SHIFT) + 1;
10496
10497                 ironlake_get_fdi_m_n_config(crtc, pipe_config);
10498         }
10499 }
10500
10501 static bool haswell_get_pipe_config(struct intel_crtc *crtc,
10502                                     struct intel_crtc_state *pipe_config)
10503 {
10504         struct drm_device *dev = crtc->base.dev;
10505         struct drm_i915_private *dev_priv = to_i915(dev);
10506         enum intel_display_power_domain power_domain;
10507         unsigned long power_domain_mask;
10508         bool active;
10509
10510         power_domain = POWER_DOMAIN_PIPE(crtc->pipe);
10511         if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
10512                 return false;
10513         power_domain_mask = BIT(power_domain);
10514
10515         pipe_config->shared_dpll = NULL;
10516
10517         active = hsw_get_transcoder_state(crtc, pipe_config, &power_domain_mask);
10518
10519         if (IS_BROXTON(dev_priv) &&
10520             bxt_get_dsi_transcoder_state(crtc, pipe_config, &power_domain_mask)) {
10521                 WARN_ON(active);
10522                 active = true;
10523         }
10524
10525         if (!active)
10526                 goto out;
10527
10528         if (!transcoder_is_dsi(pipe_config->cpu_transcoder)) {
10529                 haswell_get_ddi_port_state(crtc, pipe_config);
10530                 intel_get_pipe_timings(crtc, pipe_config);
10531         }
10532
10533         intel_get_pipe_src_size(crtc, pipe_config);
10534
10535         pipe_config->gamma_mode =
10536                 I915_READ(GAMMA_MODE(crtc->pipe)) & GAMMA_MODE_MODE_MASK;
10537
10538         if (INTEL_INFO(dev)->gen >= 9) {
10539                 skl_init_scalers(dev, crtc, pipe_config);
10540         }
10541
10542         if (INTEL_INFO(dev)->gen >= 9) {
10543                 pipe_config->scaler_state.scaler_id = -1;
10544                 pipe_config->scaler_state.scaler_users &= ~(1 << SKL_CRTC_INDEX);
10545         }
10546
10547         power_domain = POWER_DOMAIN_PIPE_PANEL_FITTER(crtc->pipe);
10548         if (intel_display_power_get_if_enabled(dev_priv, power_domain)) {
10549                 power_domain_mask |= BIT(power_domain);
10550                 if (INTEL_INFO(dev)->gen >= 9)
10551                         skylake_get_pfit_config(crtc, pipe_config);
10552                 else
10553                         ironlake_get_pfit_config(crtc, pipe_config);
10554         }
10555
10556         if (IS_HASWELL(dev))
10557                 pipe_config->ips_enabled = hsw_crtc_supports_ips(crtc) &&
10558                         (I915_READ(IPS_CTL) & IPS_ENABLE);
10559
10560         if (pipe_config->cpu_transcoder != TRANSCODER_EDP &&
10561             !transcoder_is_dsi(pipe_config->cpu_transcoder)) {
10562                 pipe_config->pixel_multiplier =
10563                         I915_READ(PIPE_MULT(pipe_config->cpu_transcoder)) + 1;
10564         } else {
10565                 pipe_config->pixel_multiplier = 1;
10566         }
10567
10568 out:
10569         for_each_power_domain(power_domain, power_domain_mask)
10570                 intel_display_power_put(dev_priv, power_domain);
10571
10572         return active;
10573 }
10574
10575 static void i845_update_cursor(struct drm_crtc *crtc, u32 base,
10576                                const struct intel_plane_state *plane_state)
10577 {
10578         struct drm_device *dev = crtc->dev;
10579         struct drm_i915_private *dev_priv = to_i915(dev);
10580         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10581         uint32_t cntl = 0, size = 0;
10582
10583         if (plane_state && plane_state->visible) {
10584                 unsigned int width = plane_state->base.crtc_w;
10585                 unsigned int height = plane_state->base.crtc_h;
10586                 unsigned int stride = roundup_pow_of_two(width) * 4;
10587
10588                 switch (stride) {
10589                 default:
10590                         WARN_ONCE(1, "Invalid cursor width/stride, width=%u, stride=%u\n",
10591                                   width, stride);
10592                         stride = 256;
10593                         /* fallthrough */
10594                 case 256:
10595                 case 512:
10596                 case 1024:
10597                 case 2048:
10598                         break;
10599                 }
10600
10601                 cntl |= CURSOR_ENABLE |
10602                         CURSOR_GAMMA_ENABLE |
10603                         CURSOR_FORMAT_ARGB |
10604                         CURSOR_STRIDE(stride);
10605
10606                 size = (height << 12) | width;
10607         }
10608
10609         if (intel_crtc->cursor_cntl != 0 &&
10610             (intel_crtc->cursor_base != base ||
10611              intel_crtc->cursor_size != size ||
10612              intel_crtc->cursor_cntl != cntl)) {
10613                 /* On these chipsets we can only modify the base/size/stride
10614                  * whilst the cursor is disabled.
10615                  */
10616                 I915_WRITE(CURCNTR(PIPE_A), 0);
10617                 POSTING_READ(CURCNTR(PIPE_A));
10618                 intel_crtc->cursor_cntl = 0;
10619         }
10620
10621         if (intel_crtc->cursor_base != base) {
10622                 I915_WRITE(CURBASE(PIPE_A), base);
10623                 intel_crtc->cursor_base = base;
10624         }
10625
10626         if (intel_crtc->cursor_size != size) {
10627                 I915_WRITE(CURSIZE, size);
10628                 intel_crtc->cursor_size = size;
10629         }
10630
10631         if (intel_crtc->cursor_cntl != cntl) {
10632                 I915_WRITE(CURCNTR(PIPE_A), cntl);
10633                 POSTING_READ(CURCNTR(PIPE_A));
10634                 intel_crtc->cursor_cntl = cntl;
10635         }
10636 }
10637
10638 static void i9xx_update_cursor(struct drm_crtc *crtc, u32 base,
10639                                const struct intel_plane_state *plane_state)
10640 {
10641         struct drm_device *dev = crtc->dev;
10642         struct drm_i915_private *dev_priv = to_i915(dev);
10643         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10644         int pipe = intel_crtc->pipe;
10645         uint32_t cntl = 0;
10646
10647         if (plane_state && plane_state->visible) {
10648                 cntl = MCURSOR_GAMMA_ENABLE;
10649                 switch (plane_state->base.crtc_w) {
10650                         case 64:
10651                                 cntl |= CURSOR_MODE_64_ARGB_AX;
10652                                 break;
10653                         case 128:
10654                                 cntl |= CURSOR_MODE_128_ARGB_AX;
10655                                 break;
10656                         case 256:
10657                                 cntl |= CURSOR_MODE_256_ARGB_AX;
10658                                 break;
10659                         default:
10660                                 MISSING_CASE(plane_state->base.crtc_w);
10661                                 return;
10662                 }
10663                 cntl |= pipe << 28; /* Connect to correct pipe */
10664
10665                 if (HAS_DDI(dev))
10666                         cntl |= CURSOR_PIPE_CSC_ENABLE;
10667
10668                 if (plane_state->base.rotation == BIT(DRM_ROTATE_180))
10669                         cntl |= CURSOR_ROTATE_180;
10670         }
10671
10672         if (intel_crtc->cursor_cntl != cntl) {
10673                 I915_WRITE(CURCNTR(pipe), cntl);
10674                 POSTING_READ(CURCNTR(pipe));
10675                 intel_crtc->cursor_cntl = cntl;
10676         }
10677
10678         /* and commit changes on next vblank */
10679         I915_WRITE(CURBASE(pipe), base);
10680         POSTING_READ(CURBASE(pipe));
10681
10682         intel_crtc->cursor_base = base;
10683 }
10684
10685 /* If no-part of the cursor is visible on the framebuffer, then the GPU may hang... */
10686 static void intel_crtc_update_cursor(struct drm_crtc *crtc,
10687                                      const struct intel_plane_state *plane_state)
10688 {
10689         struct drm_device *dev = crtc->dev;
10690         struct drm_i915_private *dev_priv = to_i915(dev);
10691         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10692         int pipe = intel_crtc->pipe;
10693         u32 base = intel_crtc->cursor_addr;
10694         u32 pos = 0;
10695
10696         if (plane_state) {
10697                 int x = plane_state->base.crtc_x;
10698                 int y = plane_state->base.crtc_y;
10699
10700                 if (x < 0) {
10701                         pos |= CURSOR_POS_SIGN << CURSOR_X_SHIFT;
10702                         x = -x;
10703                 }
10704                 pos |= x << CURSOR_X_SHIFT;
10705
10706                 if (y < 0) {
10707                         pos |= CURSOR_POS_SIGN << CURSOR_Y_SHIFT;
10708                         y = -y;
10709                 }
10710                 pos |= y << CURSOR_Y_SHIFT;
10711
10712                 /* ILK+ do this automagically */
10713                 if (HAS_GMCH_DISPLAY(dev) &&
10714                     plane_state->base.rotation == BIT(DRM_ROTATE_180)) {
10715                         base += (plane_state->base.crtc_h *
10716                                  plane_state->base.crtc_w - 1) * 4;
10717                 }
10718         }
10719
10720         I915_WRITE(CURPOS(pipe), pos);
10721
10722         if (IS_845G(dev) || IS_I865G(dev))
10723                 i845_update_cursor(crtc, base, plane_state);
10724         else
10725                 i9xx_update_cursor(crtc, base, plane_state);
10726 }
10727
10728 static bool cursor_size_ok(struct drm_device *dev,
10729                            uint32_t width, uint32_t height)
10730 {
10731         if (width == 0 || height == 0)
10732                 return false;
10733
10734         /*
10735          * 845g/865g are special in that they are only limited by
10736          * the width of their cursors, the height is arbitrary up to
10737          * the precision of the register. Everything else requires
10738          * square cursors, limited to a few power-of-two sizes.
10739          */
10740         if (IS_845G(dev) || IS_I865G(dev)) {
10741                 if ((width & 63) != 0)
10742                         return false;
10743
10744                 if (width > (IS_845G(dev) ? 64 : 512))
10745                         return false;
10746
10747                 if (height > 1023)
10748                         return false;
10749         } else {
10750                 switch (width | height) {
10751                 case 256:
10752                 case 128:
10753                         if (IS_GEN2(dev))
10754                                 return false;
10755                 case 64:
10756                         break;
10757                 default:
10758                         return false;
10759                 }
10760         }
10761
10762         return true;
10763 }
10764
10765 /* VESA 640x480x72Hz mode to set on the pipe */
10766 static struct drm_display_mode load_detect_mode = {
10767         DRM_MODE("640x480", DRM_MODE_TYPE_DEFAULT, 31500, 640, 664,
10768                  704, 832, 0, 480, 489, 491, 520, 0, DRM_MODE_FLAG_NHSYNC | DRM_MODE_FLAG_NVSYNC),
10769 };
10770
10771 struct drm_framebuffer *
10772 __intel_framebuffer_create(struct drm_device *dev,
10773                            struct drm_mode_fb_cmd2 *mode_cmd,
10774                            struct drm_i915_gem_object *obj)
10775 {
10776         struct intel_framebuffer *intel_fb;
10777         int ret;
10778
10779         intel_fb = kzalloc(sizeof(*intel_fb), GFP_KERNEL);
10780         if (!intel_fb)
10781                 return ERR_PTR(-ENOMEM);
10782
10783         ret = intel_framebuffer_init(dev, intel_fb, mode_cmd, obj);
10784         if (ret)
10785                 goto err;
10786
10787         return &intel_fb->base;
10788
10789 err:
10790         kfree(intel_fb);
10791         return ERR_PTR(ret);
10792 }
10793
10794 static struct drm_framebuffer *
10795 intel_framebuffer_create(struct drm_device *dev,
10796                          struct drm_mode_fb_cmd2 *mode_cmd,
10797                          struct drm_i915_gem_object *obj)
10798 {
10799         struct drm_framebuffer *fb;
10800         int ret;
10801
10802         ret = i915_mutex_lock_interruptible(dev);
10803         if (ret)
10804                 return ERR_PTR(ret);
10805         fb = __intel_framebuffer_create(dev, mode_cmd, obj);
10806         mutex_unlock(&dev->struct_mutex);
10807
10808         return fb;
10809 }
10810
10811 static u32
10812 intel_framebuffer_pitch_for_width(int width, int bpp)
10813 {
10814         u32 pitch = DIV_ROUND_UP(width * bpp, 8);
10815         return ALIGN(pitch, 64);
10816 }
10817
10818 static u32
10819 intel_framebuffer_size_for_mode(struct drm_display_mode *mode, int bpp)
10820 {
10821         u32 pitch = intel_framebuffer_pitch_for_width(mode->hdisplay, bpp);
10822         return PAGE_ALIGN(pitch * mode->vdisplay);
10823 }
10824
10825 static struct drm_framebuffer *
10826 intel_framebuffer_create_for_mode(struct drm_device *dev,
10827                                   struct drm_display_mode *mode,
10828                                   int depth, int bpp)
10829 {
10830         struct drm_framebuffer *fb;
10831         struct drm_i915_gem_object *obj;
10832         struct drm_mode_fb_cmd2 mode_cmd = { 0 };
10833
10834         obj = i915_gem_object_create(dev,
10835                                     intel_framebuffer_size_for_mode(mode, bpp));
10836         if (IS_ERR(obj))
10837                 return ERR_CAST(obj);
10838
10839         mode_cmd.width = mode->hdisplay;
10840         mode_cmd.height = mode->vdisplay;
10841         mode_cmd.pitches[0] = intel_framebuffer_pitch_for_width(mode_cmd.width,
10842                                                                 bpp);
10843         mode_cmd.pixel_format = drm_mode_legacy_fb_format(bpp, depth);
10844
10845         fb = intel_framebuffer_create(dev, &mode_cmd, obj);
10846         if (IS_ERR(fb))
10847                 i915_gem_object_put_unlocked(obj);
10848
10849         return fb;
10850 }
10851
10852 static struct drm_framebuffer *
10853 mode_fits_in_fbdev(struct drm_device *dev,
10854                    struct drm_display_mode *mode)
10855 {
10856 #ifdef CONFIG_DRM_FBDEV_EMULATION
10857         struct drm_i915_private *dev_priv = to_i915(dev);
10858         struct drm_i915_gem_object *obj;
10859         struct drm_framebuffer *fb;
10860
10861         if (!dev_priv->fbdev)
10862                 return NULL;
10863
10864         if (!dev_priv->fbdev->fb)
10865                 return NULL;
10866
10867         obj = dev_priv->fbdev->fb->obj;
10868         BUG_ON(!obj);
10869
10870         fb = &dev_priv->fbdev->fb->base;
10871         if (fb->pitches[0] < intel_framebuffer_pitch_for_width(mode->hdisplay,
10872                                                                fb->bits_per_pixel))
10873                 return NULL;
10874
10875         if (obj->base.size < mode->vdisplay * fb->pitches[0])
10876                 return NULL;
10877
10878         drm_framebuffer_reference(fb);
10879         return fb;
10880 #else
10881         return NULL;
10882 #endif
10883 }
10884
10885 static int intel_modeset_setup_plane_state(struct drm_atomic_state *state,
10886                                            struct drm_crtc *crtc,
10887                                            struct drm_display_mode *mode,
10888                                            struct drm_framebuffer *fb,
10889                                            int x, int y)
10890 {
10891         struct drm_plane_state *plane_state;
10892         int hdisplay, vdisplay;
10893         int ret;
10894
10895         plane_state = drm_atomic_get_plane_state(state, crtc->primary);
10896         if (IS_ERR(plane_state))
10897                 return PTR_ERR(plane_state);
10898
10899         if (mode)
10900                 drm_crtc_get_hv_timing(mode, &hdisplay, &vdisplay);
10901         else
10902                 hdisplay = vdisplay = 0;
10903
10904         ret = drm_atomic_set_crtc_for_plane(plane_state, fb ? crtc : NULL);
10905         if (ret)
10906                 return ret;
10907         drm_atomic_set_fb_for_plane(plane_state, fb);
10908         plane_state->crtc_x = 0;
10909         plane_state->crtc_y = 0;
10910         plane_state->crtc_w = hdisplay;
10911         plane_state->crtc_h = vdisplay;
10912         plane_state->src_x = x << 16;
10913         plane_state->src_y = y << 16;
10914         plane_state->src_w = hdisplay << 16;
10915         plane_state->src_h = vdisplay << 16;
10916
10917         return 0;
10918 }
10919
10920 bool intel_get_load_detect_pipe(struct drm_connector *connector,
10921                                 struct drm_display_mode *mode,
10922                                 struct intel_load_detect_pipe *old,
10923                                 struct drm_modeset_acquire_ctx *ctx)
10924 {
10925         struct intel_crtc *intel_crtc;
10926         struct intel_encoder *intel_encoder =
10927                 intel_attached_encoder(connector);
10928         struct drm_crtc *possible_crtc;
10929         struct drm_encoder *encoder = &intel_encoder->base;
10930         struct drm_crtc *crtc = NULL;
10931         struct drm_device *dev = encoder->dev;
10932         struct drm_framebuffer *fb;
10933         struct drm_mode_config *config = &dev->mode_config;
10934         struct drm_atomic_state *state = NULL, *restore_state = NULL;
10935         struct drm_connector_state *connector_state;
10936         struct intel_crtc_state *crtc_state;
10937         int ret, i = -1;
10938
10939         DRM_DEBUG_KMS("[CONNECTOR:%d:%s], [ENCODER:%d:%s]\n",
10940                       connector->base.id, connector->name,
10941                       encoder->base.id, encoder->name);
10942
10943         old->restore_state = NULL;
10944
10945 retry:
10946         ret = drm_modeset_lock(&config->connection_mutex, ctx);
10947         if (ret)
10948                 goto fail;
10949
10950         /*
10951          * Algorithm gets a little messy:
10952          *
10953          *   - if the connector already has an assigned crtc, use it (but make
10954          *     sure it's on first)
10955          *
10956          *   - try to find the first unused crtc that can drive this connector,
10957          *     and use that if we find one
10958          */
10959
10960         /* See if we already have a CRTC for this connector */
10961         if (connector->state->crtc) {
10962                 crtc = connector->state->crtc;
10963
10964                 ret = drm_modeset_lock(&crtc->mutex, ctx);
10965                 if (ret)
10966                         goto fail;
10967
10968                 /* Make sure the crtc and connector are running */
10969                 goto found;
10970         }
10971
10972         /* Find an unused one (if possible) */
10973         for_each_crtc(dev, possible_crtc) {
10974                 i++;
10975                 if (!(encoder->possible_crtcs & (1 << i)))
10976                         continue;
10977
10978                 ret = drm_modeset_lock(&possible_crtc->mutex, ctx);
10979                 if (ret)
10980                         goto fail;
10981
10982                 if (possible_crtc->state->enable) {
10983                         drm_modeset_unlock(&possible_crtc->mutex);
10984                         continue;
10985                 }
10986
10987                 crtc = possible_crtc;
10988                 break;
10989         }
10990
10991         /*
10992          * If we didn't find an unused CRTC, don't use any.
10993          */
10994         if (!crtc) {
10995                 DRM_DEBUG_KMS("no pipe available for load-detect\n");
10996                 goto fail;
10997         }
10998
10999 found:
11000         intel_crtc = to_intel_crtc(crtc);
11001
11002         ret = drm_modeset_lock(&crtc->primary->mutex, ctx);
11003         if (ret)
11004                 goto fail;
11005
11006         state = drm_atomic_state_alloc(dev);
11007         restore_state = drm_atomic_state_alloc(dev);
11008         if (!state || !restore_state) {
11009                 ret = -ENOMEM;
11010                 goto fail;
11011         }
11012
11013         state->acquire_ctx = ctx;
11014         restore_state->acquire_ctx = ctx;
11015
11016         connector_state = drm_atomic_get_connector_state(state, connector);
11017         if (IS_ERR(connector_state)) {
11018                 ret = PTR_ERR(connector_state);
11019                 goto fail;
11020         }
11021
11022         ret = drm_atomic_set_crtc_for_connector(connector_state, crtc);
11023         if (ret)
11024                 goto fail;
11025
11026         crtc_state = intel_atomic_get_crtc_state(state, intel_crtc);
11027         if (IS_ERR(crtc_state)) {
11028                 ret = PTR_ERR(crtc_state);
11029                 goto fail;
11030         }
11031
11032         crtc_state->base.active = crtc_state->base.enable = true;
11033
11034         if (!mode)
11035                 mode = &load_detect_mode;
11036
11037         /* We need a framebuffer large enough to accommodate all accesses
11038          * that the plane may generate whilst we perform load detection.
11039          * We can not rely on the fbcon either being present (we get called
11040          * during its initialisation to detect all boot displays, or it may
11041          * not even exist) or that it is large enough to satisfy the
11042          * requested mode.
11043          */
11044         fb = mode_fits_in_fbdev(dev, mode);
11045         if (fb == NULL) {
11046                 DRM_DEBUG_KMS("creating tmp fb for load-detection\n");
11047                 fb = intel_framebuffer_create_for_mode(dev, mode, 24, 32);
11048         } else
11049                 DRM_DEBUG_KMS("reusing fbdev for load-detection framebuffer\n");
11050         if (IS_ERR(fb)) {
11051                 DRM_DEBUG_KMS("failed to allocate framebuffer for load-detection\n");
11052                 goto fail;
11053         }
11054
11055         ret = intel_modeset_setup_plane_state(state, crtc, mode, fb, 0, 0);
11056         if (ret)
11057                 goto fail;
11058
11059         drm_framebuffer_unreference(fb);
11060
11061         ret = drm_atomic_set_mode_for_crtc(&crtc_state->base, mode);
11062         if (ret)
11063                 goto fail;
11064
11065         ret = PTR_ERR_OR_ZERO(drm_atomic_get_connector_state(restore_state, connector));
11066         if (!ret)
11067                 ret = PTR_ERR_OR_ZERO(drm_atomic_get_crtc_state(restore_state, crtc));
11068         if (!ret)
11069                 ret = PTR_ERR_OR_ZERO(drm_atomic_get_plane_state(restore_state, crtc->primary));
11070         if (ret) {
11071                 DRM_DEBUG_KMS("Failed to create a copy of old state to restore: %i\n", ret);
11072                 goto fail;
11073         }
11074
11075         ret = drm_atomic_commit(state);
11076         if (ret) {
11077                 DRM_DEBUG_KMS("failed to set mode on load-detect pipe\n");
11078                 goto fail;
11079         }
11080
11081         old->restore_state = restore_state;
11082
11083         /* let the connector get through one full cycle before testing */
11084         intel_wait_for_vblank(dev, intel_crtc->pipe);
11085         return true;
11086
11087 fail:
11088         drm_atomic_state_free(state);
11089         drm_atomic_state_free(restore_state);
11090         restore_state = state = NULL;
11091
11092         if (ret == -EDEADLK) {
11093                 drm_modeset_backoff(ctx);
11094                 goto retry;
11095         }
11096
11097         return false;
11098 }
11099
11100 void intel_release_load_detect_pipe(struct drm_connector *connector,
11101                                     struct intel_load_detect_pipe *old,
11102                                     struct drm_modeset_acquire_ctx *ctx)
11103 {
11104         struct intel_encoder *intel_encoder =
11105                 intel_attached_encoder(connector);
11106         struct drm_encoder *encoder = &intel_encoder->base;
11107         struct drm_atomic_state *state = old->restore_state;
11108         int ret;
11109
11110         DRM_DEBUG_KMS("[CONNECTOR:%d:%s], [ENCODER:%d:%s]\n",
11111                       connector->base.id, connector->name,
11112                       encoder->base.id, encoder->name);
11113
11114         if (!state)
11115                 return;
11116
11117         ret = drm_atomic_commit(state);
11118         if (ret) {
11119                 DRM_DEBUG_KMS("Couldn't release load detect pipe: %i\n", ret);
11120                 drm_atomic_state_free(state);
11121         }
11122 }
11123
11124 static int i9xx_pll_refclk(struct drm_device *dev,
11125                            const struct intel_crtc_state *pipe_config)
11126 {
11127         struct drm_i915_private *dev_priv = to_i915(dev);
11128         u32 dpll = pipe_config->dpll_hw_state.dpll;
11129
11130         if ((dpll & PLL_REF_INPUT_MASK) == PLLB_REF_INPUT_SPREADSPECTRUMIN)
11131                 return dev_priv->vbt.lvds_ssc_freq;
11132         else if (HAS_PCH_SPLIT(dev))
11133                 return 120000;
11134         else if (!IS_GEN2(dev))
11135                 return 96000;
11136         else
11137                 return 48000;
11138 }
11139
11140 /* Returns the clock of the currently programmed mode of the given pipe. */
11141 static void i9xx_crtc_clock_get(struct intel_crtc *crtc,
11142                                 struct intel_crtc_state *pipe_config)
11143 {
11144         struct drm_device *dev = crtc->base.dev;
11145         struct drm_i915_private *dev_priv = to_i915(dev);
11146         int pipe = pipe_config->cpu_transcoder;
11147         u32 dpll = pipe_config->dpll_hw_state.dpll;
11148         u32 fp;
11149         struct dpll clock;
11150         int port_clock;
11151         int refclk = i9xx_pll_refclk(dev, pipe_config);
11152
11153         if ((dpll & DISPLAY_RATE_SELECT_FPA1) == 0)
11154                 fp = pipe_config->dpll_hw_state.fp0;
11155         else
11156                 fp = pipe_config->dpll_hw_state.fp1;
11157
11158         clock.m1 = (fp & FP_M1_DIV_MASK) >> FP_M1_DIV_SHIFT;
11159         if (IS_PINEVIEW(dev)) {
11160                 clock.n = ffs((fp & FP_N_PINEVIEW_DIV_MASK) >> FP_N_DIV_SHIFT) - 1;
11161                 clock.m2 = (fp & FP_M2_PINEVIEW_DIV_MASK) >> FP_M2_DIV_SHIFT;
11162         } else {
11163                 clock.n = (fp & FP_N_DIV_MASK) >> FP_N_DIV_SHIFT;
11164                 clock.m2 = (fp & FP_M2_DIV_MASK) >> FP_M2_DIV_SHIFT;
11165         }
11166
11167         if (!IS_GEN2(dev)) {
11168                 if (IS_PINEVIEW(dev))
11169                         clock.p1 = ffs((dpll & DPLL_FPA01_P1_POST_DIV_MASK_PINEVIEW) >>
11170                                 DPLL_FPA01_P1_POST_DIV_SHIFT_PINEVIEW);
11171                 else
11172                         clock.p1 = ffs((dpll & DPLL_FPA01_P1_POST_DIV_MASK) >>
11173                                DPLL_FPA01_P1_POST_DIV_SHIFT);
11174
11175                 switch (dpll & DPLL_MODE_MASK) {
11176                 case DPLLB_MODE_DAC_SERIAL:
11177                         clock.p2 = dpll & DPLL_DAC_SERIAL_P2_CLOCK_DIV_5 ?
11178                                 5 : 10;
11179                         break;
11180                 case DPLLB_MODE_LVDS:
11181                         clock.p2 = dpll & DPLLB_LVDS_P2_CLOCK_DIV_7 ?
11182                                 7 : 14;
11183                         break;
11184                 default:
11185                         DRM_DEBUG_KMS("Unknown DPLL mode %08x in programmed "
11186                                   "mode\n", (int)(dpll & DPLL_MODE_MASK));
11187                         return;
11188                 }
11189
11190                 if (IS_PINEVIEW(dev))
11191                         port_clock = pnv_calc_dpll_params(refclk, &clock);
11192                 else
11193                         port_clock = i9xx_calc_dpll_params(refclk, &clock);
11194         } else {
11195                 u32 lvds = IS_I830(dev) ? 0 : I915_READ(LVDS);
11196                 bool is_lvds = (pipe == 1) && (lvds & LVDS_PORT_EN);
11197
11198                 if (is_lvds) {
11199                         clock.p1 = ffs((dpll & DPLL_FPA01_P1_POST_DIV_MASK_I830_LVDS) >>
11200                                        DPLL_FPA01_P1_POST_DIV_SHIFT);
11201
11202                         if (lvds & LVDS_CLKB_POWER_UP)
11203                                 clock.p2 = 7;
11204                         else
11205                                 clock.p2 = 14;
11206                 } else {
11207                         if (dpll & PLL_P1_DIVIDE_BY_TWO)
11208                                 clock.p1 = 2;
11209                         else {
11210                                 clock.p1 = ((dpll & DPLL_FPA01_P1_POST_DIV_MASK_I830) >>
11211                                             DPLL_FPA01_P1_POST_DIV_SHIFT) + 2;
11212                         }
11213                         if (dpll & PLL_P2_DIVIDE_BY_4)
11214                                 clock.p2 = 4;
11215                         else
11216                                 clock.p2 = 2;
11217                 }
11218
11219                 port_clock = i9xx_calc_dpll_params(refclk, &clock);
11220         }
11221
11222         /*
11223          * This value includes pixel_multiplier. We will use
11224          * port_clock to compute adjusted_mode.crtc_clock in the
11225          * encoder's get_config() function.
11226          */
11227         pipe_config->port_clock = port_clock;
11228 }
11229
11230 int intel_dotclock_calculate(int link_freq,
11231                              const struct intel_link_m_n *m_n)
11232 {
11233         /*
11234          * The calculation for the data clock is:
11235          * pixel_clock = ((m/n)*(link_clock * nr_lanes))/bpp
11236          * But we want to avoid losing precison if possible, so:
11237          * pixel_clock = ((m * link_clock * nr_lanes)/(n*bpp))
11238          *
11239          * and the link clock is simpler:
11240          * link_clock = (m * link_clock) / n
11241          */
11242
11243         if (!m_n->link_n)
11244                 return 0;
11245
11246         return div_u64((u64)m_n->link_m * link_freq, m_n->link_n);
11247 }
11248
11249 static void ironlake_pch_clock_get(struct intel_crtc *crtc,
11250                                    struct intel_crtc_state *pipe_config)
11251 {
11252         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
11253
11254         /* read out port_clock from the DPLL */
11255         i9xx_crtc_clock_get(crtc, pipe_config);
11256
11257         /*
11258          * In case there is an active pipe without active ports,
11259          * we may need some idea for the dotclock anyway.
11260          * Calculate one based on the FDI configuration.
11261          */
11262         pipe_config->base.adjusted_mode.crtc_clock =
11263                 intel_dotclock_calculate(intel_fdi_link_freq(dev_priv, pipe_config),
11264                                          &pipe_config->fdi_m_n);
11265 }
11266
11267 /** Returns the currently programmed mode of the given pipe. */
11268 struct drm_display_mode *intel_crtc_mode_get(struct drm_device *dev,
11269                                              struct drm_crtc *crtc)
11270 {
11271         struct drm_i915_private *dev_priv = to_i915(dev);
11272         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11273         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
11274         struct drm_display_mode *mode;
11275         struct intel_crtc_state *pipe_config;
11276         int htot = I915_READ(HTOTAL(cpu_transcoder));
11277         int hsync = I915_READ(HSYNC(cpu_transcoder));
11278         int vtot = I915_READ(VTOTAL(cpu_transcoder));
11279         int vsync = I915_READ(VSYNC(cpu_transcoder));
11280         enum pipe pipe = intel_crtc->pipe;
11281
11282         mode = kzalloc(sizeof(*mode), GFP_KERNEL);
11283         if (!mode)
11284                 return NULL;
11285
11286         pipe_config = kzalloc(sizeof(*pipe_config), GFP_KERNEL);
11287         if (!pipe_config) {
11288                 kfree(mode);
11289                 return NULL;
11290         }
11291
11292         /*
11293          * Construct a pipe_config sufficient for getting the clock info
11294          * back out of crtc_clock_get.
11295          *
11296          * Note, if LVDS ever uses a non-1 pixel multiplier, we'll need
11297          * to use a real value here instead.
11298          */
11299         pipe_config->cpu_transcoder = (enum transcoder) pipe;
11300         pipe_config->pixel_multiplier = 1;
11301         pipe_config->dpll_hw_state.dpll = I915_READ(DPLL(pipe));
11302         pipe_config->dpll_hw_state.fp0 = I915_READ(FP0(pipe));
11303         pipe_config->dpll_hw_state.fp1 = I915_READ(FP1(pipe));
11304         i9xx_crtc_clock_get(intel_crtc, pipe_config);
11305
11306         mode->clock = pipe_config->port_clock / pipe_config->pixel_multiplier;
11307         mode->hdisplay = (htot & 0xffff) + 1;
11308         mode->htotal = ((htot & 0xffff0000) >> 16) + 1;
11309         mode->hsync_start = (hsync & 0xffff) + 1;
11310         mode->hsync_end = ((hsync & 0xffff0000) >> 16) + 1;
11311         mode->vdisplay = (vtot & 0xffff) + 1;
11312         mode->vtotal = ((vtot & 0xffff0000) >> 16) + 1;
11313         mode->vsync_start = (vsync & 0xffff) + 1;
11314         mode->vsync_end = ((vsync & 0xffff0000) >> 16) + 1;
11315
11316         drm_mode_set_name(mode);
11317
11318         kfree(pipe_config);
11319
11320         return mode;
11321 }
11322
11323 static void intel_crtc_destroy(struct drm_crtc *crtc)
11324 {
11325         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11326         struct drm_device *dev = crtc->dev;
11327         struct intel_flip_work *work;
11328
11329         spin_lock_irq(&dev->event_lock);
11330         work = intel_crtc->flip_work;
11331         intel_crtc->flip_work = NULL;
11332         spin_unlock_irq(&dev->event_lock);
11333
11334         if (work) {
11335                 cancel_work_sync(&work->mmio_work);
11336                 cancel_work_sync(&work->unpin_work);
11337                 kfree(work);
11338         }
11339
11340         drm_crtc_cleanup(crtc);
11341
11342         kfree(intel_crtc);
11343 }
11344
11345 static void intel_unpin_work_fn(struct work_struct *__work)
11346 {
11347         struct intel_flip_work *work =
11348                 container_of(__work, struct intel_flip_work, unpin_work);
11349         struct intel_crtc *crtc = to_intel_crtc(work->crtc);
11350         struct drm_device *dev = crtc->base.dev;
11351         struct drm_plane *primary = crtc->base.primary;
11352
11353         if (is_mmio_work(work))
11354                 flush_work(&work->mmio_work);
11355
11356         mutex_lock(&dev->struct_mutex);
11357         intel_unpin_fb_obj(work->old_fb, primary->state->rotation);
11358         i915_gem_object_put(work->pending_flip_obj);
11359         mutex_unlock(&dev->struct_mutex);
11360
11361         i915_gem_request_put(work->flip_queued_req);
11362
11363         intel_frontbuffer_flip_complete(to_i915(dev),
11364                                         to_intel_plane(primary)->frontbuffer_bit);
11365         intel_fbc_post_update(crtc);
11366         drm_framebuffer_unreference(work->old_fb);
11367
11368         BUG_ON(atomic_read(&crtc->unpin_work_count) == 0);
11369         atomic_dec(&crtc->unpin_work_count);
11370
11371         kfree(work);
11372 }
11373
11374 /* Is 'a' after or equal to 'b'? */
11375 static bool g4x_flip_count_after_eq(u32 a, u32 b)
11376 {
11377         return !((a - b) & 0x80000000);
11378 }
11379
11380 static bool __pageflip_finished_cs(struct intel_crtc *crtc,
11381                                    struct intel_flip_work *work)
11382 {
11383         struct drm_device *dev = crtc->base.dev;
11384         struct drm_i915_private *dev_priv = to_i915(dev);
11385         unsigned reset_counter;
11386
11387         reset_counter = i915_reset_counter(&dev_priv->gpu_error);
11388         if (crtc->reset_counter != reset_counter)
11389                 return true;
11390
11391         /*
11392          * The relevant registers doen't exist on pre-ctg.
11393          * As the flip done interrupt doesn't trigger for mmio
11394          * flips on gmch platforms, a flip count check isn't
11395          * really needed there. But since ctg has the registers,
11396          * include it in the check anyway.
11397          */
11398         if (INTEL_INFO(dev)->gen < 5 && !IS_G4X(dev))
11399                 return true;
11400
11401         /*
11402          * BDW signals flip done immediately if the plane
11403          * is disabled, even if the plane enable is already
11404          * armed to occur at the next vblank :(
11405          */
11406
11407         /*
11408          * A DSPSURFLIVE check isn't enough in case the mmio and CS flips
11409          * used the same base address. In that case the mmio flip might
11410          * have completed, but the CS hasn't even executed the flip yet.
11411          *
11412          * A flip count check isn't enough as the CS might have updated
11413          * the base address just after start of vblank, but before we
11414          * managed to process the interrupt. This means we'd complete the
11415          * CS flip too soon.
11416          *
11417          * Combining both checks should get us a good enough result. It may
11418          * still happen that the CS flip has been executed, but has not
11419          * yet actually completed. But in case the base address is the same
11420          * anyway, we don't really care.
11421          */
11422         return (I915_READ(DSPSURFLIVE(crtc->plane)) & ~0xfff) ==
11423                 crtc->flip_work->gtt_offset &&
11424                 g4x_flip_count_after_eq(I915_READ(PIPE_FLIPCOUNT_G4X(crtc->pipe)),
11425                                     crtc->flip_work->flip_count);
11426 }
11427
11428 static bool
11429 __pageflip_finished_mmio(struct intel_crtc *crtc,
11430                                struct intel_flip_work *work)
11431 {
11432         /*
11433          * MMIO work completes when vblank is different from
11434          * flip_queued_vblank.
11435          *
11436          * Reset counter value doesn't matter, this is handled by
11437          * i915_wait_request finishing early, so no need to handle
11438          * reset here.
11439          */
11440         return intel_crtc_get_vblank_counter(crtc) != work->flip_queued_vblank;
11441 }
11442
11443
11444 static bool pageflip_finished(struct intel_crtc *crtc,
11445                               struct intel_flip_work *work)
11446 {
11447         if (!atomic_read(&work->pending))
11448                 return false;
11449
11450         smp_rmb();
11451
11452         if (is_mmio_work(work))
11453                 return __pageflip_finished_mmio(crtc, work);
11454         else
11455                 return __pageflip_finished_cs(crtc, work);
11456 }
11457
11458 void intel_finish_page_flip_cs(struct drm_i915_private *dev_priv, int pipe)
11459 {
11460         struct drm_device *dev = &dev_priv->drm;
11461         struct drm_crtc *crtc = dev_priv->pipe_to_crtc_mapping[pipe];
11462         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11463         struct intel_flip_work *work;
11464         unsigned long flags;
11465
11466         /* Ignore early vblank irqs */
11467         if (!crtc)
11468                 return;
11469
11470         /*
11471          * This is called both by irq handlers and the reset code (to complete
11472          * lost pageflips) so needs the full irqsave spinlocks.
11473          */
11474         spin_lock_irqsave(&dev->event_lock, flags);
11475         work = intel_crtc->flip_work;
11476
11477         if (work != NULL &&
11478             !is_mmio_work(work) &&
11479             pageflip_finished(intel_crtc, work))
11480                 page_flip_completed(intel_crtc);
11481
11482         spin_unlock_irqrestore(&dev->event_lock, flags);
11483 }
11484
11485 void intel_finish_page_flip_mmio(struct drm_i915_private *dev_priv, int pipe)
11486 {
11487         struct drm_device *dev = &dev_priv->drm;
11488         struct drm_crtc *crtc = dev_priv->pipe_to_crtc_mapping[pipe];
11489         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11490         struct intel_flip_work *work;
11491         unsigned long flags;
11492
11493         /* Ignore early vblank irqs */
11494         if (!crtc)
11495                 return;
11496
11497         /*
11498          * This is called both by irq handlers and the reset code (to complete
11499          * lost pageflips) so needs the full irqsave spinlocks.
11500          */
11501         spin_lock_irqsave(&dev->event_lock, flags);
11502         work = intel_crtc->flip_work;
11503
11504         if (work != NULL &&
11505             is_mmio_work(work) &&
11506             pageflip_finished(intel_crtc, work))
11507                 page_flip_completed(intel_crtc);
11508
11509         spin_unlock_irqrestore(&dev->event_lock, flags);
11510 }
11511
11512 static inline void intel_mark_page_flip_active(struct intel_crtc *crtc,
11513                                                struct intel_flip_work *work)
11514 {
11515         work->flip_queued_vblank = intel_crtc_get_vblank_counter(crtc);
11516
11517         /* Ensure that the work item is consistent when activating it ... */
11518         smp_mb__before_atomic();
11519         atomic_set(&work->pending, 1);
11520 }
11521
11522 static int intel_gen2_queue_flip(struct drm_device *dev,
11523                                  struct drm_crtc *crtc,
11524                                  struct drm_framebuffer *fb,
11525                                  struct drm_i915_gem_object *obj,
11526                                  struct drm_i915_gem_request *req,
11527                                  uint32_t flags)
11528 {
11529         struct intel_ring *ring = req->ring;
11530         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11531         u32 flip_mask;
11532         int ret;
11533
11534         ret = intel_ring_begin(req, 6);
11535         if (ret)
11536                 return ret;
11537
11538         /* Can't queue multiple flips, so wait for the previous
11539          * one to finish before executing the next.
11540          */
11541         if (intel_crtc->plane)
11542                 flip_mask = MI_WAIT_FOR_PLANE_B_FLIP;
11543         else
11544                 flip_mask = MI_WAIT_FOR_PLANE_A_FLIP;
11545         intel_ring_emit(ring, MI_WAIT_FOR_EVENT | flip_mask);
11546         intel_ring_emit(ring, MI_NOOP);
11547         intel_ring_emit(ring, MI_DISPLAY_FLIP |
11548                         MI_DISPLAY_FLIP_PLANE(intel_crtc->plane));
11549         intel_ring_emit(ring, fb->pitches[0]);
11550         intel_ring_emit(ring, intel_crtc->flip_work->gtt_offset);
11551         intel_ring_emit(ring, 0); /* aux display base address, unused */
11552
11553         return 0;
11554 }
11555
11556 static int intel_gen3_queue_flip(struct drm_device *dev,
11557                                  struct drm_crtc *crtc,
11558                                  struct drm_framebuffer *fb,
11559                                  struct drm_i915_gem_object *obj,
11560                                  struct drm_i915_gem_request *req,
11561                                  uint32_t flags)
11562 {
11563         struct intel_ring *ring = req->ring;
11564         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11565         u32 flip_mask;
11566         int ret;
11567
11568         ret = intel_ring_begin(req, 6);
11569         if (ret)
11570                 return ret;
11571
11572         if (intel_crtc->plane)
11573                 flip_mask = MI_WAIT_FOR_PLANE_B_FLIP;
11574         else
11575                 flip_mask = MI_WAIT_FOR_PLANE_A_FLIP;
11576         intel_ring_emit(ring, MI_WAIT_FOR_EVENT | flip_mask);
11577         intel_ring_emit(ring, MI_NOOP);
11578         intel_ring_emit(ring, MI_DISPLAY_FLIP_I915 |
11579                         MI_DISPLAY_FLIP_PLANE(intel_crtc->plane));
11580         intel_ring_emit(ring, fb->pitches[0]);
11581         intel_ring_emit(ring, intel_crtc->flip_work->gtt_offset);
11582         intel_ring_emit(ring, MI_NOOP);
11583
11584         return 0;
11585 }
11586
11587 static int intel_gen4_queue_flip(struct drm_device *dev,
11588                                  struct drm_crtc *crtc,
11589                                  struct drm_framebuffer *fb,
11590                                  struct drm_i915_gem_object *obj,
11591                                  struct drm_i915_gem_request *req,
11592                                  uint32_t flags)
11593 {
11594         struct intel_ring *ring = req->ring;
11595         struct drm_i915_private *dev_priv = to_i915(dev);
11596         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11597         uint32_t pf, pipesrc;
11598         int ret;
11599
11600         ret = intel_ring_begin(req, 4);
11601         if (ret)
11602                 return ret;
11603
11604         /* i965+ uses the linear or tiled offsets from the
11605          * Display Registers (which do not change across a page-flip)
11606          * so we need only reprogram the base address.
11607          */
11608         intel_ring_emit(ring, MI_DISPLAY_FLIP |
11609                         MI_DISPLAY_FLIP_PLANE(intel_crtc->plane));
11610         intel_ring_emit(ring, fb->pitches[0]);
11611         intel_ring_emit(ring, intel_crtc->flip_work->gtt_offset |
11612                         intel_fb_modifier_to_tiling(fb->modifier[0]));
11613
11614         /* XXX Enabling the panel-fitter across page-flip is so far
11615          * untested on non-native modes, so ignore it for now.
11616          * pf = I915_READ(pipe == 0 ? PFA_CTL_1 : PFB_CTL_1) & PF_ENABLE;
11617          */
11618         pf = 0;
11619         pipesrc = I915_READ(PIPESRC(intel_crtc->pipe)) & 0x0fff0fff;
11620         intel_ring_emit(ring, pf | pipesrc);
11621
11622         return 0;
11623 }
11624
11625 static int intel_gen6_queue_flip(struct drm_device *dev,
11626                                  struct drm_crtc *crtc,
11627                                  struct drm_framebuffer *fb,
11628                                  struct drm_i915_gem_object *obj,
11629                                  struct drm_i915_gem_request *req,
11630                                  uint32_t flags)
11631 {
11632         struct intel_ring *ring = req->ring;
11633         struct drm_i915_private *dev_priv = to_i915(dev);
11634         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11635         uint32_t pf, pipesrc;
11636         int ret;
11637
11638         ret = intel_ring_begin(req, 4);
11639         if (ret)
11640                 return ret;
11641
11642         intel_ring_emit(ring, MI_DISPLAY_FLIP |
11643                         MI_DISPLAY_FLIP_PLANE(intel_crtc->plane));
11644         intel_ring_emit(ring, fb->pitches[0] |
11645                         intel_fb_modifier_to_tiling(fb->modifier[0]));
11646         intel_ring_emit(ring, intel_crtc->flip_work->gtt_offset);
11647
11648         /* Contrary to the suggestions in the documentation,
11649          * "Enable Panel Fitter" does not seem to be required when page
11650          * flipping with a non-native mode, and worse causes a normal
11651          * modeset to fail.
11652          * pf = I915_READ(PF_CTL(intel_crtc->pipe)) & PF_ENABLE;
11653          */
11654         pf = 0;
11655         pipesrc = I915_READ(PIPESRC(intel_crtc->pipe)) & 0x0fff0fff;
11656         intel_ring_emit(ring, pf | pipesrc);
11657
11658         return 0;
11659 }
11660
11661 static int intel_gen7_queue_flip(struct drm_device *dev,
11662                                  struct drm_crtc *crtc,
11663                                  struct drm_framebuffer *fb,
11664                                  struct drm_i915_gem_object *obj,
11665                                  struct drm_i915_gem_request *req,
11666                                  uint32_t flags)
11667 {
11668         struct intel_ring *ring = req->ring;
11669         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11670         uint32_t plane_bit = 0;
11671         int len, ret;
11672
11673         switch (intel_crtc->plane) {
11674         case PLANE_A:
11675                 plane_bit = MI_DISPLAY_FLIP_IVB_PLANE_A;
11676                 break;
11677         case PLANE_B:
11678                 plane_bit = MI_DISPLAY_FLIP_IVB_PLANE_B;
11679                 break;
11680         case PLANE_C:
11681                 plane_bit = MI_DISPLAY_FLIP_IVB_PLANE_C;
11682                 break;
11683         default:
11684                 WARN_ONCE(1, "unknown plane in flip command\n");
11685                 return -ENODEV;
11686         }
11687
11688         len = 4;
11689         if (req->engine->id == RCS) {
11690                 len += 6;
11691                 /*
11692                  * On Gen 8, SRM is now taking an extra dword to accommodate
11693                  * 48bits addresses, and we need a NOOP for the batch size to
11694                  * stay even.
11695                  */
11696                 if (IS_GEN8(dev))
11697                         len += 2;
11698         }
11699
11700         /*
11701          * BSpec MI_DISPLAY_FLIP for IVB:
11702          * "The full packet must be contained within the same cache line."
11703          *
11704          * Currently the LRI+SRM+MI_DISPLAY_FLIP all fit within the same
11705          * cacheline, if we ever start emitting more commands before
11706          * the MI_DISPLAY_FLIP we may need to first emit everything else,
11707          * then do the cacheline alignment, and finally emit the
11708          * MI_DISPLAY_FLIP.
11709          */
11710         ret = intel_ring_cacheline_align(req);
11711         if (ret)
11712                 return ret;
11713
11714         ret = intel_ring_begin(req, len);
11715         if (ret)
11716                 return ret;
11717
11718         /* Unmask the flip-done completion message. Note that the bspec says that
11719          * we should do this for both the BCS and RCS, and that we must not unmask
11720          * more than one flip event at any time (or ensure that one flip message
11721          * can be sent by waiting for flip-done prior to queueing new flips).
11722          * Experimentation says that BCS works despite DERRMR masking all
11723          * flip-done completion events and that unmasking all planes at once
11724          * for the RCS also doesn't appear to drop events. Setting the DERRMR
11725          * to zero does lead to lockups within MI_DISPLAY_FLIP.
11726          */
11727         if (req->engine->id == RCS) {
11728                 intel_ring_emit(ring, MI_LOAD_REGISTER_IMM(1));
11729                 intel_ring_emit_reg(ring, DERRMR);
11730                 intel_ring_emit(ring, ~(DERRMR_PIPEA_PRI_FLIP_DONE |
11731                                           DERRMR_PIPEB_PRI_FLIP_DONE |
11732                                           DERRMR_PIPEC_PRI_FLIP_DONE));
11733                 if (IS_GEN8(dev))
11734                         intel_ring_emit(ring, MI_STORE_REGISTER_MEM_GEN8 |
11735                                               MI_SRM_LRM_GLOBAL_GTT);
11736                 else
11737                         intel_ring_emit(ring, MI_STORE_REGISTER_MEM |
11738                                               MI_SRM_LRM_GLOBAL_GTT);
11739                 intel_ring_emit_reg(ring, DERRMR);
11740                 intel_ring_emit(ring, req->engine->scratch.gtt_offset + 256);
11741                 if (IS_GEN8(dev)) {
11742                         intel_ring_emit(ring, 0);
11743                         intel_ring_emit(ring, MI_NOOP);
11744                 }
11745         }
11746
11747         intel_ring_emit(ring, MI_DISPLAY_FLIP_I915 | plane_bit);
11748         intel_ring_emit(ring, fb->pitches[0] |
11749                         intel_fb_modifier_to_tiling(fb->modifier[0]));
11750         intel_ring_emit(ring, intel_crtc->flip_work->gtt_offset);
11751         intel_ring_emit(ring, (MI_NOOP));
11752
11753         return 0;
11754 }
11755
11756 static bool use_mmio_flip(struct intel_engine_cs *engine,
11757                           struct drm_i915_gem_object *obj)
11758 {
11759         struct reservation_object *resv;
11760
11761         /*
11762          * This is not being used for older platforms, because
11763          * non-availability of flip done interrupt forces us to use
11764          * CS flips. Older platforms derive flip done using some clever
11765          * tricks involving the flip_pending status bits and vblank irqs.
11766          * So using MMIO flips there would disrupt this mechanism.
11767          */
11768
11769         if (engine == NULL)
11770                 return true;
11771
11772         if (INTEL_GEN(engine->i915) < 5)
11773                 return false;
11774
11775         if (i915.use_mmio_flip < 0)
11776                 return false;
11777         else if (i915.use_mmio_flip > 0)
11778                 return true;
11779         else if (i915.enable_execlists)
11780                 return true;
11781
11782         resv = i915_gem_object_get_dmabuf_resv(obj);
11783         if (resv && !reservation_object_test_signaled_rcu(resv, false))
11784                 return true;
11785
11786         return engine != i915_gem_active_get_engine(&obj->last_write,
11787                                                     &obj->base.dev->struct_mutex);
11788 }
11789
11790 static void skl_do_mmio_flip(struct intel_crtc *intel_crtc,
11791                              unsigned int rotation,
11792                              struct intel_flip_work *work)
11793 {
11794         struct drm_device *dev = intel_crtc->base.dev;
11795         struct drm_i915_private *dev_priv = to_i915(dev);
11796         struct drm_framebuffer *fb = intel_crtc->base.primary->fb;
11797         const enum pipe pipe = intel_crtc->pipe;
11798         u32 ctl, stride = skl_plane_stride(fb, 0, rotation);
11799
11800         ctl = I915_READ(PLANE_CTL(pipe, 0));
11801         ctl &= ~PLANE_CTL_TILED_MASK;
11802         switch (fb->modifier[0]) {
11803         case DRM_FORMAT_MOD_NONE:
11804                 break;
11805         case I915_FORMAT_MOD_X_TILED:
11806                 ctl |= PLANE_CTL_TILED_X;
11807                 break;
11808         case I915_FORMAT_MOD_Y_TILED:
11809                 ctl |= PLANE_CTL_TILED_Y;
11810                 break;
11811         case I915_FORMAT_MOD_Yf_TILED:
11812                 ctl |= PLANE_CTL_TILED_YF;
11813                 break;
11814         default:
11815                 MISSING_CASE(fb->modifier[0]);
11816         }
11817
11818         /*
11819          * Both PLANE_CTL and PLANE_STRIDE are not updated on vblank but on
11820          * PLANE_SURF updates, the update is then guaranteed to be atomic.
11821          */
11822         I915_WRITE(PLANE_CTL(pipe, 0), ctl);
11823         I915_WRITE(PLANE_STRIDE(pipe, 0), stride);
11824
11825         I915_WRITE(PLANE_SURF(pipe, 0), work->gtt_offset);
11826         POSTING_READ(PLANE_SURF(pipe, 0));
11827 }
11828
11829 static void ilk_do_mmio_flip(struct intel_crtc *intel_crtc,
11830                              struct intel_flip_work *work)
11831 {
11832         struct drm_device *dev = intel_crtc->base.dev;
11833         struct drm_i915_private *dev_priv = to_i915(dev);
11834         struct drm_framebuffer *fb = intel_crtc->base.primary->fb;
11835         i915_reg_t reg = DSPCNTR(intel_crtc->plane);
11836         u32 dspcntr;
11837
11838         dspcntr = I915_READ(reg);
11839
11840         if (fb->modifier[0] == I915_FORMAT_MOD_X_TILED)
11841                 dspcntr |= DISPPLANE_TILED;
11842         else
11843                 dspcntr &= ~DISPPLANE_TILED;
11844
11845         I915_WRITE(reg, dspcntr);
11846
11847         I915_WRITE(DSPSURF(intel_crtc->plane), work->gtt_offset);
11848         POSTING_READ(DSPSURF(intel_crtc->plane));
11849 }
11850
11851 static void intel_mmio_flip_work_func(struct work_struct *w)
11852 {
11853         struct intel_flip_work *work =
11854                 container_of(w, struct intel_flip_work, mmio_work);
11855         struct intel_crtc *crtc = to_intel_crtc(work->crtc);
11856         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
11857         struct intel_framebuffer *intel_fb =
11858                 to_intel_framebuffer(crtc->base.primary->fb);
11859         struct drm_i915_gem_object *obj = intel_fb->obj;
11860         struct reservation_object *resv;
11861
11862         if (work->flip_queued_req)
11863                 WARN_ON(i915_wait_request(work->flip_queued_req,
11864                                           false, NULL,
11865                                           NO_WAITBOOST));
11866
11867         /* For framebuffer backed by dmabuf, wait for fence */
11868         resv = i915_gem_object_get_dmabuf_resv(obj);
11869         if (resv)
11870                 WARN_ON(reservation_object_wait_timeout_rcu(resv, false, false,
11871                                                             MAX_SCHEDULE_TIMEOUT) < 0);
11872
11873         intel_pipe_update_start(crtc);
11874
11875         if (INTEL_GEN(dev_priv) >= 9)
11876                 skl_do_mmio_flip(crtc, work->rotation, work);
11877         else
11878                 /* use_mmio_flip() retricts MMIO flips to ilk+ */
11879                 ilk_do_mmio_flip(crtc, work);
11880
11881         intel_pipe_update_end(crtc, work);
11882 }
11883
11884 static int intel_default_queue_flip(struct drm_device *dev,
11885                                     struct drm_crtc *crtc,
11886                                     struct drm_framebuffer *fb,
11887                                     struct drm_i915_gem_object *obj,
11888                                     struct drm_i915_gem_request *req,
11889                                     uint32_t flags)
11890 {
11891         return -ENODEV;
11892 }
11893
11894 static bool __pageflip_stall_check_cs(struct drm_i915_private *dev_priv,
11895                                       struct intel_crtc *intel_crtc,
11896                                       struct intel_flip_work *work)
11897 {
11898         u32 addr, vblank;
11899
11900         if (!atomic_read(&work->pending))
11901                 return false;
11902
11903         smp_rmb();
11904
11905         vblank = intel_crtc_get_vblank_counter(intel_crtc);
11906         if (work->flip_ready_vblank == 0) {
11907                 if (work->flip_queued_req &&
11908                     !i915_gem_request_completed(work->flip_queued_req))
11909                         return false;
11910
11911                 work->flip_ready_vblank = vblank;
11912         }
11913
11914         if (vblank - work->flip_ready_vblank < 3)
11915                 return false;
11916
11917         /* Potential stall - if we see that the flip has happened,
11918          * assume a missed interrupt. */
11919         if (INTEL_GEN(dev_priv) >= 4)
11920                 addr = I915_HI_DISPBASE(I915_READ(DSPSURF(intel_crtc->plane)));
11921         else
11922                 addr = I915_READ(DSPADDR(intel_crtc->plane));
11923
11924         /* There is a potential issue here with a false positive after a flip
11925          * to the same address. We could address this by checking for a
11926          * non-incrementing frame counter.
11927          */
11928         return addr == work->gtt_offset;
11929 }
11930
11931 void intel_check_page_flip(struct drm_i915_private *dev_priv, int pipe)
11932 {
11933         struct drm_device *dev = &dev_priv->drm;
11934         struct drm_crtc *crtc = dev_priv->pipe_to_crtc_mapping[pipe];
11935         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11936         struct intel_flip_work *work;
11937
11938         WARN_ON(!in_interrupt());
11939
11940         if (crtc == NULL)
11941                 return;
11942
11943         spin_lock(&dev->event_lock);
11944         work = intel_crtc->flip_work;
11945
11946         if (work != NULL && !is_mmio_work(work) &&
11947             __pageflip_stall_check_cs(dev_priv, intel_crtc, work)) {
11948                 WARN_ONCE(1,
11949                           "Kicking stuck page flip: queued at %d, now %d\n",
11950                         work->flip_queued_vblank, intel_crtc_get_vblank_counter(intel_crtc));
11951                 page_flip_completed(intel_crtc);
11952                 work = NULL;
11953         }
11954
11955         if (work != NULL && !is_mmio_work(work) &&
11956             intel_crtc_get_vblank_counter(intel_crtc) - work->flip_queued_vblank > 1)
11957                 intel_queue_rps_boost_for_request(work->flip_queued_req);
11958         spin_unlock(&dev->event_lock);
11959 }
11960
11961 static int intel_crtc_page_flip(struct drm_crtc *crtc,
11962                                 struct drm_framebuffer *fb,
11963                                 struct drm_pending_vblank_event *event,
11964                                 uint32_t page_flip_flags)
11965 {
11966         struct drm_device *dev = crtc->dev;
11967         struct drm_i915_private *dev_priv = to_i915(dev);
11968         struct drm_framebuffer *old_fb = crtc->primary->fb;
11969         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
11970         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11971         struct drm_plane *primary = crtc->primary;
11972         enum pipe pipe = intel_crtc->pipe;
11973         struct intel_flip_work *work;
11974         struct intel_engine_cs *engine;
11975         bool mmio_flip;
11976         struct drm_i915_gem_request *request;
11977         int ret;
11978
11979         /*
11980          * drm_mode_page_flip_ioctl() should already catch this, but double
11981          * check to be safe.  In the future we may enable pageflipping from
11982          * a disabled primary plane.
11983          */
11984         if (WARN_ON(intel_fb_obj(old_fb) == NULL))
11985                 return -EBUSY;
11986
11987         /* Can't change pixel format via MI display flips. */
11988         if (fb->pixel_format != crtc->primary->fb->pixel_format)
11989                 return -EINVAL;
11990
11991         /*
11992          * TILEOFF/LINOFF registers can't be changed via MI display flips.
11993          * Note that pitch changes could also affect these register.
11994          */
11995         if (INTEL_INFO(dev)->gen > 3 &&
11996             (fb->offsets[0] != crtc->primary->fb->offsets[0] ||
11997              fb->pitches[0] != crtc->primary->fb->pitches[0]))
11998                 return -EINVAL;
11999
12000         if (i915_terminally_wedged(&dev_priv->gpu_error))
12001                 goto out_hang;
12002
12003         work = kzalloc(sizeof(*work), GFP_KERNEL);
12004         if (work == NULL)
12005                 return -ENOMEM;
12006
12007         work->event = event;
12008         work->crtc = crtc;
12009         work->old_fb = old_fb;
12010         INIT_WORK(&work->unpin_work, intel_unpin_work_fn);
12011
12012         ret = drm_crtc_vblank_get(crtc);
12013         if (ret)
12014                 goto free_work;
12015
12016         /* We borrow the event spin lock for protecting flip_work */
12017         spin_lock_irq(&dev->event_lock);
12018         if (intel_crtc->flip_work) {
12019                 /* Before declaring the flip queue wedged, check if
12020                  * the hardware completed the operation behind our backs.
12021                  */
12022                 if (pageflip_finished(intel_crtc, intel_crtc->flip_work)) {
12023                         DRM_DEBUG_DRIVER("flip queue: previous flip completed, continuing\n");
12024                         page_flip_completed(intel_crtc);
12025                 } else {
12026                         DRM_DEBUG_DRIVER("flip queue: crtc already busy\n");
12027                         spin_unlock_irq(&dev->event_lock);
12028
12029                         drm_crtc_vblank_put(crtc);
12030                         kfree(work);
12031                         return -EBUSY;
12032                 }
12033         }
12034         intel_crtc->flip_work = work;
12035         spin_unlock_irq(&dev->event_lock);
12036
12037         if (atomic_read(&intel_crtc->unpin_work_count) >= 2)
12038                 flush_workqueue(dev_priv->wq);
12039
12040         /* Reference the objects for the scheduled work. */
12041         drm_framebuffer_reference(work->old_fb);
12042
12043         crtc->primary->fb = fb;
12044         update_state_fb(crtc->primary);
12045
12046         intel_fbc_pre_update(intel_crtc, intel_crtc->config,
12047                              to_intel_plane_state(primary->state));
12048
12049         work->pending_flip_obj = i915_gem_object_get(obj);
12050
12051         ret = i915_mutex_lock_interruptible(dev);
12052         if (ret)
12053                 goto cleanup;
12054
12055         intel_crtc->reset_counter = i915_reset_counter(&dev_priv->gpu_error);
12056         if (__i915_reset_in_progress_or_wedged(intel_crtc->reset_counter)) {
12057                 ret = -EIO;
12058                 goto cleanup;
12059         }
12060
12061         atomic_inc(&intel_crtc->unpin_work_count);
12062
12063         if (INTEL_INFO(dev)->gen >= 5 || IS_G4X(dev))
12064                 work->flip_count = I915_READ(PIPE_FLIPCOUNT_G4X(pipe)) + 1;
12065
12066         if (IS_VALLEYVIEW(dev) || IS_CHERRYVIEW(dev)) {
12067                 engine = &dev_priv->engine[BCS];
12068                 if (fb->modifier[0] != old_fb->modifier[0])
12069                         /* vlv: DISPLAY_FLIP fails to change tiling */
12070                         engine = NULL;
12071         } else if (IS_IVYBRIDGE(dev) || IS_HASWELL(dev)) {
12072                 engine = &dev_priv->engine[BCS];
12073         } else if (INTEL_INFO(dev)->gen >= 7) {
12074                 engine = i915_gem_active_get_engine(&obj->last_write,
12075                                                     &obj->base.dev->struct_mutex);
12076                 if (engine == NULL || engine->id != RCS)
12077                         engine = &dev_priv->engine[BCS];
12078         } else {
12079                 engine = &dev_priv->engine[RCS];
12080         }
12081
12082         mmio_flip = use_mmio_flip(engine, obj);
12083
12084         ret = intel_pin_and_fence_fb_obj(fb, primary->state->rotation);
12085         if (ret)
12086                 goto cleanup_pending;
12087
12088         work->gtt_offset = intel_fb_gtt_offset(fb, primary->state->rotation);
12089         work->gtt_offset += intel_crtc->dspaddr_offset;
12090         work->rotation = crtc->primary->state->rotation;
12091
12092         if (mmio_flip) {
12093                 INIT_WORK(&work->mmio_work, intel_mmio_flip_work_func);
12094
12095                 work->flip_queued_req = i915_gem_active_get(&obj->last_write,
12096                                                             &obj->base.dev->struct_mutex);
12097                 schedule_work(&work->mmio_work);
12098         } else {
12099                 request = i915_gem_request_alloc(engine, engine->last_context);
12100                 if (IS_ERR(request)) {
12101                         ret = PTR_ERR(request);
12102                         goto cleanup_unpin;
12103                 }
12104
12105                 ret = i915_gem_object_sync(obj, request);
12106                 if (ret)
12107                         goto cleanup_request;
12108
12109                 ret = dev_priv->display.queue_flip(dev, crtc, fb, obj, request,
12110                                                    page_flip_flags);
12111                 if (ret)
12112                         goto cleanup_request;
12113
12114                 intel_mark_page_flip_active(intel_crtc, work);
12115
12116                 work->flip_queued_req = i915_gem_request_get(request);
12117                 i915_add_request_no_flush(request);
12118         }
12119
12120         i915_gem_track_fb(intel_fb_obj(old_fb), obj,
12121                           to_intel_plane(primary)->frontbuffer_bit);
12122         mutex_unlock(&dev->struct_mutex);
12123
12124         intel_frontbuffer_flip_prepare(to_i915(dev),
12125                                        to_intel_plane(primary)->frontbuffer_bit);
12126
12127         trace_i915_flip_request(intel_crtc->plane, obj);
12128
12129         return 0;
12130
12131 cleanup_request:
12132         i915_add_request_no_flush(request);
12133 cleanup_unpin:
12134         intel_unpin_fb_obj(fb, crtc->primary->state->rotation);
12135 cleanup_pending:
12136         atomic_dec(&intel_crtc->unpin_work_count);
12137         mutex_unlock(&dev->struct_mutex);
12138 cleanup:
12139         crtc->primary->fb = old_fb;
12140         update_state_fb(crtc->primary);
12141
12142         i915_gem_object_put_unlocked(obj);
12143         drm_framebuffer_unreference(work->old_fb);
12144
12145         spin_lock_irq(&dev->event_lock);
12146         intel_crtc->flip_work = NULL;
12147         spin_unlock_irq(&dev->event_lock);
12148
12149         drm_crtc_vblank_put(crtc);
12150 free_work:
12151         kfree(work);
12152
12153         if (ret == -EIO) {
12154                 struct drm_atomic_state *state;
12155                 struct drm_plane_state *plane_state;
12156
12157 out_hang:
12158                 state = drm_atomic_state_alloc(dev);
12159                 if (!state)
12160                         return -ENOMEM;
12161                 state->acquire_ctx = drm_modeset_legacy_acquire_ctx(crtc);
12162
12163 retry:
12164                 plane_state = drm_atomic_get_plane_state(state, primary);
12165                 ret = PTR_ERR_OR_ZERO(plane_state);
12166                 if (!ret) {
12167                         drm_atomic_set_fb_for_plane(plane_state, fb);
12168
12169                         ret = drm_atomic_set_crtc_for_plane(plane_state, crtc);
12170                         if (!ret)
12171                                 ret = drm_atomic_commit(state);
12172                 }
12173
12174                 if (ret == -EDEADLK) {
12175                         drm_modeset_backoff(state->acquire_ctx);
12176                         drm_atomic_state_clear(state);
12177                         goto retry;
12178                 }
12179
12180                 if (ret)
12181                         drm_atomic_state_free(state);
12182
12183                 if (ret == 0 && event) {
12184                         spin_lock_irq(&dev->event_lock);
12185                         drm_crtc_send_vblank_event(crtc, event);
12186                         spin_unlock_irq(&dev->event_lock);
12187                 }
12188         }
12189         return ret;
12190 }
12191
12192
12193 /**
12194  * intel_wm_need_update - Check whether watermarks need updating
12195  * @plane: drm plane
12196  * @state: new plane state
12197  *
12198  * Check current plane state versus the new one to determine whether
12199  * watermarks need to be recalculated.
12200  *
12201  * Returns true or false.
12202  */
12203 static bool intel_wm_need_update(struct drm_plane *plane,
12204                                  struct drm_plane_state *state)
12205 {
12206         struct intel_plane_state *new = to_intel_plane_state(state);
12207         struct intel_plane_state *cur = to_intel_plane_state(plane->state);
12208
12209         /* Update watermarks on tiling or size changes. */
12210         if (new->visible != cur->visible)
12211                 return true;
12212
12213         if (!cur->base.fb || !new->base.fb)
12214                 return false;
12215
12216         if (cur->base.fb->modifier[0] != new->base.fb->modifier[0] ||
12217             cur->base.rotation != new->base.rotation ||
12218             drm_rect_width(&new->src) != drm_rect_width(&cur->src) ||
12219             drm_rect_height(&new->src) != drm_rect_height(&cur->src) ||
12220             drm_rect_width(&new->dst) != drm_rect_width(&cur->dst) ||
12221             drm_rect_height(&new->dst) != drm_rect_height(&cur->dst))
12222                 return true;
12223
12224         return false;
12225 }
12226
12227 static bool needs_scaling(struct intel_plane_state *state)
12228 {
12229         int src_w = drm_rect_width(&state->src) >> 16;
12230         int src_h = drm_rect_height(&state->src) >> 16;
12231         int dst_w = drm_rect_width(&state->dst);
12232         int dst_h = drm_rect_height(&state->dst);
12233
12234         return (src_w != dst_w || src_h != dst_h);
12235 }
12236
12237 int intel_plane_atomic_calc_changes(struct drm_crtc_state *crtc_state,
12238                                     struct drm_plane_state *plane_state)
12239 {
12240         struct intel_crtc_state *pipe_config = to_intel_crtc_state(crtc_state);
12241         struct drm_crtc *crtc = crtc_state->crtc;
12242         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
12243         struct drm_plane *plane = plane_state->plane;
12244         struct drm_device *dev = crtc->dev;
12245         struct drm_i915_private *dev_priv = to_i915(dev);
12246         struct intel_plane_state *old_plane_state =
12247                 to_intel_plane_state(plane->state);
12248         bool mode_changed = needs_modeset(crtc_state);
12249         bool was_crtc_enabled = crtc->state->active;
12250         bool is_crtc_enabled = crtc_state->active;
12251         bool turn_off, turn_on, visible, was_visible;
12252         struct drm_framebuffer *fb = plane_state->fb;
12253         int ret;
12254
12255         if (INTEL_GEN(dev) >= 9 && plane->type != DRM_PLANE_TYPE_CURSOR) {
12256                 ret = skl_update_scaler_plane(
12257                         to_intel_crtc_state(crtc_state),
12258                         to_intel_plane_state(plane_state));
12259                 if (ret)
12260                         return ret;
12261         }
12262
12263         was_visible = old_plane_state->visible;
12264         visible = to_intel_plane_state(plane_state)->visible;
12265
12266         if (!was_crtc_enabled && WARN_ON(was_visible))
12267                 was_visible = false;
12268
12269         /*
12270          * Visibility is calculated as if the crtc was on, but
12271          * after scaler setup everything depends on it being off
12272          * when the crtc isn't active.
12273          *
12274          * FIXME this is wrong for watermarks. Watermarks should also
12275          * be computed as if the pipe would be active. Perhaps move
12276          * per-plane wm computation to the .check_plane() hook, and
12277          * only combine the results from all planes in the current place?
12278          */
12279         if (!is_crtc_enabled)
12280                 to_intel_plane_state(plane_state)->visible = visible = false;
12281
12282         if (!was_visible && !visible)
12283                 return 0;
12284
12285         if (fb != old_plane_state->base.fb)
12286                 pipe_config->fb_changed = true;
12287
12288         turn_off = was_visible && (!visible || mode_changed);
12289         turn_on = visible && (!was_visible || mode_changed);
12290
12291         DRM_DEBUG_ATOMIC("[CRTC:%d:%s] has [PLANE:%d:%s] with fb %i\n",
12292                          intel_crtc->base.base.id,
12293                          intel_crtc->base.name,
12294                          plane->base.id, plane->name,
12295                          fb ? fb->base.id : -1);
12296
12297         DRM_DEBUG_ATOMIC("[PLANE:%d:%s] visible %i -> %i, off %i, on %i, ms %i\n",
12298                          plane->base.id, plane->name,
12299                          was_visible, visible,
12300                          turn_off, turn_on, mode_changed);
12301
12302         if (turn_on) {
12303                 pipe_config->update_wm_pre = true;
12304
12305                 /* must disable cxsr around plane enable/disable */
12306                 if (plane->type != DRM_PLANE_TYPE_CURSOR)
12307                         pipe_config->disable_cxsr = true;
12308         } else if (turn_off) {
12309                 pipe_config->update_wm_post = true;
12310
12311                 /* must disable cxsr around plane enable/disable */
12312                 if (plane->type != DRM_PLANE_TYPE_CURSOR)
12313                         pipe_config->disable_cxsr = true;
12314         } else if (intel_wm_need_update(plane, plane_state)) {
12315                 /* FIXME bollocks */
12316                 pipe_config->update_wm_pre = true;
12317                 pipe_config->update_wm_post = true;
12318         }
12319
12320         /* Pre-gen9 platforms need two-step watermark updates */
12321         if ((pipe_config->update_wm_pre || pipe_config->update_wm_post) &&
12322             INTEL_INFO(dev)->gen < 9 && dev_priv->display.optimize_watermarks)
12323                 to_intel_crtc_state(crtc_state)->wm.need_postvbl_update = true;
12324
12325         if (visible || was_visible)
12326                 pipe_config->fb_bits |= to_intel_plane(plane)->frontbuffer_bit;
12327
12328         /*
12329          * WaCxSRDisabledForSpriteScaling:ivb
12330          *
12331          * cstate->update_wm was already set above, so this flag will
12332          * take effect when we commit and program watermarks.
12333          */
12334         if (plane->type == DRM_PLANE_TYPE_OVERLAY && IS_IVYBRIDGE(dev) &&
12335             needs_scaling(to_intel_plane_state(plane_state)) &&
12336             !needs_scaling(old_plane_state))
12337                 pipe_config->disable_lp_wm = true;
12338
12339         return 0;
12340 }
12341
12342 static bool encoders_cloneable(const struct intel_encoder *a,
12343                                const struct intel_encoder *b)
12344 {
12345         /* masks could be asymmetric, so check both ways */
12346         return a == b || (a->cloneable & (1 << b->type) &&
12347                           b->cloneable & (1 << a->type));
12348 }
12349
12350 static bool check_single_encoder_cloning(struct drm_atomic_state *state,
12351                                          struct intel_crtc *crtc,
12352                                          struct intel_encoder *encoder)
12353 {
12354         struct intel_encoder *source_encoder;
12355         struct drm_connector *connector;
12356         struct drm_connector_state *connector_state;
12357         int i;
12358
12359         for_each_connector_in_state(state, connector, connector_state, i) {
12360                 if (connector_state->crtc != &crtc->base)
12361                         continue;
12362
12363                 source_encoder =
12364                         to_intel_encoder(connector_state->best_encoder);
12365                 if (!encoders_cloneable(encoder, source_encoder))
12366                         return false;
12367         }
12368
12369         return true;
12370 }
12371
12372 static int intel_crtc_atomic_check(struct drm_crtc *crtc,
12373                                    struct drm_crtc_state *crtc_state)
12374 {
12375         struct drm_device *dev = crtc->dev;
12376         struct drm_i915_private *dev_priv = to_i915(dev);
12377         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
12378         struct intel_crtc_state *pipe_config =
12379                 to_intel_crtc_state(crtc_state);
12380         struct drm_atomic_state *state = crtc_state->state;
12381         int ret;
12382         bool mode_changed = needs_modeset(crtc_state);
12383
12384         if (mode_changed && !crtc_state->active)
12385                 pipe_config->update_wm_post = true;
12386
12387         if (mode_changed && crtc_state->enable &&
12388             dev_priv->display.crtc_compute_clock &&
12389             !WARN_ON(pipe_config->shared_dpll)) {
12390                 ret = dev_priv->display.crtc_compute_clock(intel_crtc,
12391                                                            pipe_config);
12392                 if (ret)
12393                         return ret;
12394         }
12395
12396         if (crtc_state->color_mgmt_changed) {
12397                 ret = intel_color_check(crtc, crtc_state);
12398                 if (ret)
12399                         return ret;
12400
12401                 /*
12402                  * Changing color management on Intel hardware is
12403                  * handled as part of planes update.
12404                  */
12405                 crtc_state->planes_changed = true;
12406         }
12407
12408         ret = 0;
12409         if (dev_priv->display.compute_pipe_wm) {
12410                 ret = dev_priv->display.compute_pipe_wm(pipe_config);
12411                 if (ret) {
12412                         DRM_DEBUG_KMS("Target pipe watermarks are invalid\n");
12413                         return ret;
12414                 }
12415         }
12416
12417         if (dev_priv->display.compute_intermediate_wm &&
12418             !to_intel_atomic_state(state)->skip_intermediate_wm) {
12419                 if (WARN_ON(!dev_priv->display.compute_pipe_wm))
12420                         return 0;
12421
12422                 /*
12423                  * Calculate 'intermediate' watermarks that satisfy both the
12424                  * old state and the new state.  We can program these
12425                  * immediately.
12426                  */
12427                 ret = dev_priv->display.compute_intermediate_wm(crtc->dev,
12428                                                                 intel_crtc,
12429                                                                 pipe_config);
12430                 if (ret) {
12431                         DRM_DEBUG_KMS("No valid intermediate pipe watermarks are possible\n");
12432                         return ret;
12433                 }
12434         } else if (dev_priv->display.compute_intermediate_wm) {
12435                 if (HAS_PCH_SPLIT(dev_priv) && INTEL_GEN(dev_priv) < 9)
12436                         pipe_config->wm.ilk.intermediate = pipe_config->wm.ilk.optimal;
12437         }
12438
12439         if (INTEL_INFO(dev)->gen >= 9) {
12440                 if (mode_changed)
12441                         ret = skl_update_scaler_crtc(pipe_config);
12442
12443                 if (!ret)
12444                         ret = intel_atomic_setup_scalers(dev, intel_crtc,
12445                                                          pipe_config);
12446         }
12447
12448         return ret;
12449 }
12450
12451 static const struct drm_crtc_helper_funcs intel_helper_funcs = {
12452         .mode_set_base_atomic = intel_pipe_set_base_atomic,
12453         .atomic_begin = intel_begin_crtc_commit,
12454         .atomic_flush = intel_finish_crtc_commit,
12455         .atomic_check = intel_crtc_atomic_check,
12456 };
12457
12458 static void intel_modeset_update_connector_atomic_state(struct drm_device *dev)
12459 {
12460         struct intel_connector *connector;
12461
12462         for_each_intel_connector(dev, connector) {
12463                 if (connector->base.state->crtc)
12464                         drm_connector_unreference(&connector->base);
12465
12466                 if (connector->base.encoder) {
12467                         connector->base.state->best_encoder =
12468                                 connector->base.encoder;
12469                         connector->base.state->crtc =
12470                                 connector->base.encoder->crtc;
12471
12472                         drm_connector_reference(&connector->base);
12473                 } else {
12474                         connector->base.state->best_encoder = NULL;
12475                         connector->base.state->crtc = NULL;
12476                 }
12477         }
12478 }
12479
12480 static void
12481 connected_sink_compute_bpp(struct intel_connector *connector,
12482                            struct intel_crtc_state *pipe_config)
12483 {
12484         int bpp = pipe_config->pipe_bpp;
12485
12486         DRM_DEBUG_KMS("[CONNECTOR:%d:%s] checking for sink bpp constrains\n",
12487                 connector->base.base.id,
12488                 connector->base.name);
12489
12490         /* Don't use an invalid EDID bpc value */
12491         if (connector->base.display_info.bpc &&
12492             connector->base.display_info.bpc * 3 < bpp) {
12493                 DRM_DEBUG_KMS("clamping display bpp (was %d) to EDID reported max of %d\n",
12494                               bpp, connector->base.display_info.bpc*3);
12495                 pipe_config->pipe_bpp = connector->base.display_info.bpc*3;
12496         }
12497
12498         /* Clamp bpp to default limit on screens without EDID 1.4 */
12499         if (connector->base.display_info.bpc == 0) {
12500                 int type = connector->base.connector_type;
12501                 int clamp_bpp = 24;
12502
12503                 /* Fall back to 18 bpp when DP sink capability is unknown. */
12504                 if (type == DRM_MODE_CONNECTOR_DisplayPort ||
12505                     type == DRM_MODE_CONNECTOR_eDP)
12506                         clamp_bpp = 18;
12507
12508                 if (bpp > clamp_bpp) {
12509                         DRM_DEBUG_KMS("clamping display bpp (was %d) to default limit of %d\n",
12510                                       bpp, clamp_bpp);
12511                         pipe_config->pipe_bpp = clamp_bpp;
12512                 }
12513         }
12514 }
12515
12516 static int
12517 compute_baseline_pipe_bpp(struct intel_crtc *crtc,
12518                           struct intel_crtc_state *pipe_config)
12519 {
12520         struct drm_device *dev = crtc->base.dev;
12521         struct drm_atomic_state *state;
12522         struct drm_connector *connector;
12523         struct drm_connector_state *connector_state;
12524         int bpp, i;
12525
12526         if ((IS_G4X(dev) || IS_VALLEYVIEW(dev) || IS_CHERRYVIEW(dev)))
12527                 bpp = 10*3;
12528         else if (INTEL_INFO(dev)->gen >= 5)
12529                 bpp = 12*3;
12530         else
12531                 bpp = 8*3;
12532
12533
12534         pipe_config->pipe_bpp = bpp;
12535
12536         state = pipe_config->base.state;
12537
12538         /* Clamp display bpp to EDID value */
12539         for_each_connector_in_state(state, connector, connector_state, i) {
12540                 if (connector_state->crtc != &crtc->base)
12541                         continue;
12542
12543                 connected_sink_compute_bpp(to_intel_connector(connector),
12544                                            pipe_config);
12545         }
12546
12547         return bpp;
12548 }
12549
12550 static void intel_dump_crtc_timings(const struct drm_display_mode *mode)
12551 {
12552         DRM_DEBUG_KMS("crtc timings: %d %d %d %d %d %d %d %d %d, "
12553                         "type: 0x%x flags: 0x%x\n",
12554                 mode->crtc_clock,
12555                 mode->crtc_hdisplay, mode->crtc_hsync_start,
12556                 mode->crtc_hsync_end, mode->crtc_htotal,
12557                 mode->crtc_vdisplay, mode->crtc_vsync_start,
12558                 mode->crtc_vsync_end, mode->crtc_vtotal, mode->type, mode->flags);
12559 }
12560
12561 static void intel_dump_pipe_config(struct intel_crtc *crtc,
12562                                    struct intel_crtc_state *pipe_config,
12563                                    const char *context)
12564 {
12565         struct drm_device *dev = crtc->base.dev;
12566         struct drm_plane *plane;
12567         struct intel_plane *intel_plane;
12568         struct intel_plane_state *state;
12569         struct drm_framebuffer *fb;
12570
12571         DRM_DEBUG_KMS("[CRTC:%d:%s]%s config %p for pipe %c\n",
12572                       crtc->base.base.id, crtc->base.name,
12573                       context, pipe_config, pipe_name(crtc->pipe));
12574
12575         DRM_DEBUG_KMS("cpu_transcoder: %s\n", transcoder_name(pipe_config->cpu_transcoder));
12576         DRM_DEBUG_KMS("pipe bpp: %i, dithering: %i\n",
12577                       pipe_config->pipe_bpp, pipe_config->dither);
12578         DRM_DEBUG_KMS("fdi/pch: %i, lanes: %i, gmch_m: %u, gmch_n: %u, link_m: %u, link_n: %u, tu: %u\n",
12579                       pipe_config->has_pch_encoder,
12580                       pipe_config->fdi_lanes,
12581                       pipe_config->fdi_m_n.gmch_m, pipe_config->fdi_m_n.gmch_n,
12582                       pipe_config->fdi_m_n.link_m, pipe_config->fdi_m_n.link_n,
12583                       pipe_config->fdi_m_n.tu);
12584         DRM_DEBUG_KMS("dp: %i, lanes: %i, gmch_m: %u, gmch_n: %u, link_m: %u, link_n: %u, tu: %u\n",
12585                       intel_crtc_has_dp_encoder(pipe_config),
12586                       pipe_config->lane_count,
12587                       pipe_config->dp_m_n.gmch_m, pipe_config->dp_m_n.gmch_n,
12588                       pipe_config->dp_m_n.link_m, pipe_config->dp_m_n.link_n,
12589                       pipe_config->dp_m_n.tu);
12590
12591         DRM_DEBUG_KMS("dp: %i, lanes: %i, gmch_m2: %u, gmch_n2: %u, link_m2: %u, link_n2: %u, tu2: %u\n",
12592                       intel_crtc_has_dp_encoder(pipe_config),
12593                       pipe_config->lane_count,
12594                       pipe_config->dp_m2_n2.gmch_m,
12595                       pipe_config->dp_m2_n2.gmch_n,
12596                       pipe_config->dp_m2_n2.link_m,
12597                       pipe_config->dp_m2_n2.link_n,
12598                       pipe_config->dp_m2_n2.tu);
12599
12600         DRM_DEBUG_KMS("audio: %i, infoframes: %i\n",
12601                       pipe_config->has_audio,
12602                       pipe_config->has_infoframe);
12603
12604         DRM_DEBUG_KMS("requested mode:\n");
12605         drm_mode_debug_printmodeline(&pipe_config->base.mode);
12606         DRM_DEBUG_KMS("adjusted mode:\n");
12607         drm_mode_debug_printmodeline(&pipe_config->base.adjusted_mode);
12608         intel_dump_crtc_timings(&pipe_config->base.adjusted_mode);
12609         DRM_DEBUG_KMS("port clock: %d\n", pipe_config->port_clock);
12610         DRM_DEBUG_KMS("pipe src size: %dx%d\n",
12611                       pipe_config->pipe_src_w, pipe_config->pipe_src_h);
12612         DRM_DEBUG_KMS("num_scalers: %d, scaler_users: 0x%x, scaler_id: %d\n",
12613                       crtc->num_scalers,
12614                       pipe_config->scaler_state.scaler_users,
12615                       pipe_config->scaler_state.scaler_id);
12616         DRM_DEBUG_KMS("gmch pfit: control: 0x%08x, ratios: 0x%08x, lvds border: 0x%08x\n",
12617                       pipe_config->gmch_pfit.control,
12618                       pipe_config->gmch_pfit.pgm_ratios,
12619                       pipe_config->gmch_pfit.lvds_border_bits);
12620         DRM_DEBUG_KMS("pch pfit: pos: 0x%08x, size: 0x%08x, %s\n",
12621                       pipe_config->pch_pfit.pos,
12622                       pipe_config->pch_pfit.size,
12623                       pipe_config->pch_pfit.enabled ? "enabled" : "disabled");
12624         DRM_DEBUG_KMS("ips: %i\n", pipe_config->ips_enabled);
12625         DRM_DEBUG_KMS("double wide: %i\n", pipe_config->double_wide);
12626
12627         if (IS_BROXTON(dev)) {
12628                 DRM_DEBUG_KMS("ddi_pll_sel: %u; dpll_hw_state: ebb0: 0x%x, ebb4: 0x%x,"
12629                               "pll0: 0x%x, pll1: 0x%x, pll2: 0x%x, pll3: 0x%x, "
12630                               "pll6: 0x%x, pll8: 0x%x, pll9: 0x%x, pll10: 0x%x, pcsdw12: 0x%x\n",
12631                               pipe_config->ddi_pll_sel,
12632                               pipe_config->dpll_hw_state.ebb0,
12633                               pipe_config->dpll_hw_state.ebb4,
12634                               pipe_config->dpll_hw_state.pll0,
12635                               pipe_config->dpll_hw_state.pll1,
12636                               pipe_config->dpll_hw_state.pll2,
12637                               pipe_config->dpll_hw_state.pll3,
12638                               pipe_config->dpll_hw_state.pll6,
12639                               pipe_config->dpll_hw_state.pll8,
12640                               pipe_config->dpll_hw_state.pll9,
12641                               pipe_config->dpll_hw_state.pll10,
12642                               pipe_config->dpll_hw_state.pcsdw12);
12643         } else if (IS_SKYLAKE(dev) || IS_KABYLAKE(dev)) {
12644                 DRM_DEBUG_KMS("ddi_pll_sel: %u; dpll_hw_state: "
12645                               "ctrl1: 0x%x, cfgcr1: 0x%x, cfgcr2: 0x%x\n",
12646                               pipe_config->ddi_pll_sel,
12647                               pipe_config->dpll_hw_state.ctrl1,
12648                               pipe_config->dpll_hw_state.cfgcr1,
12649                               pipe_config->dpll_hw_state.cfgcr2);
12650         } else if (HAS_DDI(dev)) {
12651                 DRM_DEBUG_KMS("ddi_pll_sel: 0x%x; dpll_hw_state: wrpll: 0x%x spll: 0x%x\n",
12652                               pipe_config->ddi_pll_sel,
12653                               pipe_config->dpll_hw_state.wrpll,
12654                               pipe_config->dpll_hw_state.spll);
12655         } else {
12656                 DRM_DEBUG_KMS("dpll_hw_state: dpll: 0x%x, dpll_md: 0x%x, "
12657                               "fp0: 0x%x, fp1: 0x%x\n",
12658                               pipe_config->dpll_hw_state.dpll,
12659                               pipe_config->dpll_hw_state.dpll_md,
12660                               pipe_config->dpll_hw_state.fp0,
12661                               pipe_config->dpll_hw_state.fp1);
12662         }
12663
12664         DRM_DEBUG_KMS("planes on this crtc\n");
12665         list_for_each_entry(plane, &dev->mode_config.plane_list, head) {
12666                 intel_plane = to_intel_plane(plane);
12667                 if (intel_plane->pipe != crtc->pipe)
12668                         continue;
12669
12670                 state = to_intel_plane_state(plane->state);
12671                 fb = state->base.fb;
12672                 if (!fb) {
12673                         DRM_DEBUG_KMS("[PLANE:%d:%s] disabled, scaler_id = %d\n",
12674                                       plane->base.id, plane->name, state->scaler_id);
12675                         continue;
12676                 }
12677
12678                 DRM_DEBUG_KMS("[PLANE:%d:%s] enabled",
12679                               plane->base.id, plane->name);
12680                 DRM_DEBUG_KMS("\tFB:%d, fb = %ux%u format = %s",
12681                               fb->base.id, fb->width, fb->height,
12682                               drm_get_format_name(fb->pixel_format));
12683                 DRM_DEBUG_KMS("\tscaler:%d src %dx%d+%d+%d dst %dx%d+%d+%d\n",
12684                               state->scaler_id,
12685                               state->src.x1 >> 16, state->src.y1 >> 16,
12686                               drm_rect_width(&state->src) >> 16,
12687                               drm_rect_height(&state->src) >> 16,
12688                               state->dst.x1, state->dst.y1,
12689                               drm_rect_width(&state->dst),
12690                               drm_rect_height(&state->dst));
12691         }
12692 }
12693
12694 static bool check_digital_port_conflicts(struct drm_atomic_state *state)
12695 {
12696         struct drm_device *dev = state->dev;
12697         struct drm_connector *connector;
12698         unsigned int used_ports = 0;
12699         unsigned int used_mst_ports = 0;
12700
12701         /*
12702          * Walk the connector list instead of the encoder
12703          * list to detect the problem on ddi platforms
12704          * where there's just one encoder per digital port.
12705          */
12706         drm_for_each_connector(connector, dev) {
12707                 struct drm_connector_state *connector_state;
12708                 struct intel_encoder *encoder;
12709
12710                 connector_state = drm_atomic_get_existing_connector_state(state, connector);
12711                 if (!connector_state)
12712                         connector_state = connector->state;
12713
12714                 if (!connector_state->best_encoder)
12715                         continue;
12716
12717                 encoder = to_intel_encoder(connector_state->best_encoder);
12718
12719                 WARN_ON(!connector_state->crtc);
12720
12721                 switch (encoder->type) {
12722                         unsigned int port_mask;
12723                 case INTEL_OUTPUT_UNKNOWN:
12724                         if (WARN_ON(!HAS_DDI(dev)))
12725                                 break;
12726                 case INTEL_OUTPUT_DP:
12727                 case INTEL_OUTPUT_HDMI:
12728                 case INTEL_OUTPUT_EDP:
12729                         port_mask = 1 << enc_to_dig_port(&encoder->base)->port;
12730
12731                         /* the same port mustn't appear more than once */
12732                         if (used_ports & port_mask)
12733                                 return false;
12734
12735                         used_ports |= port_mask;
12736                         break;
12737                 case INTEL_OUTPUT_DP_MST:
12738                         used_mst_ports |=
12739                                 1 << enc_to_mst(&encoder->base)->primary->port;
12740                         break;
12741                 default:
12742                         break;
12743                 }
12744         }
12745
12746         /* can't mix MST and SST/HDMI on the same port */
12747         if (used_ports & used_mst_ports)
12748                 return false;
12749
12750         return true;
12751 }
12752
12753 static void
12754 clear_intel_crtc_state(struct intel_crtc_state *crtc_state)
12755 {
12756         struct drm_crtc_state tmp_state;
12757         struct intel_crtc_scaler_state scaler_state;
12758         struct intel_dpll_hw_state dpll_hw_state;
12759         struct intel_shared_dpll *shared_dpll;
12760         uint32_t ddi_pll_sel;
12761         bool force_thru;
12762
12763         /* FIXME: before the switch to atomic started, a new pipe_config was
12764          * kzalloc'd. Code that depends on any field being zero should be
12765          * fixed, so that the crtc_state can be safely duplicated. For now,
12766          * only fields that are know to not cause problems are preserved. */
12767
12768         tmp_state = crtc_state->base;
12769         scaler_state = crtc_state->scaler_state;
12770         shared_dpll = crtc_state->shared_dpll;
12771         dpll_hw_state = crtc_state->dpll_hw_state;
12772         ddi_pll_sel = crtc_state->ddi_pll_sel;
12773         force_thru = crtc_state->pch_pfit.force_thru;
12774
12775         memset(crtc_state, 0, sizeof *crtc_state);
12776
12777         crtc_state->base = tmp_state;
12778         crtc_state->scaler_state = scaler_state;
12779         crtc_state->shared_dpll = shared_dpll;
12780         crtc_state->dpll_hw_state = dpll_hw_state;
12781         crtc_state->ddi_pll_sel = ddi_pll_sel;
12782         crtc_state->pch_pfit.force_thru = force_thru;
12783 }
12784
12785 static int
12786 intel_modeset_pipe_config(struct drm_crtc *crtc,
12787                           struct intel_crtc_state *pipe_config)
12788 {
12789         struct drm_atomic_state *state = pipe_config->base.state;
12790         struct intel_encoder *encoder;
12791         struct drm_connector *connector;
12792         struct drm_connector_state *connector_state;
12793         int base_bpp, ret = -EINVAL;
12794         int i;
12795         bool retry = true;
12796
12797         clear_intel_crtc_state(pipe_config);
12798
12799         pipe_config->cpu_transcoder =
12800                 (enum transcoder) to_intel_crtc(crtc)->pipe;
12801
12802         /*
12803          * Sanitize sync polarity flags based on requested ones. If neither
12804          * positive or negative polarity is requested, treat this as meaning
12805          * negative polarity.
12806          */
12807         if (!(pipe_config->base.adjusted_mode.flags &
12808               (DRM_MODE_FLAG_PHSYNC | DRM_MODE_FLAG_NHSYNC)))
12809                 pipe_config->base.adjusted_mode.flags |= DRM_MODE_FLAG_NHSYNC;
12810
12811         if (!(pipe_config->base.adjusted_mode.flags &
12812               (DRM_MODE_FLAG_PVSYNC | DRM_MODE_FLAG_NVSYNC)))
12813                 pipe_config->base.adjusted_mode.flags |= DRM_MODE_FLAG_NVSYNC;
12814
12815         base_bpp = compute_baseline_pipe_bpp(to_intel_crtc(crtc),
12816                                              pipe_config);
12817         if (base_bpp < 0)
12818                 goto fail;
12819
12820         /*
12821          * Determine the real pipe dimensions. Note that stereo modes can
12822          * increase the actual pipe size due to the frame doubling and
12823          * insertion of additional space for blanks between the frame. This
12824          * is stored in the crtc timings. We use the requested mode to do this
12825          * computation to clearly distinguish it from the adjusted mode, which
12826          * can be changed by the connectors in the below retry loop.
12827          */
12828         drm_crtc_get_hv_timing(&pipe_config->base.mode,
12829                                &pipe_config->pipe_src_w,
12830                                &pipe_config->pipe_src_h);
12831
12832         for_each_connector_in_state(state, connector, connector_state, i) {
12833                 if (connector_state->crtc != crtc)
12834                         continue;
12835
12836                 encoder = to_intel_encoder(connector_state->best_encoder);
12837
12838                 if (!check_single_encoder_cloning(state, to_intel_crtc(crtc), encoder)) {
12839                         DRM_DEBUG_KMS("rejecting invalid cloning configuration\n");
12840                         goto fail;
12841                 }
12842
12843                 /*
12844                  * Determine output_types before calling the .compute_config()
12845                  * hooks so that the hooks can use this information safely.
12846                  */
12847                 pipe_config->output_types |= 1 << encoder->type;
12848         }
12849
12850 encoder_retry:
12851         /* Ensure the port clock defaults are reset when retrying. */
12852         pipe_config->port_clock = 0;
12853         pipe_config->pixel_multiplier = 1;
12854
12855         /* Fill in default crtc timings, allow encoders to overwrite them. */
12856         drm_mode_set_crtcinfo(&pipe_config->base.adjusted_mode,
12857                               CRTC_STEREO_DOUBLE);
12858
12859         /* Pass our mode to the connectors and the CRTC to give them a chance to
12860          * adjust it according to limitations or connector properties, and also
12861          * a chance to reject the mode entirely.
12862          */
12863         for_each_connector_in_state(state, connector, connector_state, i) {
12864                 if (connector_state->crtc != crtc)
12865                         continue;
12866
12867                 encoder = to_intel_encoder(connector_state->best_encoder);
12868
12869                 if (!(encoder->compute_config(encoder, pipe_config))) {
12870                         DRM_DEBUG_KMS("Encoder config failure\n");
12871                         goto fail;
12872                 }
12873         }
12874
12875         /* Set default port clock if not overwritten by the encoder. Needs to be
12876          * done afterwards in case the encoder adjusts the mode. */
12877         if (!pipe_config->port_clock)
12878                 pipe_config->port_clock = pipe_config->base.adjusted_mode.crtc_clock
12879                         * pipe_config->pixel_multiplier;
12880
12881         ret = intel_crtc_compute_config(to_intel_crtc(crtc), pipe_config);
12882         if (ret < 0) {
12883                 DRM_DEBUG_KMS("CRTC fixup failed\n");
12884                 goto fail;
12885         }
12886
12887         if (ret == RETRY) {
12888                 if (WARN(!retry, "loop in pipe configuration computation\n")) {
12889                         ret = -EINVAL;
12890                         goto fail;
12891                 }
12892
12893                 DRM_DEBUG_KMS("CRTC bw constrained, retrying\n");
12894                 retry = false;
12895                 goto encoder_retry;
12896         }
12897
12898         /* Dithering seems to not pass-through bits correctly when it should, so
12899          * only enable it on 6bpc panels. */
12900         pipe_config->dither = pipe_config->pipe_bpp == 6*3;
12901         DRM_DEBUG_KMS("hw max bpp: %i, pipe bpp: %i, dithering: %i\n",
12902                       base_bpp, pipe_config->pipe_bpp, pipe_config->dither);
12903
12904 fail:
12905         return ret;
12906 }
12907
12908 static void
12909 intel_modeset_update_crtc_state(struct drm_atomic_state *state)
12910 {
12911         struct drm_crtc *crtc;
12912         struct drm_crtc_state *crtc_state;
12913         int i;
12914
12915         /* Double check state. */
12916         for_each_crtc_in_state(state, crtc, crtc_state, i) {
12917                 to_intel_crtc(crtc)->config = to_intel_crtc_state(crtc->state);
12918
12919                 /* Update hwmode for vblank functions */
12920                 if (crtc->state->active)
12921                         crtc->hwmode = crtc->state->adjusted_mode;
12922                 else
12923                         crtc->hwmode.crtc_clock = 0;
12924
12925                 /*
12926                  * Update legacy state to satisfy fbc code. This can
12927                  * be removed when fbc uses the atomic state.
12928                  */
12929                 if (drm_atomic_get_existing_plane_state(state, crtc->primary)) {
12930                         struct drm_plane_state *plane_state = crtc->primary->state;
12931
12932                         crtc->primary->fb = plane_state->fb;
12933                         crtc->x = plane_state->src_x >> 16;
12934                         crtc->y = plane_state->src_y >> 16;
12935                 }
12936         }
12937 }
12938
12939 static bool intel_fuzzy_clock_check(int clock1, int clock2)
12940 {
12941         int diff;
12942
12943         if (clock1 == clock2)
12944                 return true;
12945
12946         if (!clock1 || !clock2)
12947                 return false;
12948
12949         diff = abs(clock1 - clock2);
12950
12951         if (((((diff + clock1 + clock2) * 100)) / (clock1 + clock2)) < 105)
12952                 return true;
12953
12954         return false;
12955 }
12956
12957 #define for_each_intel_crtc_masked(dev, mask, intel_crtc) \
12958         list_for_each_entry((intel_crtc), \
12959                             &(dev)->mode_config.crtc_list, \
12960                             base.head) \
12961                 for_each_if (mask & (1 <<(intel_crtc)->pipe))
12962
12963 static bool
12964 intel_compare_m_n(unsigned int m, unsigned int n,
12965                   unsigned int m2, unsigned int n2,
12966                   bool exact)
12967 {
12968         if (m == m2 && n == n2)
12969                 return true;
12970
12971         if (exact || !m || !n || !m2 || !n2)
12972                 return false;
12973
12974         BUILD_BUG_ON(DATA_LINK_M_N_MASK > INT_MAX);
12975
12976         if (n > n2) {
12977                 while (n > n2) {
12978                         m2 <<= 1;
12979                         n2 <<= 1;
12980                 }
12981         } else if (n < n2) {
12982                 while (n < n2) {
12983                         m <<= 1;
12984                         n <<= 1;
12985                 }
12986         }
12987
12988         if (n != n2)
12989                 return false;
12990
12991         return intel_fuzzy_clock_check(m, m2);
12992 }
12993
12994 static bool
12995 intel_compare_link_m_n(const struct intel_link_m_n *m_n,
12996                        struct intel_link_m_n *m2_n2,
12997                        bool adjust)
12998 {
12999         if (m_n->tu == m2_n2->tu &&
13000             intel_compare_m_n(m_n->gmch_m, m_n->gmch_n,
13001                               m2_n2->gmch_m, m2_n2->gmch_n, !adjust) &&
13002             intel_compare_m_n(m_n->link_m, m_n->link_n,
13003                               m2_n2->link_m, m2_n2->link_n, !adjust)) {
13004                 if (adjust)
13005                         *m2_n2 = *m_n;
13006
13007                 return true;
13008         }
13009
13010         return false;
13011 }
13012
13013 static bool
13014 intel_pipe_config_compare(struct drm_device *dev,
13015                           struct intel_crtc_state *current_config,
13016                           struct intel_crtc_state *pipe_config,
13017                           bool adjust)
13018 {
13019         bool ret = true;
13020
13021 #define INTEL_ERR_OR_DBG_KMS(fmt, ...) \
13022         do { \
13023                 if (!adjust) \
13024                         DRM_ERROR(fmt, ##__VA_ARGS__); \
13025                 else \
13026                         DRM_DEBUG_KMS(fmt, ##__VA_ARGS__); \
13027         } while (0)
13028
13029 #define PIPE_CONF_CHECK_X(name) \
13030         if (current_config->name != pipe_config->name) { \
13031                 INTEL_ERR_OR_DBG_KMS("mismatch in " #name " " \
13032                           "(expected 0x%08x, found 0x%08x)\n", \
13033                           current_config->name, \
13034                           pipe_config->name); \
13035                 ret = false; \
13036         }
13037
13038 #define PIPE_CONF_CHECK_I(name) \
13039         if (current_config->name != pipe_config->name) { \
13040                 INTEL_ERR_OR_DBG_KMS("mismatch in " #name " " \
13041                           "(expected %i, found %i)\n", \
13042                           current_config->name, \
13043                           pipe_config->name); \
13044                 ret = false; \
13045         }
13046
13047 #define PIPE_CONF_CHECK_P(name) \
13048         if (current_config->name != pipe_config->name) { \
13049                 INTEL_ERR_OR_DBG_KMS("mismatch in " #name " " \
13050                           "(expected %p, found %p)\n", \
13051                           current_config->name, \
13052                           pipe_config->name); \
13053                 ret = false; \
13054         }
13055
13056 #define PIPE_CONF_CHECK_M_N(name) \
13057         if (!intel_compare_link_m_n(&current_config->name, \
13058                                     &pipe_config->name,\
13059                                     adjust)) { \
13060                 INTEL_ERR_OR_DBG_KMS("mismatch in " #name " " \
13061                           "(expected tu %i gmch %i/%i link %i/%i, " \
13062                           "found tu %i, gmch %i/%i link %i/%i)\n", \
13063                           current_config->name.tu, \
13064                           current_config->name.gmch_m, \
13065                           current_config->name.gmch_n, \
13066                           current_config->name.link_m, \
13067                           current_config->name.link_n, \
13068                           pipe_config->name.tu, \
13069                           pipe_config->name.gmch_m, \
13070                           pipe_config->name.gmch_n, \
13071                           pipe_config->name.link_m, \
13072                           pipe_config->name.link_n); \
13073                 ret = false; \
13074         }
13075
13076 /* This is required for BDW+ where there is only one set of registers for
13077  * switching between high and low RR.
13078  * This macro can be used whenever a comparison has to be made between one
13079  * hw state and multiple sw state variables.
13080  */
13081 #define PIPE_CONF_CHECK_M_N_ALT(name, alt_name) \
13082         if (!intel_compare_link_m_n(&current_config->name, \
13083                                     &pipe_config->name, adjust) && \
13084             !intel_compare_link_m_n(&current_config->alt_name, \
13085                                     &pipe_config->name, adjust)) { \
13086                 INTEL_ERR_OR_DBG_KMS("mismatch in " #name " " \
13087                           "(expected tu %i gmch %i/%i link %i/%i, " \
13088                           "or tu %i gmch %i/%i link %i/%i, " \
13089                           "found tu %i, gmch %i/%i link %i/%i)\n", \
13090                           current_config->name.tu, \
13091                           current_config->name.gmch_m, \
13092                           current_config->name.gmch_n, \
13093                           current_config->name.link_m, \
13094                           current_config->name.link_n, \
13095                           current_config->alt_name.tu, \
13096                           current_config->alt_name.gmch_m, \
13097                           current_config->alt_name.gmch_n, \
13098                           current_config->alt_name.link_m, \
13099                           current_config->alt_name.link_n, \
13100                           pipe_config->name.tu, \
13101                           pipe_config->name.gmch_m, \
13102                           pipe_config->name.gmch_n, \
13103                           pipe_config->name.link_m, \
13104                           pipe_config->name.link_n); \
13105                 ret = false; \
13106         }
13107
13108 #define PIPE_CONF_CHECK_FLAGS(name, mask)       \
13109         if ((current_config->name ^ pipe_config->name) & (mask)) { \
13110                 INTEL_ERR_OR_DBG_KMS("mismatch in " #name "(" #mask ") " \
13111                           "(expected %i, found %i)\n", \
13112                           current_config->name & (mask), \
13113                           pipe_config->name & (mask)); \
13114                 ret = false; \
13115         }
13116
13117 #define PIPE_CONF_CHECK_CLOCK_FUZZY(name) \
13118         if (!intel_fuzzy_clock_check(current_config->name, pipe_config->name)) { \
13119                 INTEL_ERR_OR_DBG_KMS("mismatch in " #name " " \
13120                           "(expected %i, found %i)\n", \
13121                           current_config->name, \
13122                           pipe_config->name); \
13123                 ret = false; \
13124         }
13125
13126 #define PIPE_CONF_QUIRK(quirk)  \
13127         ((current_config->quirks | pipe_config->quirks) & (quirk))
13128
13129         PIPE_CONF_CHECK_I(cpu_transcoder);
13130
13131         PIPE_CONF_CHECK_I(has_pch_encoder);
13132         PIPE_CONF_CHECK_I(fdi_lanes);
13133         PIPE_CONF_CHECK_M_N(fdi_m_n);
13134
13135         PIPE_CONF_CHECK_I(lane_count);
13136         PIPE_CONF_CHECK_X(lane_lat_optim_mask);
13137
13138         if (INTEL_INFO(dev)->gen < 8) {
13139                 PIPE_CONF_CHECK_M_N(dp_m_n);
13140
13141                 if (current_config->has_drrs)
13142                         PIPE_CONF_CHECK_M_N(dp_m2_n2);
13143         } else
13144                 PIPE_CONF_CHECK_M_N_ALT(dp_m_n, dp_m2_n2);
13145
13146         PIPE_CONF_CHECK_X(output_types);
13147
13148         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hdisplay);
13149         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_htotal);
13150         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hblank_start);
13151         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hblank_end);
13152         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hsync_start);
13153         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hsync_end);
13154
13155         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vdisplay);
13156         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vtotal);
13157         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vblank_start);
13158         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vblank_end);
13159         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vsync_start);
13160         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vsync_end);
13161
13162         PIPE_CONF_CHECK_I(pixel_multiplier);
13163         PIPE_CONF_CHECK_I(has_hdmi_sink);
13164         if ((INTEL_INFO(dev)->gen < 8 && !IS_HASWELL(dev)) ||
13165             IS_VALLEYVIEW(dev) || IS_CHERRYVIEW(dev))
13166                 PIPE_CONF_CHECK_I(limited_color_range);
13167         PIPE_CONF_CHECK_I(has_infoframe);
13168
13169         PIPE_CONF_CHECK_I(has_audio);
13170
13171         PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
13172                               DRM_MODE_FLAG_INTERLACE);
13173
13174         if (!PIPE_CONF_QUIRK(PIPE_CONFIG_QUIRK_MODE_SYNC_FLAGS)) {
13175                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
13176                                       DRM_MODE_FLAG_PHSYNC);
13177                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
13178                                       DRM_MODE_FLAG_NHSYNC);
13179                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
13180                                       DRM_MODE_FLAG_PVSYNC);
13181                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
13182                                       DRM_MODE_FLAG_NVSYNC);
13183         }
13184
13185         PIPE_CONF_CHECK_X(gmch_pfit.control);
13186         /* pfit ratios are autocomputed by the hw on gen4+ */
13187         if (INTEL_INFO(dev)->gen < 4)
13188                 PIPE_CONF_CHECK_X(gmch_pfit.pgm_ratios);
13189         PIPE_CONF_CHECK_X(gmch_pfit.lvds_border_bits);
13190
13191         if (!adjust) {
13192                 PIPE_CONF_CHECK_I(pipe_src_w);
13193                 PIPE_CONF_CHECK_I(pipe_src_h);
13194
13195                 PIPE_CONF_CHECK_I(pch_pfit.enabled);
13196                 if (current_config->pch_pfit.enabled) {
13197                         PIPE_CONF_CHECK_X(pch_pfit.pos);
13198                         PIPE_CONF_CHECK_X(pch_pfit.size);
13199                 }
13200
13201                 PIPE_CONF_CHECK_I(scaler_state.scaler_id);
13202         }
13203
13204         /* BDW+ don't expose a synchronous way to read the state */
13205         if (IS_HASWELL(dev))
13206                 PIPE_CONF_CHECK_I(ips_enabled);
13207
13208         PIPE_CONF_CHECK_I(double_wide);
13209
13210         PIPE_CONF_CHECK_X(ddi_pll_sel);
13211
13212         PIPE_CONF_CHECK_P(shared_dpll);
13213         PIPE_CONF_CHECK_X(dpll_hw_state.dpll);
13214         PIPE_CONF_CHECK_X(dpll_hw_state.dpll_md);
13215         PIPE_CONF_CHECK_X(dpll_hw_state.fp0);
13216         PIPE_CONF_CHECK_X(dpll_hw_state.fp1);
13217         PIPE_CONF_CHECK_X(dpll_hw_state.wrpll);
13218         PIPE_CONF_CHECK_X(dpll_hw_state.spll);
13219         PIPE_CONF_CHECK_X(dpll_hw_state.ctrl1);
13220         PIPE_CONF_CHECK_X(dpll_hw_state.cfgcr1);
13221         PIPE_CONF_CHECK_X(dpll_hw_state.cfgcr2);
13222
13223         PIPE_CONF_CHECK_X(dsi_pll.ctrl);
13224         PIPE_CONF_CHECK_X(dsi_pll.div);
13225
13226         if (IS_G4X(dev) || INTEL_INFO(dev)->gen >= 5)
13227                 PIPE_CONF_CHECK_I(pipe_bpp);
13228
13229         PIPE_CONF_CHECK_CLOCK_FUZZY(base.adjusted_mode.crtc_clock);
13230         PIPE_CONF_CHECK_CLOCK_FUZZY(port_clock);
13231
13232 #undef PIPE_CONF_CHECK_X
13233 #undef PIPE_CONF_CHECK_I
13234 #undef PIPE_CONF_CHECK_P
13235 #undef PIPE_CONF_CHECK_FLAGS
13236 #undef PIPE_CONF_CHECK_CLOCK_FUZZY
13237 #undef PIPE_CONF_QUIRK
13238 #undef INTEL_ERR_OR_DBG_KMS
13239
13240         return ret;
13241 }
13242
13243 static void intel_pipe_config_sanity_check(struct drm_i915_private *dev_priv,
13244                                            const struct intel_crtc_state *pipe_config)
13245 {
13246         if (pipe_config->has_pch_encoder) {
13247                 int fdi_dotclock = intel_dotclock_calculate(intel_fdi_link_freq(dev_priv, pipe_config),
13248                                                             &pipe_config->fdi_m_n);
13249                 int dotclock = pipe_config->base.adjusted_mode.crtc_clock;
13250
13251                 /*
13252                  * FDI already provided one idea for the dotclock.
13253                  * Yell if the encoder disagrees.
13254                  */
13255                 WARN(!intel_fuzzy_clock_check(fdi_dotclock, dotclock),
13256                      "FDI dotclock and encoder dotclock mismatch, fdi: %i, encoder: %i\n",
13257                      fdi_dotclock, dotclock);
13258         }
13259 }
13260
13261 static void verify_wm_state(struct drm_crtc *crtc,
13262                             struct drm_crtc_state *new_state)
13263 {
13264         struct drm_device *dev = crtc->dev;
13265         struct drm_i915_private *dev_priv = to_i915(dev);
13266         struct skl_ddb_allocation hw_ddb, *sw_ddb;
13267         struct skl_ddb_entry *hw_entry, *sw_entry;
13268         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
13269         const enum pipe pipe = intel_crtc->pipe;
13270         int plane;
13271
13272         if (INTEL_INFO(dev)->gen < 9 || !new_state->active)
13273                 return;
13274
13275         skl_ddb_get_hw_state(dev_priv, &hw_ddb);
13276         sw_ddb = &dev_priv->wm.skl_hw.ddb;
13277
13278         /* planes */
13279         for_each_plane(dev_priv, pipe, plane) {
13280                 hw_entry = &hw_ddb.plane[pipe][plane];
13281                 sw_entry = &sw_ddb->plane[pipe][plane];
13282
13283                 if (skl_ddb_entry_equal(hw_entry, sw_entry))
13284                         continue;
13285
13286                 DRM_ERROR("mismatch in DDB state pipe %c plane %d "
13287                           "(expected (%u,%u), found (%u,%u))\n",
13288                           pipe_name(pipe), plane + 1,
13289                           sw_entry->start, sw_entry->end,
13290                           hw_entry->start, hw_entry->end);
13291         }
13292
13293         /* cursor */
13294         hw_entry = &hw_ddb.plane[pipe][PLANE_CURSOR];
13295         sw_entry = &sw_ddb->plane[pipe][PLANE_CURSOR];
13296
13297         if (!skl_ddb_entry_equal(hw_entry, sw_entry)) {
13298                 DRM_ERROR("mismatch in DDB state pipe %c cursor "
13299                           "(expected (%u,%u), found (%u,%u))\n",
13300                           pipe_name(pipe),
13301                           sw_entry->start, sw_entry->end,
13302                           hw_entry->start, hw_entry->end);
13303         }
13304 }
13305
13306 static void
13307 verify_connector_state(struct drm_device *dev, struct drm_crtc *crtc)
13308 {
13309         struct drm_connector *connector;
13310
13311         drm_for_each_connector(connector, dev) {
13312                 struct drm_encoder *encoder = connector->encoder;
13313                 struct drm_connector_state *state = connector->state;
13314
13315                 if (state->crtc != crtc)
13316                         continue;
13317
13318                 intel_connector_verify_state(to_intel_connector(connector));
13319
13320                 I915_STATE_WARN(state->best_encoder != encoder,
13321                      "connector's atomic encoder doesn't match legacy encoder\n");
13322         }
13323 }
13324
13325 static void
13326 verify_encoder_state(struct drm_device *dev)
13327 {
13328         struct intel_encoder *encoder;
13329         struct intel_connector *connector;
13330
13331         for_each_intel_encoder(dev, encoder) {
13332                 bool enabled = false;
13333                 enum pipe pipe;
13334
13335                 DRM_DEBUG_KMS("[ENCODER:%d:%s]\n",
13336                               encoder->base.base.id,
13337                               encoder->base.name);
13338
13339                 for_each_intel_connector(dev, connector) {
13340                         if (connector->base.state->best_encoder != &encoder->base)
13341                                 continue;
13342                         enabled = true;
13343
13344                         I915_STATE_WARN(connector->base.state->crtc !=
13345                                         encoder->base.crtc,
13346                              "connector's crtc doesn't match encoder crtc\n");
13347                 }
13348
13349                 I915_STATE_WARN(!!encoder->base.crtc != enabled,
13350                      "encoder's enabled state mismatch "
13351                      "(expected %i, found %i)\n",
13352                      !!encoder->base.crtc, enabled);
13353
13354                 if (!encoder->base.crtc) {
13355                         bool active;
13356
13357                         active = encoder->get_hw_state(encoder, &pipe);
13358                         I915_STATE_WARN(active,
13359                              "encoder detached but still enabled on pipe %c.\n",
13360                              pipe_name(pipe));
13361                 }
13362         }
13363 }
13364
13365 static void
13366 verify_crtc_state(struct drm_crtc *crtc,
13367                   struct drm_crtc_state *old_crtc_state,
13368                   struct drm_crtc_state *new_crtc_state)
13369 {
13370         struct drm_device *dev = crtc->dev;
13371         struct drm_i915_private *dev_priv = to_i915(dev);
13372         struct intel_encoder *encoder;
13373         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
13374         struct intel_crtc_state *pipe_config, *sw_config;
13375         struct drm_atomic_state *old_state;
13376         bool active;
13377
13378         old_state = old_crtc_state->state;
13379         __drm_atomic_helper_crtc_destroy_state(old_crtc_state);
13380         pipe_config = to_intel_crtc_state(old_crtc_state);
13381         memset(pipe_config, 0, sizeof(*pipe_config));
13382         pipe_config->base.crtc = crtc;
13383         pipe_config->base.state = old_state;
13384
13385         DRM_DEBUG_KMS("[CRTC:%d:%s]\n", crtc->base.id, crtc->name);
13386
13387         active = dev_priv->display.get_pipe_config(intel_crtc, pipe_config);
13388
13389         /* hw state is inconsistent with the pipe quirk */
13390         if ((intel_crtc->pipe == PIPE_A && dev_priv->quirks & QUIRK_PIPEA_FORCE) ||
13391             (intel_crtc->pipe == PIPE_B && dev_priv->quirks & QUIRK_PIPEB_FORCE))
13392                 active = new_crtc_state->active;
13393
13394         I915_STATE_WARN(new_crtc_state->active != active,
13395              "crtc active state doesn't match with hw state "
13396              "(expected %i, found %i)\n", new_crtc_state->active, active);
13397
13398         I915_STATE_WARN(intel_crtc->active != new_crtc_state->active,
13399              "transitional active state does not match atomic hw state "
13400              "(expected %i, found %i)\n", new_crtc_state->active, intel_crtc->active);
13401
13402         for_each_encoder_on_crtc(dev, crtc, encoder) {
13403                 enum pipe pipe;
13404
13405                 active = encoder->get_hw_state(encoder, &pipe);
13406                 I915_STATE_WARN(active != new_crtc_state->active,
13407                         "[ENCODER:%i] active %i with crtc active %i\n",
13408                         encoder->base.base.id, active, new_crtc_state->active);
13409
13410                 I915_STATE_WARN(active && intel_crtc->pipe != pipe,
13411                                 "Encoder connected to wrong pipe %c\n",
13412                                 pipe_name(pipe));
13413
13414                 if (active) {
13415                         pipe_config->output_types |= 1 << encoder->type;
13416                         encoder->get_config(encoder, pipe_config);
13417                 }
13418         }
13419
13420         if (!new_crtc_state->active)
13421                 return;
13422
13423         intel_pipe_config_sanity_check(dev_priv, pipe_config);
13424
13425         sw_config = to_intel_crtc_state(crtc->state);
13426         if (!intel_pipe_config_compare(dev, sw_config,
13427                                        pipe_config, false)) {
13428                 I915_STATE_WARN(1, "pipe state doesn't match!\n");
13429                 intel_dump_pipe_config(intel_crtc, pipe_config,
13430                                        "[hw state]");
13431                 intel_dump_pipe_config(intel_crtc, sw_config,
13432                                        "[sw state]");
13433         }
13434 }
13435
13436 static void
13437 verify_single_dpll_state(struct drm_i915_private *dev_priv,
13438                          struct intel_shared_dpll *pll,
13439                          struct drm_crtc *crtc,
13440                          struct drm_crtc_state *new_state)
13441 {
13442         struct intel_dpll_hw_state dpll_hw_state;
13443         unsigned crtc_mask;
13444         bool active;
13445
13446         memset(&dpll_hw_state, 0, sizeof(dpll_hw_state));
13447
13448         DRM_DEBUG_KMS("%s\n", pll->name);
13449
13450         active = pll->funcs.get_hw_state(dev_priv, pll, &dpll_hw_state);
13451
13452         if (!(pll->flags & INTEL_DPLL_ALWAYS_ON)) {
13453                 I915_STATE_WARN(!pll->on && pll->active_mask,
13454                      "pll in active use but not on in sw tracking\n");
13455                 I915_STATE_WARN(pll->on && !pll->active_mask,
13456                      "pll is on but not used by any active crtc\n");
13457                 I915_STATE_WARN(pll->on != active,
13458                      "pll on state mismatch (expected %i, found %i)\n",
13459                      pll->on, active);
13460         }
13461
13462         if (!crtc) {
13463                 I915_STATE_WARN(pll->active_mask & ~pll->config.crtc_mask,
13464                                 "more active pll users than references: %x vs %x\n",
13465                                 pll->active_mask, pll->config.crtc_mask);
13466
13467                 return;
13468         }
13469
13470         crtc_mask = 1 << drm_crtc_index(crtc);
13471
13472         if (new_state->active)
13473                 I915_STATE_WARN(!(pll->active_mask & crtc_mask),
13474                                 "pll active mismatch (expected pipe %c in active mask 0x%02x)\n",
13475                                 pipe_name(drm_crtc_index(crtc)), pll->active_mask);
13476         else
13477                 I915_STATE_WARN(pll->active_mask & crtc_mask,
13478                                 "pll active mismatch (didn't expect pipe %c in active mask 0x%02x)\n",
13479                                 pipe_name(drm_crtc_index(crtc)), pll->active_mask);
13480
13481         I915_STATE_WARN(!(pll->config.crtc_mask & crtc_mask),
13482                         "pll enabled crtcs mismatch (expected 0x%x in 0x%02x)\n",
13483                         crtc_mask, pll->config.crtc_mask);
13484
13485         I915_STATE_WARN(pll->on && memcmp(&pll->config.hw_state,
13486                                           &dpll_hw_state,
13487                                           sizeof(dpll_hw_state)),
13488                         "pll hw state mismatch\n");
13489 }
13490
13491 static void
13492 verify_shared_dpll_state(struct drm_device *dev, struct drm_crtc *crtc,
13493                          struct drm_crtc_state *old_crtc_state,
13494                          struct drm_crtc_state *new_crtc_state)
13495 {
13496         struct drm_i915_private *dev_priv = to_i915(dev);
13497         struct intel_crtc_state *old_state = to_intel_crtc_state(old_crtc_state);
13498         struct intel_crtc_state *new_state = to_intel_crtc_state(new_crtc_state);
13499
13500         if (new_state->shared_dpll)
13501                 verify_single_dpll_state(dev_priv, new_state->shared_dpll, crtc, new_crtc_state);
13502
13503         if (old_state->shared_dpll &&
13504             old_state->shared_dpll != new_state->shared_dpll) {
13505                 unsigned crtc_mask = 1 << drm_crtc_index(crtc);
13506                 struct intel_shared_dpll *pll = old_state->shared_dpll;
13507
13508                 I915_STATE_WARN(pll->active_mask & crtc_mask,
13509                                 "pll active mismatch (didn't expect pipe %c in active mask)\n",
13510                                 pipe_name(drm_crtc_index(crtc)));
13511                 I915_STATE_WARN(pll->config.crtc_mask & crtc_mask,
13512                                 "pll enabled crtcs mismatch (found %x in enabled mask)\n",
13513                                 pipe_name(drm_crtc_index(crtc)));
13514         }
13515 }
13516
13517 static void
13518 intel_modeset_verify_crtc(struct drm_crtc *crtc,
13519                          struct drm_crtc_state *old_state,
13520                          struct drm_crtc_state *new_state)
13521 {
13522         if (!needs_modeset(new_state) &&
13523             !to_intel_crtc_state(new_state)->update_pipe)
13524                 return;
13525
13526         verify_wm_state(crtc, new_state);
13527         verify_connector_state(crtc->dev, crtc);
13528         verify_crtc_state(crtc, old_state, new_state);
13529         verify_shared_dpll_state(crtc->dev, crtc, old_state, new_state);
13530 }
13531
13532 static void
13533 verify_disabled_dpll_state(struct drm_device *dev)
13534 {
13535         struct drm_i915_private *dev_priv = to_i915(dev);
13536         int i;
13537
13538         for (i = 0; i < dev_priv->num_shared_dpll; i++)
13539                 verify_single_dpll_state(dev_priv, &dev_priv->shared_dplls[i], NULL, NULL);
13540 }
13541
13542 static void
13543 intel_modeset_verify_disabled(struct drm_device *dev)
13544 {
13545         verify_encoder_state(dev);
13546         verify_connector_state(dev, NULL);
13547         verify_disabled_dpll_state(dev);
13548 }
13549
13550 static void update_scanline_offset(struct intel_crtc *crtc)
13551 {
13552         struct drm_device *dev = crtc->base.dev;
13553
13554         /*
13555          * The scanline counter increments at the leading edge of hsync.
13556          *
13557          * On most platforms it starts counting from vtotal-1 on the
13558          * first active line. That means the scanline counter value is
13559          * always one less than what we would expect. Ie. just after
13560          * start of vblank, which also occurs at start of hsync (on the
13561          * last active line), the scanline counter will read vblank_start-1.
13562          *
13563          * On gen2 the scanline counter starts counting from 1 instead
13564          * of vtotal-1, so we have to subtract one (or rather add vtotal-1
13565          * to keep the value positive), instead of adding one.
13566          *
13567          * On HSW+ the behaviour of the scanline counter depends on the output
13568          * type. For DP ports it behaves like most other platforms, but on HDMI
13569          * there's an extra 1 line difference. So we need to add two instead of
13570          * one to the value.
13571          */
13572         if (IS_GEN2(dev)) {
13573                 const struct drm_display_mode *adjusted_mode = &crtc->config->base.adjusted_mode;
13574                 int vtotal;
13575
13576                 vtotal = adjusted_mode->crtc_vtotal;
13577                 if (adjusted_mode->flags & DRM_MODE_FLAG_INTERLACE)
13578                         vtotal /= 2;
13579
13580                 crtc->scanline_offset = vtotal - 1;
13581         } else if (HAS_DDI(dev) &&
13582                    intel_crtc_has_type(crtc->config, INTEL_OUTPUT_HDMI)) {
13583                 crtc->scanline_offset = 2;
13584         } else
13585                 crtc->scanline_offset = 1;
13586 }
13587
13588 static void intel_modeset_clear_plls(struct drm_atomic_state *state)
13589 {
13590         struct drm_device *dev = state->dev;
13591         struct drm_i915_private *dev_priv = to_i915(dev);
13592         struct intel_shared_dpll_config *shared_dpll = NULL;
13593         struct drm_crtc *crtc;
13594         struct drm_crtc_state *crtc_state;
13595         int i;
13596
13597         if (!dev_priv->display.crtc_compute_clock)
13598                 return;
13599
13600         for_each_crtc_in_state(state, crtc, crtc_state, i) {
13601                 struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
13602                 struct intel_shared_dpll *old_dpll =
13603                         to_intel_crtc_state(crtc->state)->shared_dpll;
13604
13605                 if (!needs_modeset(crtc_state))
13606                         continue;
13607
13608                 to_intel_crtc_state(crtc_state)->shared_dpll = NULL;
13609
13610                 if (!old_dpll)
13611                         continue;
13612
13613                 if (!shared_dpll)
13614                         shared_dpll = intel_atomic_get_shared_dpll_state(state);
13615
13616                 intel_shared_dpll_config_put(shared_dpll, old_dpll, intel_crtc);
13617         }
13618 }
13619
13620 /*
13621  * This implements the workaround described in the "notes" section of the mode
13622  * set sequence documentation. When going from no pipes or single pipe to
13623  * multiple pipes, and planes are enabled after the pipe, we need to wait at
13624  * least 2 vblanks on the first pipe before enabling planes on the second pipe.
13625  */
13626 static int haswell_mode_set_planes_workaround(struct drm_atomic_state *state)
13627 {
13628         struct drm_crtc_state *crtc_state;
13629         struct intel_crtc *intel_crtc;
13630         struct drm_crtc *crtc;
13631         struct intel_crtc_state *first_crtc_state = NULL;
13632         struct intel_crtc_state *other_crtc_state = NULL;
13633         enum pipe first_pipe = INVALID_PIPE, enabled_pipe = INVALID_PIPE;
13634         int i;
13635
13636         /* look at all crtc's that are going to be enabled in during modeset */
13637         for_each_crtc_in_state(state, crtc, crtc_state, i) {
13638                 intel_crtc = to_intel_crtc(crtc);
13639
13640                 if (!crtc_state->active || !needs_modeset(crtc_state))
13641                         continue;
13642
13643                 if (first_crtc_state) {
13644                         other_crtc_state = to_intel_crtc_state(crtc_state);
13645                         break;
13646                 } else {
13647                         first_crtc_state = to_intel_crtc_state(crtc_state);
13648                         first_pipe = intel_crtc->pipe;
13649                 }
13650         }
13651
13652         /* No workaround needed? */
13653         if (!first_crtc_state)
13654                 return 0;
13655
13656         /* w/a possibly needed, check how many crtc's are already enabled. */
13657         for_each_intel_crtc(state->dev, intel_crtc) {
13658                 struct intel_crtc_state *pipe_config;
13659
13660                 pipe_config = intel_atomic_get_crtc_state(state, intel_crtc);
13661                 if (IS_ERR(pipe_config))
13662                         return PTR_ERR(pipe_config);
13663
13664                 pipe_config->hsw_workaround_pipe = INVALID_PIPE;
13665
13666                 if (!pipe_config->base.active ||
13667                     needs_modeset(&pipe_config->base))
13668                         continue;
13669
13670                 /* 2 or more enabled crtcs means no need for w/a */
13671                 if (enabled_pipe != INVALID_PIPE)
13672                         return 0;
13673
13674                 enabled_pipe = intel_crtc->pipe;
13675         }
13676
13677         if (enabled_pipe != INVALID_PIPE)
13678                 first_crtc_state->hsw_workaround_pipe = enabled_pipe;
13679         else if (other_crtc_state)
13680                 other_crtc_state->hsw_workaround_pipe = first_pipe;
13681
13682         return 0;
13683 }
13684
13685 static int intel_modeset_all_pipes(struct drm_atomic_state *state)
13686 {
13687         struct drm_crtc *crtc;
13688         struct drm_crtc_state *crtc_state;
13689         int ret = 0;
13690
13691         /* add all active pipes to the state */
13692         for_each_crtc(state->dev, crtc) {
13693                 crtc_state = drm_atomic_get_crtc_state(state, crtc);
13694                 if (IS_ERR(crtc_state))
13695                         return PTR_ERR(crtc_state);
13696
13697                 if (!crtc_state->active || needs_modeset(crtc_state))
13698                         continue;
13699
13700                 crtc_state->mode_changed = true;
13701
13702                 ret = drm_atomic_add_affected_connectors(state, crtc);
13703                 if (ret)
13704                         break;
13705
13706                 ret = drm_atomic_add_affected_planes(state, crtc);
13707                 if (ret)
13708                         break;
13709         }
13710
13711         return ret;
13712 }
13713
13714 static int intel_modeset_checks(struct drm_atomic_state *state)
13715 {
13716         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
13717         struct drm_i915_private *dev_priv = to_i915(state->dev);
13718         struct drm_crtc *crtc;
13719         struct drm_crtc_state *crtc_state;
13720         int ret = 0, i;
13721
13722         if (!check_digital_port_conflicts(state)) {
13723                 DRM_DEBUG_KMS("rejecting conflicting digital port configuration\n");
13724                 return -EINVAL;
13725         }
13726
13727         intel_state->modeset = true;
13728         intel_state->active_crtcs = dev_priv->active_crtcs;
13729
13730         for_each_crtc_in_state(state, crtc, crtc_state, i) {
13731                 if (crtc_state->active)
13732                         intel_state->active_crtcs |= 1 << i;
13733                 else
13734                         intel_state->active_crtcs &= ~(1 << i);
13735
13736                 if (crtc_state->active != crtc->state->active)
13737                         intel_state->active_pipe_changes |= drm_crtc_mask(crtc);
13738         }
13739
13740         /*
13741          * See if the config requires any additional preparation, e.g.
13742          * to adjust global state with pipes off.  We need to do this
13743          * here so we can get the modeset_pipe updated config for the new
13744          * mode set on this crtc.  For other crtcs we need to use the
13745          * adjusted_mode bits in the crtc directly.
13746          */
13747         if (dev_priv->display.modeset_calc_cdclk) {
13748                 if (!intel_state->cdclk_pll_vco)
13749                         intel_state->cdclk_pll_vco = dev_priv->cdclk_pll.vco;
13750                 if (!intel_state->cdclk_pll_vco)
13751                         intel_state->cdclk_pll_vco = dev_priv->skl_preferred_vco_freq;
13752
13753                 ret = dev_priv->display.modeset_calc_cdclk(state);
13754                 if (ret < 0)
13755                         return ret;
13756
13757                 if (intel_state->dev_cdclk != dev_priv->cdclk_freq ||
13758                     intel_state->cdclk_pll_vco != dev_priv->cdclk_pll.vco)
13759                         ret = intel_modeset_all_pipes(state);
13760
13761                 if (ret < 0)
13762                         return ret;
13763
13764                 DRM_DEBUG_KMS("New cdclk calculated to be atomic %u, actual %u\n",
13765                               intel_state->cdclk, intel_state->dev_cdclk);
13766         } else
13767                 to_intel_atomic_state(state)->cdclk = dev_priv->atomic_cdclk_freq;
13768
13769         intel_modeset_clear_plls(state);
13770
13771         if (IS_HASWELL(dev_priv))
13772                 return haswell_mode_set_planes_workaround(state);
13773
13774         return 0;
13775 }
13776
13777 /*
13778  * Handle calculation of various watermark data at the end of the atomic check
13779  * phase.  The code here should be run after the per-crtc and per-plane 'check'
13780  * handlers to ensure that all derived state has been updated.
13781  */
13782 static int calc_watermark_data(struct drm_atomic_state *state)
13783 {
13784         struct drm_device *dev = state->dev;
13785         struct drm_i915_private *dev_priv = to_i915(dev);
13786
13787         /* Is there platform-specific watermark information to calculate? */
13788         if (dev_priv->display.compute_global_watermarks)
13789                 return dev_priv->display.compute_global_watermarks(state);
13790
13791         return 0;
13792 }
13793
13794 /**
13795  * intel_atomic_check - validate state object
13796  * @dev: drm device
13797  * @state: state to validate
13798  */
13799 static int intel_atomic_check(struct drm_device *dev,
13800                               struct drm_atomic_state *state)
13801 {
13802         struct drm_i915_private *dev_priv = to_i915(dev);
13803         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
13804         struct drm_crtc *crtc;
13805         struct drm_crtc_state *crtc_state;
13806         int ret, i;
13807         bool any_ms = false;
13808
13809         ret = drm_atomic_helper_check_modeset(dev, state);
13810         if (ret)
13811                 return ret;
13812
13813         for_each_crtc_in_state(state, crtc, crtc_state, i) {
13814                 struct intel_crtc_state *pipe_config =
13815                         to_intel_crtc_state(crtc_state);
13816
13817                 /* Catch I915_MODE_FLAG_INHERITED */
13818                 if (crtc_state->mode.private_flags != crtc->state->mode.private_flags)
13819                         crtc_state->mode_changed = true;
13820
13821                 if (!needs_modeset(crtc_state))
13822                         continue;
13823
13824                 if (!crtc_state->enable) {
13825                         any_ms = true;
13826                         continue;
13827                 }
13828
13829                 /* FIXME: For only active_changed we shouldn't need to do any
13830                  * state recomputation at all. */
13831
13832                 ret = drm_atomic_add_affected_connectors(state, crtc);
13833                 if (ret)
13834                         return ret;
13835
13836                 ret = intel_modeset_pipe_config(crtc, pipe_config);
13837                 if (ret) {
13838                         intel_dump_pipe_config(to_intel_crtc(crtc),
13839                                                pipe_config, "[failed]");
13840                         return ret;
13841                 }
13842
13843                 if (i915.fastboot &&
13844                     intel_pipe_config_compare(dev,
13845                                         to_intel_crtc_state(crtc->state),
13846                                         pipe_config, true)) {
13847                         crtc_state->mode_changed = false;
13848                         to_intel_crtc_state(crtc_state)->update_pipe = true;
13849                 }
13850
13851                 if (needs_modeset(crtc_state))
13852                         any_ms = true;
13853
13854                 ret = drm_atomic_add_affected_planes(state, crtc);
13855                 if (ret)
13856                         return ret;
13857
13858                 intel_dump_pipe_config(to_intel_crtc(crtc), pipe_config,
13859                                        needs_modeset(crtc_state) ?
13860                                        "[modeset]" : "[fastset]");
13861         }
13862
13863         if (any_ms) {
13864                 ret = intel_modeset_checks(state);
13865
13866                 if (ret)
13867                         return ret;
13868         } else
13869                 intel_state->cdclk = dev_priv->cdclk_freq;
13870
13871         ret = drm_atomic_helper_check_planes(dev, state);
13872         if (ret)
13873                 return ret;
13874
13875         intel_fbc_choose_crtc(dev_priv, state);
13876         return calc_watermark_data(state);
13877 }
13878
13879 static int intel_atomic_prepare_commit(struct drm_device *dev,
13880                                        struct drm_atomic_state *state,
13881                                        bool nonblock)
13882 {
13883         struct drm_i915_private *dev_priv = to_i915(dev);
13884         struct drm_plane_state *plane_state;
13885         struct drm_crtc_state *crtc_state;
13886         struct drm_plane *plane;
13887         struct drm_crtc *crtc;
13888         int i, ret;
13889
13890         for_each_crtc_in_state(state, crtc, crtc_state, i) {
13891                 if (state->legacy_cursor_update)
13892                         continue;
13893
13894                 ret = intel_crtc_wait_for_pending_flips(crtc);
13895                 if (ret)
13896                         return ret;
13897
13898                 if (atomic_read(&to_intel_crtc(crtc)->unpin_work_count) >= 2)
13899                         flush_workqueue(dev_priv->wq);
13900         }
13901
13902         ret = mutex_lock_interruptible(&dev->struct_mutex);
13903         if (ret)
13904                 return ret;
13905
13906         ret = drm_atomic_helper_prepare_planes(dev, state);
13907         mutex_unlock(&dev->struct_mutex);
13908
13909         if (!ret && !nonblock) {
13910                 for_each_plane_in_state(state, plane, plane_state, i) {
13911                         struct intel_plane_state *intel_plane_state =
13912                                 to_intel_plane_state(plane_state);
13913
13914                         if (!intel_plane_state->wait_req)
13915                                 continue;
13916
13917                         ret = i915_wait_request(intel_plane_state->wait_req,
13918                                                 true, NULL, NULL);
13919                         if (ret) {
13920                                 /* Any hang should be swallowed by the wait */
13921                                 WARN_ON(ret == -EIO);
13922                                 mutex_lock(&dev->struct_mutex);
13923                                 drm_atomic_helper_cleanup_planes(dev, state);
13924                                 mutex_unlock(&dev->struct_mutex);
13925                                 break;
13926                         }
13927                 }
13928         }
13929
13930         return ret;
13931 }
13932
13933 u32 intel_crtc_get_vblank_counter(struct intel_crtc *crtc)
13934 {
13935         struct drm_device *dev = crtc->base.dev;
13936
13937         if (!dev->max_vblank_count)
13938                 return drm_accurate_vblank_count(&crtc->base);
13939
13940         return dev->driver->get_vblank_counter(dev, crtc->pipe);
13941 }
13942
13943 static void intel_atomic_wait_for_vblanks(struct drm_device *dev,
13944                                           struct drm_i915_private *dev_priv,
13945                                           unsigned crtc_mask)
13946 {
13947         unsigned last_vblank_count[I915_MAX_PIPES];
13948         enum pipe pipe;
13949         int ret;
13950
13951         if (!crtc_mask)
13952                 return;
13953
13954         for_each_pipe(dev_priv, pipe) {
13955                 struct drm_crtc *crtc = dev_priv->pipe_to_crtc_mapping[pipe];
13956
13957                 if (!((1 << pipe) & crtc_mask))
13958                         continue;
13959
13960                 ret = drm_crtc_vblank_get(crtc);
13961                 if (WARN_ON(ret != 0)) {
13962                         crtc_mask &= ~(1 << pipe);
13963                         continue;
13964                 }
13965
13966                 last_vblank_count[pipe] = drm_crtc_vblank_count(crtc);
13967         }
13968
13969         for_each_pipe(dev_priv, pipe) {
13970                 struct drm_crtc *crtc = dev_priv->pipe_to_crtc_mapping[pipe];
13971                 long lret;
13972
13973                 if (!((1 << pipe) & crtc_mask))
13974                         continue;
13975
13976                 lret = wait_event_timeout(dev->vblank[pipe].queue,
13977                                 last_vblank_count[pipe] !=
13978                                         drm_crtc_vblank_count(crtc),
13979                                 msecs_to_jiffies(50));
13980
13981                 WARN(!lret, "pipe %c vblank wait timed out\n", pipe_name(pipe));
13982
13983                 drm_crtc_vblank_put(crtc);
13984         }
13985 }
13986
13987 static bool needs_vblank_wait(struct intel_crtc_state *crtc_state)
13988 {
13989         /* fb updated, need to unpin old fb */
13990         if (crtc_state->fb_changed)
13991                 return true;
13992
13993         /* wm changes, need vblank before final wm's */
13994         if (crtc_state->update_wm_post)
13995                 return true;
13996
13997         /*
13998          * cxsr is re-enabled after vblank.
13999          * This is already handled by crtc_state->update_wm_post,
14000          * but added for clarity.
14001          */
14002         if (crtc_state->disable_cxsr)
14003                 return true;
14004
14005         return false;
14006 }
14007
14008 static void intel_atomic_commit_tail(struct drm_atomic_state *state)
14009 {
14010         struct drm_device *dev = state->dev;
14011         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
14012         struct drm_i915_private *dev_priv = to_i915(dev);
14013         struct drm_crtc_state *old_crtc_state;
14014         struct drm_crtc *crtc;
14015         struct intel_crtc_state *intel_cstate;
14016         struct drm_plane *plane;
14017         struct drm_plane_state *plane_state;
14018         bool hw_check = intel_state->modeset;
14019         unsigned long put_domains[I915_MAX_PIPES] = {};
14020         unsigned crtc_vblank_mask = 0;
14021         int i, ret;
14022
14023         for_each_plane_in_state(state, plane, plane_state, i) {
14024                 struct intel_plane_state *intel_plane_state =
14025                         to_intel_plane_state(plane_state);
14026
14027                 if (!intel_plane_state->wait_req)
14028                         continue;
14029
14030                 ret = i915_wait_request(intel_plane_state->wait_req,
14031                                         true, NULL, NULL);
14032                 /* EIO should be eaten, and we can't get interrupted in the
14033                  * worker, and blocking commits have waited already. */
14034                 WARN_ON(ret);
14035         }
14036
14037         drm_atomic_helper_wait_for_dependencies(state);
14038
14039         if (intel_state->modeset) {
14040                 memcpy(dev_priv->min_pixclk, intel_state->min_pixclk,
14041                        sizeof(intel_state->min_pixclk));
14042                 dev_priv->active_crtcs = intel_state->active_crtcs;
14043                 dev_priv->atomic_cdclk_freq = intel_state->cdclk;
14044
14045                 intel_display_power_get(dev_priv, POWER_DOMAIN_MODESET);
14046         }
14047
14048         for_each_crtc_in_state(state, crtc, old_crtc_state, i) {
14049                 struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
14050
14051                 if (needs_modeset(crtc->state) ||
14052                     to_intel_crtc_state(crtc->state)->update_pipe) {
14053                         hw_check = true;
14054
14055                         put_domains[to_intel_crtc(crtc)->pipe] =
14056                                 modeset_get_crtc_power_domains(crtc,
14057                                         to_intel_crtc_state(crtc->state));
14058                 }
14059
14060                 if (!needs_modeset(crtc->state))
14061                         continue;
14062
14063                 intel_pre_plane_update(to_intel_crtc_state(old_crtc_state));
14064
14065                 if (old_crtc_state->active) {
14066                         intel_crtc_disable_planes(crtc, old_crtc_state->plane_mask);
14067                         dev_priv->display.crtc_disable(crtc);
14068                         intel_crtc->active = false;
14069                         intel_fbc_disable(intel_crtc);
14070                         intel_disable_shared_dpll(intel_crtc);
14071
14072                         /*
14073                          * Underruns don't always raise
14074                          * interrupts, so check manually.
14075                          */
14076                         intel_check_cpu_fifo_underruns(dev_priv);
14077                         intel_check_pch_fifo_underruns(dev_priv);
14078
14079                         if (!crtc->state->active)
14080                                 intel_update_watermarks(crtc);
14081                 }
14082         }
14083
14084         /* Only after disabling all output pipelines that will be changed can we
14085          * update the the output configuration. */
14086         intel_modeset_update_crtc_state(state);
14087
14088         if (intel_state->modeset) {
14089                 drm_atomic_helper_update_legacy_modeset_state(state->dev, state);
14090
14091                 if (dev_priv->display.modeset_commit_cdclk &&
14092                     (intel_state->dev_cdclk != dev_priv->cdclk_freq ||
14093                      intel_state->cdclk_pll_vco != dev_priv->cdclk_pll.vco))
14094                         dev_priv->display.modeset_commit_cdclk(state);
14095
14096                 intel_modeset_verify_disabled(dev);
14097         }
14098
14099         /* Now enable the clocks, plane, pipe, and connectors that we set up. */
14100         for_each_crtc_in_state(state, crtc, old_crtc_state, i) {
14101                 struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
14102                 bool modeset = needs_modeset(crtc->state);
14103                 struct intel_crtc_state *pipe_config =
14104                         to_intel_crtc_state(crtc->state);
14105
14106                 if (modeset && crtc->state->active) {
14107                         update_scanline_offset(to_intel_crtc(crtc));
14108                         dev_priv->display.crtc_enable(crtc);
14109                 }
14110
14111                 /* Complete events for now disable pipes here. */
14112                 if (modeset && !crtc->state->active && crtc->state->event) {
14113                         spin_lock_irq(&dev->event_lock);
14114                         drm_crtc_send_vblank_event(crtc, crtc->state->event);
14115                         spin_unlock_irq(&dev->event_lock);
14116
14117                         crtc->state->event = NULL;
14118                 }
14119
14120                 if (!modeset)
14121                         intel_pre_plane_update(to_intel_crtc_state(old_crtc_state));
14122
14123                 if (crtc->state->active &&
14124                     drm_atomic_get_existing_plane_state(state, crtc->primary))
14125                         intel_fbc_enable(intel_crtc, pipe_config, to_intel_plane_state(crtc->primary->state));
14126
14127                 if (crtc->state->active)
14128                         drm_atomic_helper_commit_planes_on_crtc(old_crtc_state);
14129
14130                 if (pipe_config->base.active && needs_vblank_wait(pipe_config))
14131                         crtc_vblank_mask |= 1 << i;
14132         }
14133
14134         /* FIXME: We should call drm_atomic_helper_commit_hw_done() here
14135          * already, but still need the state for the delayed optimization. To
14136          * fix this:
14137          * - wrap the optimization/post_plane_update stuff into a per-crtc work.
14138          * - schedule that vblank worker _before_ calling hw_done
14139          * - at the start of commit_tail, cancel it _synchrously
14140          * - switch over to the vblank wait helper in the core after that since
14141          *   we don't need out special handling any more.
14142          */
14143         if (!state->legacy_cursor_update)
14144                 intel_atomic_wait_for_vblanks(dev, dev_priv, crtc_vblank_mask);
14145
14146         /*
14147          * Now that the vblank has passed, we can go ahead and program the
14148          * optimal watermarks on platforms that need two-step watermark
14149          * programming.
14150          *
14151          * TODO: Move this (and other cleanup) to an async worker eventually.
14152          */
14153         for_each_crtc_in_state(state, crtc, old_crtc_state, i) {
14154                 intel_cstate = to_intel_crtc_state(crtc->state);
14155
14156                 if (dev_priv->display.optimize_watermarks)
14157                         dev_priv->display.optimize_watermarks(intel_cstate);
14158         }
14159
14160         for_each_crtc_in_state(state, crtc, old_crtc_state, i) {
14161                 intel_post_plane_update(to_intel_crtc_state(old_crtc_state));
14162
14163                 if (put_domains[i])
14164                         modeset_put_power_domains(dev_priv, put_domains[i]);
14165
14166                 intel_modeset_verify_crtc(crtc, old_crtc_state, crtc->state);
14167         }
14168
14169         drm_atomic_helper_commit_hw_done(state);
14170
14171         if (intel_state->modeset)
14172                 intel_display_power_put(dev_priv, POWER_DOMAIN_MODESET);
14173
14174         mutex_lock(&dev->struct_mutex);
14175         drm_atomic_helper_cleanup_planes(dev, state);
14176         mutex_unlock(&dev->struct_mutex);
14177
14178         drm_atomic_helper_commit_cleanup_done(state);
14179
14180         drm_atomic_state_free(state);
14181
14182         /* As one of the primary mmio accessors, KMS has a high likelihood
14183          * of triggering bugs in unclaimed access. After we finish
14184          * modesetting, see if an error has been flagged, and if so
14185          * enable debugging for the next modeset - and hope we catch
14186          * the culprit.
14187          *
14188          * XXX note that we assume display power is on at this point.
14189          * This might hold true now but we need to add pm helper to check
14190          * unclaimed only when the hardware is on, as atomic commits
14191          * can happen also when the device is completely off.
14192          */
14193         intel_uncore_arm_unclaimed_mmio_detection(dev_priv);
14194 }
14195
14196 static void intel_atomic_commit_work(struct work_struct *work)
14197 {
14198         struct drm_atomic_state *state = container_of(work,
14199                                                       struct drm_atomic_state,
14200                                                       commit_work);
14201         intel_atomic_commit_tail(state);
14202 }
14203
14204 static void intel_atomic_track_fbs(struct drm_atomic_state *state)
14205 {
14206         struct drm_plane_state *old_plane_state;
14207         struct drm_plane *plane;
14208         int i;
14209
14210         for_each_plane_in_state(state, plane, old_plane_state, i)
14211                 i915_gem_track_fb(intel_fb_obj(old_plane_state->fb),
14212                                   intel_fb_obj(plane->state->fb),
14213                                   to_intel_plane(plane)->frontbuffer_bit);
14214 }
14215
14216 /**
14217  * intel_atomic_commit - commit validated state object
14218  * @dev: DRM device
14219  * @state: the top-level driver state object
14220  * @nonblock: nonblocking commit
14221  *
14222  * This function commits a top-level state object that has been validated
14223  * with drm_atomic_helper_check().
14224  *
14225  * FIXME:  Atomic modeset support for i915 is not yet complete.  At the moment
14226  * nonblocking commits are only safe for pure plane updates. Everything else
14227  * should work though.
14228  *
14229  * RETURNS
14230  * Zero for success or -errno.
14231  */
14232 static int intel_atomic_commit(struct drm_device *dev,
14233                                struct drm_atomic_state *state,
14234                                bool nonblock)
14235 {
14236         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
14237         struct drm_i915_private *dev_priv = to_i915(dev);
14238         int ret = 0;
14239
14240         if (intel_state->modeset && nonblock) {
14241                 DRM_DEBUG_KMS("nonblocking commit for modeset not yet implemented.\n");
14242                 return -EINVAL;
14243         }
14244
14245         ret = drm_atomic_helper_setup_commit(state, nonblock);
14246         if (ret)
14247                 return ret;
14248
14249         INIT_WORK(&state->commit_work, intel_atomic_commit_work);
14250
14251         ret = intel_atomic_prepare_commit(dev, state, nonblock);
14252         if (ret) {
14253                 DRM_DEBUG_ATOMIC("Preparing state failed with %i\n", ret);
14254                 return ret;
14255         }
14256
14257         drm_atomic_helper_swap_state(state, true);
14258         dev_priv->wm.distrust_bios_wm = false;
14259         dev_priv->wm.skl_results = intel_state->wm_results;
14260         intel_shared_dpll_commit(state);
14261         intel_atomic_track_fbs(state);
14262
14263         if (nonblock)
14264                 queue_work(system_unbound_wq, &state->commit_work);
14265         else
14266                 intel_atomic_commit_tail(state);
14267
14268         return 0;
14269 }
14270
14271 void intel_crtc_restore_mode(struct drm_crtc *crtc)
14272 {
14273         struct drm_device *dev = crtc->dev;
14274         struct drm_atomic_state *state;
14275         struct drm_crtc_state *crtc_state;
14276         int ret;
14277
14278         state = drm_atomic_state_alloc(dev);
14279         if (!state) {
14280                 DRM_DEBUG_KMS("[CRTC:%d:%s] crtc restore failed, out of memory",
14281                               crtc->base.id, crtc->name);
14282                 return;
14283         }
14284
14285         state->acquire_ctx = drm_modeset_legacy_acquire_ctx(crtc);
14286
14287 retry:
14288         crtc_state = drm_atomic_get_crtc_state(state, crtc);
14289         ret = PTR_ERR_OR_ZERO(crtc_state);
14290         if (!ret) {
14291                 if (!crtc_state->active)
14292                         goto out;
14293
14294                 crtc_state->mode_changed = true;
14295                 ret = drm_atomic_commit(state);
14296         }
14297
14298         if (ret == -EDEADLK) {
14299                 drm_atomic_state_clear(state);
14300                 drm_modeset_backoff(state->acquire_ctx);
14301                 goto retry;
14302         }
14303
14304         if (ret)
14305 out:
14306                 drm_atomic_state_free(state);
14307 }
14308
14309 #undef for_each_intel_crtc_masked
14310
14311 /*
14312  * FIXME: Remove this once i915 is fully DRIVER_ATOMIC by calling
14313  *        drm_atomic_helper_legacy_gamma_set() directly.
14314  */
14315 static int intel_atomic_legacy_gamma_set(struct drm_crtc *crtc,
14316                                          u16 *red, u16 *green, u16 *blue,
14317                                          uint32_t size)
14318 {
14319         struct drm_device *dev = crtc->dev;
14320         struct drm_mode_config *config = &dev->mode_config;
14321         struct drm_crtc_state *state;
14322         int ret;
14323
14324         ret = drm_atomic_helper_legacy_gamma_set(crtc, red, green, blue, size);
14325         if (ret)
14326                 return ret;
14327
14328         /*
14329          * Make sure we update the legacy properties so this works when
14330          * atomic is not enabled.
14331          */
14332
14333         state = crtc->state;
14334
14335         drm_object_property_set_value(&crtc->base,
14336                                       config->degamma_lut_property,
14337                                       (state->degamma_lut) ?
14338                                       state->degamma_lut->base.id : 0);
14339
14340         drm_object_property_set_value(&crtc->base,
14341                                       config->ctm_property,
14342                                       (state->ctm) ?
14343                                       state->ctm->base.id : 0);
14344
14345         drm_object_property_set_value(&crtc->base,
14346                                       config->gamma_lut_property,
14347                                       (state->gamma_lut) ?
14348                                       state->gamma_lut->base.id : 0);
14349
14350         return 0;
14351 }
14352
14353 static const struct drm_crtc_funcs intel_crtc_funcs = {
14354         .gamma_set = intel_atomic_legacy_gamma_set,
14355         .set_config = drm_atomic_helper_set_config,
14356         .set_property = drm_atomic_helper_crtc_set_property,
14357         .destroy = intel_crtc_destroy,
14358         .page_flip = intel_crtc_page_flip,
14359         .atomic_duplicate_state = intel_crtc_duplicate_state,
14360         .atomic_destroy_state = intel_crtc_destroy_state,
14361 };
14362
14363 /**
14364  * intel_prepare_plane_fb - Prepare fb for usage on plane
14365  * @plane: drm plane to prepare for
14366  * @fb: framebuffer to prepare for presentation
14367  *
14368  * Prepares a framebuffer for usage on a display plane.  Generally this
14369  * involves pinning the underlying object and updating the frontbuffer tracking
14370  * bits.  Some older platforms need special physical address handling for
14371  * cursor planes.
14372  *
14373  * Must be called with struct_mutex held.
14374  *
14375  * Returns 0 on success, negative error code on failure.
14376  */
14377 int
14378 intel_prepare_plane_fb(struct drm_plane *plane,
14379                        const struct drm_plane_state *new_state)
14380 {
14381         struct drm_device *dev = plane->dev;
14382         struct drm_framebuffer *fb = new_state->fb;
14383         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
14384         struct drm_i915_gem_object *old_obj = intel_fb_obj(plane->state->fb);
14385         struct reservation_object *resv;
14386         int ret = 0;
14387
14388         if (!obj && !old_obj)
14389                 return 0;
14390
14391         if (old_obj) {
14392                 struct drm_crtc_state *crtc_state =
14393                         drm_atomic_get_existing_crtc_state(new_state->state, plane->state->crtc);
14394
14395                 /* Big Hammer, we also need to ensure that any pending
14396                  * MI_WAIT_FOR_EVENT inside a user batch buffer on the
14397                  * current scanout is retired before unpinning the old
14398                  * framebuffer. Note that we rely on userspace rendering
14399                  * into the buffer attached to the pipe they are waiting
14400                  * on. If not, userspace generates a GPU hang with IPEHR
14401                  * point to the MI_WAIT_FOR_EVENT.
14402                  *
14403                  * This should only fail upon a hung GPU, in which case we
14404                  * can safely continue.
14405                  */
14406                 if (needs_modeset(crtc_state))
14407                         ret = i915_gem_object_wait_rendering(old_obj, true);
14408                 if (ret) {
14409                         /* GPU hangs should have been swallowed by the wait */
14410                         WARN_ON(ret == -EIO);
14411                         return ret;
14412                 }
14413         }
14414
14415         if (!obj)
14416                 return 0;
14417
14418         /* For framebuffer backed by dmabuf, wait for fence */
14419         resv = i915_gem_object_get_dmabuf_resv(obj);
14420         if (resv) {
14421                 long lret;
14422
14423                 lret = reservation_object_wait_timeout_rcu(resv, false, true,
14424                                                            MAX_SCHEDULE_TIMEOUT);
14425                 if (lret == -ERESTARTSYS)
14426                         return lret;
14427
14428                 WARN(lret < 0, "waiting returns %li\n", lret);
14429         }
14430
14431         if (plane->type == DRM_PLANE_TYPE_CURSOR &&
14432             INTEL_INFO(dev)->cursor_needs_physical) {
14433                 int align = IS_I830(dev) ? 16 * 1024 : 256;
14434                 ret = i915_gem_object_attach_phys(obj, align);
14435                 if (ret)
14436                         DRM_DEBUG_KMS("failed to attach phys object\n");
14437         } else {
14438                 ret = intel_pin_and_fence_fb_obj(fb, new_state->rotation);
14439         }
14440
14441         if (ret == 0) {
14442                 to_intel_plane_state(new_state)->wait_req =
14443                         i915_gem_active_get(&obj->last_write,
14444                                             &obj->base.dev->struct_mutex);
14445         }
14446
14447         return ret;
14448 }
14449
14450 /**
14451  * intel_cleanup_plane_fb - Cleans up an fb after plane use
14452  * @plane: drm plane to clean up for
14453  * @fb: old framebuffer that was on plane
14454  *
14455  * Cleans up a framebuffer that has just been removed from a plane.
14456  *
14457  * Must be called with struct_mutex held.
14458  */
14459 void
14460 intel_cleanup_plane_fb(struct drm_plane *plane,
14461                        const struct drm_plane_state *old_state)
14462 {
14463         struct drm_device *dev = plane->dev;
14464         struct intel_plane_state *old_intel_state;
14465         struct intel_plane_state *intel_state = to_intel_plane_state(plane->state);
14466         struct drm_i915_gem_object *old_obj = intel_fb_obj(old_state->fb);
14467         struct drm_i915_gem_object *obj = intel_fb_obj(plane->state->fb);
14468
14469         old_intel_state = to_intel_plane_state(old_state);
14470
14471         if (!obj && !old_obj)
14472                 return;
14473
14474         if (old_obj && (plane->type != DRM_PLANE_TYPE_CURSOR ||
14475             !INTEL_INFO(dev)->cursor_needs_physical))
14476                 intel_unpin_fb_obj(old_state->fb, old_state->rotation);
14477
14478         i915_gem_request_assign(&intel_state->wait_req, NULL);
14479         i915_gem_request_assign(&old_intel_state->wait_req, NULL);
14480 }
14481
14482 int
14483 skl_max_scale(struct intel_crtc *intel_crtc, struct intel_crtc_state *crtc_state)
14484 {
14485         int max_scale;
14486         int crtc_clock, cdclk;
14487
14488         if (!intel_crtc || !crtc_state->base.enable)
14489                 return DRM_PLANE_HELPER_NO_SCALING;
14490
14491         crtc_clock = crtc_state->base.adjusted_mode.crtc_clock;
14492         cdclk = to_intel_atomic_state(crtc_state->base.state)->cdclk;
14493
14494         if (WARN_ON_ONCE(!crtc_clock || cdclk < crtc_clock))
14495                 return DRM_PLANE_HELPER_NO_SCALING;
14496
14497         /*
14498          * skl max scale is lower of:
14499          *    close to 3 but not 3, -1 is for that purpose
14500          *            or
14501          *    cdclk/crtc_clock
14502          */
14503         max_scale = min((1 << 16) * 3 - 1, (1 << 8) * ((cdclk << 8) / crtc_clock));
14504
14505         return max_scale;
14506 }
14507
14508 static int
14509 intel_check_primary_plane(struct drm_plane *plane,
14510                           struct intel_crtc_state *crtc_state,
14511                           struct intel_plane_state *state)
14512 {
14513         struct drm_i915_private *dev_priv = to_i915(plane->dev);
14514         struct drm_crtc *crtc = state->base.crtc;
14515         struct drm_framebuffer *fb = state->base.fb;
14516         int min_scale = DRM_PLANE_HELPER_NO_SCALING;
14517         int max_scale = DRM_PLANE_HELPER_NO_SCALING;
14518         bool can_position = false;
14519         int ret;
14520
14521         if (INTEL_GEN(dev_priv) >= 9) {
14522                 /* use scaler when colorkey is not required */
14523                 if (state->ckey.flags == I915_SET_COLORKEY_NONE) {
14524                         min_scale = 1;
14525                         max_scale = skl_max_scale(to_intel_crtc(crtc), crtc_state);
14526                 }
14527                 can_position = true;
14528         }
14529
14530         ret = drm_plane_helper_check_update(plane, crtc, fb, &state->src,
14531                                             &state->dst, &state->clip,
14532                                             state->base.rotation,
14533                                             min_scale, max_scale,
14534                                             can_position, true,
14535                                             &state->visible);
14536         if (ret)
14537                 return ret;
14538
14539         if (!fb)
14540                 return 0;
14541
14542         if (INTEL_GEN(dev_priv) >= 9) {
14543                 ret = skl_check_plane_surface(state);
14544                 if (ret)
14545                         return ret;
14546         }
14547
14548         return 0;
14549 }
14550
14551 static void intel_begin_crtc_commit(struct drm_crtc *crtc,
14552                                     struct drm_crtc_state *old_crtc_state)
14553 {
14554         struct drm_device *dev = crtc->dev;
14555         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
14556         struct intel_crtc_state *old_intel_state =
14557                 to_intel_crtc_state(old_crtc_state);
14558         bool modeset = needs_modeset(crtc->state);
14559
14560         /* Perform vblank evasion around commit operation */
14561         intel_pipe_update_start(intel_crtc);
14562
14563         if (modeset)
14564                 return;
14565
14566         if (crtc->state->color_mgmt_changed || to_intel_crtc_state(crtc->state)->update_pipe) {
14567                 intel_color_set_csc(crtc->state);
14568                 intel_color_load_luts(crtc->state);
14569         }
14570
14571         if (to_intel_crtc_state(crtc->state)->update_pipe)
14572                 intel_update_pipe_config(intel_crtc, old_intel_state);
14573         else if (INTEL_INFO(dev)->gen >= 9)
14574                 skl_detach_scalers(intel_crtc);
14575 }
14576
14577 static void intel_finish_crtc_commit(struct drm_crtc *crtc,
14578                                      struct drm_crtc_state *old_crtc_state)
14579 {
14580         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
14581
14582         intel_pipe_update_end(intel_crtc, NULL);
14583 }
14584
14585 /**
14586  * intel_plane_destroy - destroy a plane
14587  * @plane: plane to destroy
14588  *
14589  * Common destruction function for all types of planes (primary, cursor,
14590  * sprite).
14591  */
14592 void intel_plane_destroy(struct drm_plane *plane)
14593 {
14594         if (!plane)
14595                 return;
14596
14597         drm_plane_cleanup(plane);
14598         kfree(to_intel_plane(plane));
14599 }
14600
14601 const struct drm_plane_funcs intel_plane_funcs = {
14602         .update_plane = drm_atomic_helper_update_plane,
14603         .disable_plane = drm_atomic_helper_disable_plane,
14604         .destroy = intel_plane_destroy,
14605         .set_property = drm_atomic_helper_plane_set_property,
14606         .atomic_get_property = intel_plane_atomic_get_property,
14607         .atomic_set_property = intel_plane_atomic_set_property,
14608         .atomic_duplicate_state = intel_plane_duplicate_state,
14609         .atomic_destroy_state = intel_plane_destroy_state,
14610
14611 };
14612
14613 static struct drm_plane *intel_primary_plane_create(struct drm_device *dev,
14614                                                     int pipe)
14615 {
14616         struct intel_plane *primary = NULL;
14617         struct intel_plane_state *state = NULL;
14618         const uint32_t *intel_primary_formats;
14619         unsigned int num_formats;
14620         int ret;
14621
14622         primary = kzalloc(sizeof(*primary), GFP_KERNEL);
14623         if (!primary)
14624                 goto fail;
14625
14626         state = intel_create_plane_state(&primary->base);
14627         if (!state)
14628                 goto fail;
14629         primary->base.state = &state->base;
14630
14631         primary->can_scale = false;
14632         primary->max_downscale = 1;
14633         if (INTEL_INFO(dev)->gen >= 9) {
14634                 primary->can_scale = true;
14635                 state->scaler_id = -1;
14636         }
14637         primary->pipe = pipe;
14638         primary->plane = pipe;
14639         primary->frontbuffer_bit = INTEL_FRONTBUFFER_PRIMARY(pipe);
14640         primary->check_plane = intel_check_primary_plane;
14641         if (HAS_FBC(dev) && INTEL_INFO(dev)->gen < 4)
14642                 primary->plane = !pipe;
14643
14644         if (INTEL_INFO(dev)->gen >= 9) {
14645                 intel_primary_formats = skl_primary_formats;
14646                 num_formats = ARRAY_SIZE(skl_primary_formats);
14647
14648                 primary->update_plane = skylake_update_primary_plane;
14649                 primary->disable_plane = skylake_disable_primary_plane;
14650         } else if (HAS_PCH_SPLIT(dev)) {
14651                 intel_primary_formats = i965_primary_formats;
14652                 num_formats = ARRAY_SIZE(i965_primary_formats);
14653
14654                 primary->update_plane = ironlake_update_primary_plane;
14655                 primary->disable_plane = i9xx_disable_primary_plane;
14656         } else if (INTEL_INFO(dev)->gen >= 4) {
14657                 intel_primary_formats = i965_primary_formats;
14658                 num_formats = ARRAY_SIZE(i965_primary_formats);
14659
14660                 primary->update_plane = i9xx_update_primary_plane;
14661                 primary->disable_plane = i9xx_disable_primary_plane;
14662         } else {
14663                 intel_primary_formats = i8xx_primary_formats;
14664                 num_formats = ARRAY_SIZE(i8xx_primary_formats);
14665
14666                 primary->update_plane = i9xx_update_primary_plane;
14667                 primary->disable_plane = i9xx_disable_primary_plane;
14668         }
14669
14670         if (INTEL_INFO(dev)->gen >= 9)
14671                 ret = drm_universal_plane_init(dev, &primary->base, 0,
14672                                                &intel_plane_funcs,
14673                                                intel_primary_formats, num_formats,
14674                                                DRM_PLANE_TYPE_PRIMARY,
14675                                                "plane 1%c", pipe_name(pipe));
14676         else if (INTEL_INFO(dev)->gen >= 5 || IS_G4X(dev))
14677                 ret = drm_universal_plane_init(dev, &primary->base, 0,
14678                                                &intel_plane_funcs,
14679                                                intel_primary_formats, num_formats,
14680                                                DRM_PLANE_TYPE_PRIMARY,
14681                                                "primary %c", pipe_name(pipe));
14682         else
14683                 ret = drm_universal_plane_init(dev, &primary->base, 0,
14684                                                &intel_plane_funcs,
14685                                                intel_primary_formats, num_formats,
14686                                                DRM_PLANE_TYPE_PRIMARY,
14687                                                "plane %c", plane_name(primary->plane));
14688         if (ret)
14689                 goto fail;
14690
14691         if (INTEL_INFO(dev)->gen >= 4)
14692                 intel_create_rotation_property(dev, primary);
14693
14694         drm_plane_helper_add(&primary->base, &intel_plane_helper_funcs);
14695
14696         return &primary->base;
14697
14698 fail:
14699         kfree(state);
14700         kfree(primary);
14701
14702         return NULL;
14703 }
14704
14705 void intel_create_rotation_property(struct drm_device *dev, struct intel_plane *plane)
14706 {
14707         if (!dev->mode_config.rotation_property) {
14708                 unsigned long flags = BIT(DRM_ROTATE_0) |
14709                         BIT(DRM_ROTATE_180);
14710
14711                 if (INTEL_INFO(dev)->gen >= 9)
14712                         flags |= BIT(DRM_ROTATE_90) | BIT(DRM_ROTATE_270);
14713
14714                 dev->mode_config.rotation_property =
14715                         drm_mode_create_rotation_property(dev, flags);
14716         }
14717         if (dev->mode_config.rotation_property)
14718                 drm_object_attach_property(&plane->base.base,
14719                                 dev->mode_config.rotation_property,
14720                                 plane->base.state->rotation);
14721 }
14722
14723 static int
14724 intel_check_cursor_plane(struct drm_plane *plane,
14725                          struct intel_crtc_state *crtc_state,
14726                          struct intel_plane_state *state)
14727 {
14728         struct drm_crtc *crtc = crtc_state->base.crtc;
14729         struct drm_framebuffer *fb = state->base.fb;
14730         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
14731         enum pipe pipe = to_intel_plane(plane)->pipe;
14732         unsigned stride;
14733         int ret;
14734
14735         ret = drm_plane_helper_check_update(plane, crtc, fb, &state->src,
14736                                             &state->dst, &state->clip,
14737                                             state->base.rotation,
14738                                             DRM_PLANE_HELPER_NO_SCALING,
14739                                             DRM_PLANE_HELPER_NO_SCALING,
14740                                             true, true, &state->visible);
14741         if (ret)
14742                 return ret;
14743
14744         /* if we want to turn off the cursor ignore width and height */
14745         if (!obj)
14746                 return 0;
14747
14748         /* Check for which cursor types we support */
14749         if (!cursor_size_ok(plane->dev, state->base.crtc_w, state->base.crtc_h)) {
14750                 DRM_DEBUG("Cursor dimension %dx%d not supported\n",
14751                           state->base.crtc_w, state->base.crtc_h);
14752                 return -EINVAL;
14753         }
14754
14755         stride = roundup_pow_of_two(state->base.crtc_w) * 4;
14756         if (obj->base.size < stride * state->base.crtc_h) {
14757                 DRM_DEBUG_KMS("buffer is too small\n");
14758                 return -ENOMEM;
14759         }
14760
14761         if (fb->modifier[0] != DRM_FORMAT_MOD_NONE) {
14762                 DRM_DEBUG_KMS("cursor cannot be tiled\n");
14763                 return -EINVAL;
14764         }
14765
14766         /*
14767          * There's something wrong with the cursor on CHV pipe C.
14768          * If it straddles the left edge of the screen then
14769          * moving it away from the edge or disabling it often
14770          * results in a pipe underrun, and often that can lead to
14771          * dead pipe (constant underrun reported, and it scans
14772          * out just a solid color). To recover from that, the
14773          * display power well must be turned off and on again.
14774          * Refuse the put the cursor into that compromised position.
14775          */
14776         if (IS_CHERRYVIEW(plane->dev) && pipe == PIPE_C &&
14777             state->visible && state->base.crtc_x < 0) {
14778                 DRM_DEBUG_KMS("CHV cursor C not allowed to straddle the left screen edge\n");
14779                 return -EINVAL;
14780         }
14781
14782         return 0;
14783 }
14784
14785 static void
14786 intel_disable_cursor_plane(struct drm_plane *plane,
14787                            struct drm_crtc *crtc)
14788 {
14789         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
14790
14791         intel_crtc->cursor_addr = 0;
14792         intel_crtc_update_cursor(crtc, NULL);
14793 }
14794
14795 static void
14796 intel_update_cursor_plane(struct drm_plane *plane,
14797                           const struct intel_crtc_state *crtc_state,
14798                           const struct intel_plane_state *state)
14799 {
14800         struct drm_crtc *crtc = crtc_state->base.crtc;
14801         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
14802         struct drm_device *dev = plane->dev;
14803         struct drm_i915_gem_object *obj = intel_fb_obj(state->base.fb);
14804         uint32_t addr;
14805
14806         if (!obj)
14807                 addr = 0;
14808         else if (!INTEL_INFO(dev)->cursor_needs_physical)
14809                 addr = i915_gem_obj_ggtt_offset(obj);
14810         else
14811                 addr = obj->phys_handle->busaddr;
14812
14813         intel_crtc->cursor_addr = addr;
14814         intel_crtc_update_cursor(crtc, state);
14815 }
14816
14817 static struct drm_plane *intel_cursor_plane_create(struct drm_device *dev,
14818                                                    int pipe)
14819 {
14820         struct intel_plane *cursor = NULL;
14821         struct intel_plane_state *state = NULL;
14822         int ret;
14823
14824         cursor = kzalloc(sizeof(*cursor), GFP_KERNEL);
14825         if (!cursor)
14826                 goto fail;
14827
14828         state = intel_create_plane_state(&cursor->base);
14829         if (!state)
14830                 goto fail;
14831         cursor->base.state = &state->base;
14832
14833         cursor->can_scale = false;
14834         cursor->max_downscale = 1;
14835         cursor->pipe = pipe;
14836         cursor->plane = pipe;
14837         cursor->frontbuffer_bit = INTEL_FRONTBUFFER_CURSOR(pipe);
14838         cursor->check_plane = intel_check_cursor_plane;
14839         cursor->update_plane = intel_update_cursor_plane;
14840         cursor->disable_plane = intel_disable_cursor_plane;
14841
14842         ret = drm_universal_plane_init(dev, &cursor->base, 0,
14843                                        &intel_plane_funcs,
14844                                        intel_cursor_formats,
14845                                        ARRAY_SIZE(intel_cursor_formats),
14846                                        DRM_PLANE_TYPE_CURSOR,
14847                                        "cursor %c", pipe_name(pipe));
14848         if (ret)
14849                 goto fail;
14850
14851         if (INTEL_INFO(dev)->gen >= 4) {
14852                 if (!dev->mode_config.rotation_property)
14853                         dev->mode_config.rotation_property =
14854                                 drm_mode_create_rotation_property(dev,
14855                                                         BIT(DRM_ROTATE_0) |
14856                                                         BIT(DRM_ROTATE_180));
14857                 if (dev->mode_config.rotation_property)
14858                         drm_object_attach_property(&cursor->base.base,
14859                                 dev->mode_config.rotation_property,
14860                                 state->base.rotation);
14861         }
14862
14863         if (INTEL_INFO(dev)->gen >=9)
14864                 state->scaler_id = -1;
14865
14866         drm_plane_helper_add(&cursor->base, &intel_plane_helper_funcs);
14867
14868         return &cursor->base;
14869
14870 fail:
14871         kfree(state);
14872         kfree(cursor);
14873
14874         return NULL;
14875 }
14876
14877 static void skl_init_scalers(struct drm_device *dev, struct intel_crtc *intel_crtc,
14878         struct intel_crtc_state *crtc_state)
14879 {
14880         int i;
14881         struct intel_scaler *intel_scaler;
14882         struct intel_crtc_scaler_state *scaler_state = &crtc_state->scaler_state;
14883
14884         for (i = 0; i < intel_crtc->num_scalers; i++) {
14885                 intel_scaler = &scaler_state->scalers[i];
14886                 intel_scaler->in_use = 0;
14887                 intel_scaler->mode = PS_SCALER_MODE_DYN;
14888         }
14889
14890         scaler_state->scaler_id = -1;
14891 }
14892
14893 static void intel_crtc_init(struct drm_device *dev, int pipe)
14894 {
14895         struct drm_i915_private *dev_priv = to_i915(dev);
14896         struct intel_crtc *intel_crtc;
14897         struct intel_crtc_state *crtc_state = NULL;
14898         struct drm_plane *primary = NULL;
14899         struct drm_plane *cursor = NULL;
14900         int ret;
14901
14902         intel_crtc = kzalloc(sizeof(*intel_crtc), GFP_KERNEL);
14903         if (intel_crtc == NULL)
14904                 return;
14905
14906         crtc_state = kzalloc(sizeof(*crtc_state), GFP_KERNEL);
14907         if (!crtc_state)
14908                 goto fail;
14909         intel_crtc->config = crtc_state;
14910         intel_crtc->base.state = &crtc_state->base;
14911         crtc_state->base.crtc = &intel_crtc->base;
14912
14913         /* initialize shared scalers */
14914         if (INTEL_INFO(dev)->gen >= 9) {
14915                 if (pipe == PIPE_C)
14916                         intel_crtc->num_scalers = 1;
14917                 else
14918                         intel_crtc->num_scalers = SKL_NUM_SCALERS;
14919
14920                 skl_init_scalers(dev, intel_crtc, crtc_state);
14921         }
14922
14923         primary = intel_primary_plane_create(dev, pipe);
14924         if (!primary)
14925                 goto fail;
14926
14927         cursor = intel_cursor_plane_create(dev, pipe);
14928         if (!cursor)
14929                 goto fail;
14930
14931         ret = drm_crtc_init_with_planes(dev, &intel_crtc->base, primary,
14932                                         cursor, &intel_crtc_funcs,
14933                                         "pipe %c", pipe_name(pipe));
14934         if (ret)
14935                 goto fail;
14936
14937         /*
14938          * On gen2/3 only plane A can do fbc, but the panel fitter and lvds port
14939          * is hooked to pipe B. Hence we want plane A feeding pipe B.
14940          */
14941         intel_crtc->pipe = pipe;
14942         intel_crtc->plane = pipe;
14943         if (HAS_FBC(dev) && INTEL_INFO(dev)->gen < 4) {
14944                 DRM_DEBUG_KMS("swapping pipes & planes for FBC\n");
14945                 intel_crtc->plane = !pipe;
14946         }
14947
14948         intel_crtc->cursor_base = ~0;
14949         intel_crtc->cursor_cntl = ~0;
14950         intel_crtc->cursor_size = ~0;
14951
14952         intel_crtc->wm.cxsr_allowed = true;
14953
14954         BUG_ON(pipe >= ARRAY_SIZE(dev_priv->plane_to_crtc_mapping) ||
14955                dev_priv->plane_to_crtc_mapping[intel_crtc->plane] != NULL);
14956         dev_priv->plane_to_crtc_mapping[intel_crtc->plane] = &intel_crtc->base;
14957         dev_priv->pipe_to_crtc_mapping[intel_crtc->pipe] = &intel_crtc->base;
14958
14959         drm_crtc_helper_add(&intel_crtc->base, &intel_helper_funcs);
14960
14961         intel_color_init(&intel_crtc->base);
14962
14963         WARN_ON(drm_crtc_index(&intel_crtc->base) != intel_crtc->pipe);
14964         return;
14965
14966 fail:
14967         intel_plane_destroy(primary);
14968         intel_plane_destroy(cursor);
14969         kfree(crtc_state);
14970         kfree(intel_crtc);
14971 }
14972
14973 enum pipe intel_get_pipe_from_connector(struct intel_connector *connector)
14974 {
14975         struct drm_encoder *encoder = connector->base.encoder;
14976         struct drm_device *dev = connector->base.dev;
14977
14978         WARN_ON(!drm_modeset_is_locked(&dev->mode_config.connection_mutex));
14979
14980         if (!encoder || WARN_ON(!encoder->crtc))
14981                 return INVALID_PIPE;
14982
14983         return to_intel_crtc(encoder->crtc)->pipe;
14984 }
14985
14986 int intel_get_pipe_from_crtc_id(struct drm_device *dev, void *data,
14987                                 struct drm_file *file)
14988 {
14989         struct drm_i915_get_pipe_from_crtc_id *pipe_from_crtc_id = data;
14990         struct drm_crtc *drmmode_crtc;
14991         struct intel_crtc *crtc;
14992
14993         drmmode_crtc = drm_crtc_find(dev, pipe_from_crtc_id->crtc_id);
14994         if (!drmmode_crtc)
14995                 return -ENOENT;
14996
14997         crtc = to_intel_crtc(drmmode_crtc);
14998         pipe_from_crtc_id->pipe = crtc->pipe;
14999
15000         return 0;
15001 }
15002
15003 static int intel_encoder_clones(struct intel_encoder *encoder)
15004 {
15005         struct drm_device *dev = encoder->base.dev;
15006         struct intel_encoder *source_encoder;
15007         int index_mask = 0;
15008         int entry = 0;
15009
15010         for_each_intel_encoder(dev, source_encoder) {
15011                 if (encoders_cloneable(encoder, source_encoder))
15012                         index_mask |= (1 << entry);
15013
15014                 entry++;
15015         }
15016
15017         return index_mask;
15018 }
15019
15020 static bool has_edp_a(struct drm_device *dev)
15021 {
15022         struct drm_i915_private *dev_priv = to_i915(dev);
15023
15024         if (!IS_MOBILE(dev))
15025                 return false;
15026
15027         if ((I915_READ(DP_A) & DP_DETECTED) == 0)
15028                 return false;
15029
15030         if (IS_GEN5(dev) && (I915_READ(FUSE_STRAP) & ILK_eDP_A_DISABLE))
15031                 return false;
15032
15033         return true;
15034 }
15035
15036 static bool intel_crt_present(struct drm_device *dev)
15037 {
15038         struct drm_i915_private *dev_priv = to_i915(dev);
15039
15040         if (INTEL_INFO(dev)->gen >= 9)
15041                 return false;
15042
15043         if (IS_HSW_ULT(dev) || IS_BDW_ULT(dev))
15044                 return false;
15045
15046         if (IS_CHERRYVIEW(dev))
15047                 return false;
15048
15049         if (HAS_PCH_LPT_H(dev) && I915_READ(SFUSE_STRAP) & SFUSE_STRAP_CRT_DISABLED)
15050                 return false;
15051
15052         /* DDI E can't be used if DDI A requires 4 lanes */
15053         if (HAS_DDI(dev) && I915_READ(DDI_BUF_CTL(PORT_A)) & DDI_A_4_LANES)
15054                 return false;
15055
15056         if (!dev_priv->vbt.int_crt_support)
15057                 return false;
15058
15059         return true;
15060 }
15061
15062 void intel_pps_unlock_regs_wa(struct drm_i915_private *dev_priv)
15063 {
15064         int pps_num;
15065         int pps_idx;
15066
15067         if (HAS_DDI(dev_priv))
15068                 return;
15069         /*
15070          * This w/a is needed at least on CPT/PPT, but to be sure apply it
15071          * everywhere where registers can be write protected.
15072          */
15073         if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
15074                 pps_num = 2;
15075         else
15076                 pps_num = 1;
15077
15078         for (pps_idx = 0; pps_idx < pps_num; pps_idx++) {
15079                 u32 val = I915_READ(PP_CONTROL(pps_idx));
15080
15081                 val = (val & ~PANEL_UNLOCK_MASK) | PANEL_UNLOCK_REGS;
15082                 I915_WRITE(PP_CONTROL(pps_idx), val);
15083         }
15084 }
15085
15086 static void intel_pps_init(struct drm_i915_private *dev_priv)
15087 {
15088         if (HAS_PCH_SPLIT(dev_priv) || IS_BROXTON(dev_priv))
15089                 dev_priv->pps_mmio_base = PCH_PPS_BASE;
15090         else if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
15091                 dev_priv->pps_mmio_base = VLV_PPS_BASE;
15092         else
15093                 dev_priv->pps_mmio_base = PPS_BASE;
15094
15095         intel_pps_unlock_regs_wa(dev_priv);
15096 }
15097
15098 static void intel_setup_outputs(struct drm_device *dev)
15099 {
15100         struct drm_i915_private *dev_priv = to_i915(dev);
15101         struct intel_encoder *encoder;
15102         bool dpd_is_edp = false;
15103
15104         intel_pps_init(dev_priv);
15105
15106         /*
15107          * intel_edp_init_connector() depends on this completing first, to
15108          * prevent the registeration of both eDP and LVDS and the incorrect
15109          * sharing of the PPS.
15110          */
15111         intel_lvds_init(dev);
15112
15113         if (intel_crt_present(dev))
15114                 intel_crt_init(dev);
15115
15116         if (IS_BROXTON(dev)) {
15117                 /*
15118                  * FIXME: Broxton doesn't support port detection via the
15119                  * DDI_BUF_CTL_A or SFUSE_STRAP registers, find another way to
15120                  * detect the ports.
15121                  */
15122                 intel_ddi_init(dev, PORT_A);
15123                 intel_ddi_init(dev, PORT_B);
15124                 intel_ddi_init(dev, PORT_C);
15125
15126                 intel_dsi_init(dev);
15127         } else if (HAS_DDI(dev)) {
15128                 int found;
15129
15130                 /*
15131                  * Haswell uses DDI functions to detect digital outputs.
15132                  * On SKL pre-D0 the strap isn't connected, so we assume
15133                  * it's there.
15134                  */
15135                 found = I915_READ(DDI_BUF_CTL(PORT_A)) & DDI_INIT_DISPLAY_DETECTED;
15136                 /* WaIgnoreDDIAStrap: skl */
15137                 if (found || IS_SKYLAKE(dev) || IS_KABYLAKE(dev))
15138                         intel_ddi_init(dev, PORT_A);
15139
15140                 /* DDI B, C and D detection is indicated by the SFUSE_STRAP
15141                  * register */
15142                 found = I915_READ(SFUSE_STRAP);
15143
15144                 if (found & SFUSE_STRAP_DDIB_DETECTED)
15145                         intel_ddi_init(dev, PORT_B);
15146                 if (found & SFUSE_STRAP_DDIC_DETECTED)
15147                         intel_ddi_init(dev, PORT_C);
15148                 if (found & SFUSE_STRAP_DDID_DETECTED)
15149                         intel_ddi_init(dev, PORT_D);
15150                 /*
15151                  * On SKL we don't have a way to detect DDI-E so we rely on VBT.
15152                  */
15153                 if ((IS_SKYLAKE(dev) || IS_KABYLAKE(dev)) &&
15154                     (dev_priv->vbt.ddi_port_info[PORT_E].supports_dp ||
15155                      dev_priv->vbt.ddi_port_info[PORT_E].supports_dvi ||
15156                      dev_priv->vbt.ddi_port_info[PORT_E].supports_hdmi))
15157                         intel_ddi_init(dev, PORT_E);
15158
15159         } else if (HAS_PCH_SPLIT(dev)) {
15160                 int found;
15161                 dpd_is_edp = intel_dp_is_edp(dev, PORT_D);
15162
15163                 if (has_edp_a(dev))
15164                         intel_dp_init(dev, DP_A, PORT_A);
15165
15166                 if (I915_READ(PCH_HDMIB) & SDVO_DETECTED) {
15167                         /* PCH SDVOB multiplex with HDMIB */
15168                         found = intel_sdvo_init(dev, PCH_SDVOB, PORT_B);
15169                         if (!found)
15170                                 intel_hdmi_init(dev, PCH_HDMIB, PORT_B);
15171                         if (!found && (I915_READ(PCH_DP_B) & DP_DETECTED))
15172                                 intel_dp_init(dev, PCH_DP_B, PORT_B);
15173                 }
15174
15175                 if (I915_READ(PCH_HDMIC) & SDVO_DETECTED)
15176                         intel_hdmi_init(dev, PCH_HDMIC, PORT_C);
15177
15178                 if (!dpd_is_edp && I915_READ(PCH_HDMID) & SDVO_DETECTED)
15179                         intel_hdmi_init(dev, PCH_HDMID, PORT_D);
15180
15181                 if (I915_READ(PCH_DP_C) & DP_DETECTED)
15182                         intel_dp_init(dev, PCH_DP_C, PORT_C);
15183
15184                 if (I915_READ(PCH_DP_D) & DP_DETECTED)
15185                         intel_dp_init(dev, PCH_DP_D, PORT_D);
15186         } else if (IS_VALLEYVIEW(dev) || IS_CHERRYVIEW(dev)) {
15187                 bool has_edp, has_port;
15188
15189                 /*
15190                  * The DP_DETECTED bit is the latched state of the DDC
15191                  * SDA pin at boot. However since eDP doesn't require DDC
15192                  * (no way to plug in a DP->HDMI dongle) the DDC pins for
15193                  * eDP ports may have been muxed to an alternate function.
15194                  * Thus we can't rely on the DP_DETECTED bit alone to detect
15195                  * eDP ports. Consult the VBT as well as DP_DETECTED to
15196                  * detect eDP ports.
15197                  *
15198                  * Sadly the straps seem to be missing sometimes even for HDMI
15199                  * ports (eg. on Voyo V3 - CHT x7-Z8700), so check both strap
15200                  * and VBT for the presence of the port. Additionally we can't
15201                  * trust the port type the VBT declares as we've seen at least
15202                  * HDMI ports that the VBT claim are DP or eDP.
15203                  */
15204                 has_edp = intel_dp_is_edp(dev, PORT_B);
15205                 has_port = intel_bios_is_port_present(dev_priv, PORT_B);
15206                 if (I915_READ(VLV_DP_B) & DP_DETECTED || has_port)
15207                         has_edp &= intel_dp_init(dev, VLV_DP_B, PORT_B);
15208                 if ((I915_READ(VLV_HDMIB) & SDVO_DETECTED || has_port) && !has_edp)
15209                         intel_hdmi_init(dev, VLV_HDMIB, PORT_B);
15210
15211                 has_edp = intel_dp_is_edp(dev, PORT_C);
15212                 has_port = intel_bios_is_port_present(dev_priv, PORT_C);
15213                 if (I915_READ(VLV_DP_C) & DP_DETECTED || has_port)
15214                         has_edp &= intel_dp_init(dev, VLV_DP_C, PORT_C);
15215                 if ((I915_READ(VLV_HDMIC) & SDVO_DETECTED || has_port) && !has_edp)
15216                         intel_hdmi_init(dev, VLV_HDMIC, PORT_C);
15217
15218                 if (IS_CHERRYVIEW(dev)) {
15219                         /*
15220                          * eDP not supported on port D,
15221                          * so no need to worry about it
15222                          */
15223                         has_port = intel_bios_is_port_present(dev_priv, PORT_D);
15224                         if (I915_READ(CHV_DP_D) & DP_DETECTED || has_port)
15225                                 intel_dp_init(dev, CHV_DP_D, PORT_D);
15226                         if (I915_READ(CHV_HDMID) & SDVO_DETECTED || has_port)
15227                                 intel_hdmi_init(dev, CHV_HDMID, PORT_D);
15228                 }
15229
15230                 intel_dsi_init(dev);
15231         } else if (!IS_GEN2(dev) && !IS_PINEVIEW(dev)) {
15232                 bool found = false;
15233
15234                 if (I915_READ(GEN3_SDVOB) & SDVO_DETECTED) {
15235                         DRM_DEBUG_KMS("probing SDVOB\n");
15236                         found = intel_sdvo_init(dev, GEN3_SDVOB, PORT_B);
15237                         if (!found && IS_G4X(dev)) {
15238                                 DRM_DEBUG_KMS("probing HDMI on SDVOB\n");
15239                                 intel_hdmi_init(dev, GEN4_HDMIB, PORT_B);
15240                         }
15241
15242                         if (!found && IS_G4X(dev))
15243                                 intel_dp_init(dev, DP_B, PORT_B);
15244                 }
15245
15246                 /* Before G4X SDVOC doesn't have its own detect register */
15247
15248                 if (I915_READ(GEN3_SDVOB) & SDVO_DETECTED) {
15249                         DRM_DEBUG_KMS("probing SDVOC\n");
15250                         found = intel_sdvo_init(dev, GEN3_SDVOC, PORT_C);
15251                 }
15252
15253                 if (!found && (I915_READ(GEN3_SDVOC) & SDVO_DETECTED)) {
15254
15255                         if (IS_G4X(dev)) {
15256                                 DRM_DEBUG_KMS("probing HDMI on SDVOC\n");
15257                                 intel_hdmi_init(dev, GEN4_HDMIC, PORT_C);
15258                         }
15259                         if (IS_G4X(dev))
15260                                 intel_dp_init(dev, DP_C, PORT_C);
15261                 }
15262
15263                 if (IS_G4X(dev) &&
15264                     (I915_READ(DP_D) & DP_DETECTED))
15265                         intel_dp_init(dev, DP_D, PORT_D);
15266         } else if (IS_GEN2(dev))
15267                 intel_dvo_init(dev);
15268
15269         if (SUPPORTS_TV(dev))
15270                 intel_tv_init(dev);
15271
15272         intel_psr_init(dev);
15273
15274         for_each_intel_encoder(dev, encoder) {
15275                 encoder->base.possible_crtcs = encoder->crtc_mask;
15276                 encoder->base.possible_clones =
15277                         intel_encoder_clones(encoder);
15278         }
15279
15280         intel_init_pch_refclk(dev);
15281
15282         drm_helper_move_panel_connectors_to_head(dev);
15283 }
15284
15285 static void intel_user_framebuffer_destroy(struct drm_framebuffer *fb)
15286 {
15287         struct drm_device *dev = fb->dev;
15288         struct intel_framebuffer *intel_fb = to_intel_framebuffer(fb);
15289
15290         drm_framebuffer_cleanup(fb);
15291         mutex_lock(&dev->struct_mutex);
15292         WARN_ON(!intel_fb->obj->framebuffer_references--);
15293         i915_gem_object_put(intel_fb->obj);
15294         mutex_unlock(&dev->struct_mutex);
15295         kfree(intel_fb);
15296 }
15297
15298 static int intel_user_framebuffer_create_handle(struct drm_framebuffer *fb,
15299                                                 struct drm_file *file,
15300                                                 unsigned int *handle)
15301 {
15302         struct intel_framebuffer *intel_fb = to_intel_framebuffer(fb);
15303         struct drm_i915_gem_object *obj = intel_fb->obj;
15304
15305         if (obj->userptr.mm) {
15306                 DRM_DEBUG("attempting to use a userptr for a framebuffer, denied\n");
15307                 return -EINVAL;
15308         }
15309
15310         return drm_gem_handle_create(file, &obj->base, handle);
15311 }
15312
15313 static int intel_user_framebuffer_dirty(struct drm_framebuffer *fb,
15314                                         struct drm_file *file,
15315                                         unsigned flags, unsigned color,
15316                                         struct drm_clip_rect *clips,
15317                                         unsigned num_clips)
15318 {
15319         struct drm_device *dev = fb->dev;
15320         struct intel_framebuffer *intel_fb = to_intel_framebuffer(fb);
15321         struct drm_i915_gem_object *obj = intel_fb->obj;
15322
15323         mutex_lock(&dev->struct_mutex);
15324         intel_fb_obj_flush(obj, false, ORIGIN_DIRTYFB);
15325         mutex_unlock(&dev->struct_mutex);
15326
15327         return 0;
15328 }
15329
15330 static const struct drm_framebuffer_funcs intel_fb_funcs = {
15331         .destroy = intel_user_framebuffer_destroy,
15332         .create_handle = intel_user_framebuffer_create_handle,
15333         .dirty = intel_user_framebuffer_dirty,
15334 };
15335
15336 static
15337 u32 intel_fb_pitch_limit(struct drm_device *dev, uint64_t fb_modifier,
15338                          uint32_t pixel_format)
15339 {
15340         u32 gen = INTEL_INFO(dev)->gen;
15341
15342         if (gen >= 9) {
15343                 int cpp = drm_format_plane_cpp(pixel_format, 0);
15344
15345                 /* "The stride in bytes must not exceed the of the size of 8K
15346                  *  pixels and 32K bytes."
15347                  */
15348                 return min(8192 * cpp, 32768);
15349         } else if (gen >= 5 && !IS_VALLEYVIEW(dev) && !IS_CHERRYVIEW(dev)) {
15350                 return 32*1024;
15351         } else if (gen >= 4) {
15352                 if (fb_modifier == I915_FORMAT_MOD_X_TILED)
15353                         return 16*1024;
15354                 else
15355                         return 32*1024;
15356         } else if (gen >= 3) {
15357                 if (fb_modifier == I915_FORMAT_MOD_X_TILED)
15358                         return 8*1024;
15359                 else
15360                         return 16*1024;
15361         } else {
15362                 /* XXX DSPC is limited to 4k tiled */
15363                 return 8*1024;
15364         }
15365 }
15366
15367 static int intel_framebuffer_init(struct drm_device *dev,
15368                                   struct intel_framebuffer *intel_fb,
15369                                   struct drm_mode_fb_cmd2 *mode_cmd,
15370                                   struct drm_i915_gem_object *obj)
15371 {
15372         struct drm_i915_private *dev_priv = to_i915(dev);
15373         unsigned int tiling = i915_gem_object_get_tiling(obj);
15374         int ret;
15375         u32 pitch_limit, stride_alignment;
15376
15377         WARN_ON(!mutex_is_locked(&dev->struct_mutex));
15378
15379         if (mode_cmd->flags & DRM_MODE_FB_MODIFIERS) {
15380                 /*
15381                  * If there's a fence, enforce that
15382                  * the fb modifier and tiling mode match.
15383                  */
15384                 if (tiling != I915_TILING_NONE &&
15385                     tiling != intel_fb_modifier_to_tiling(mode_cmd->modifier[0])) {
15386                         DRM_DEBUG("tiling_mode doesn't match fb modifier\n");
15387                         return -EINVAL;
15388                 }
15389         } else {
15390                 if (tiling == I915_TILING_X) {
15391                         mode_cmd->modifier[0] = I915_FORMAT_MOD_X_TILED;
15392                 } else if (tiling == I915_TILING_Y) {
15393                         DRM_DEBUG("No Y tiling for legacy addfb\n");
15394                         return -EINVAL;
15395                 }
15396         }
15397
15398         /* Passed in modifier sanity checking. */
15399         switch (mode_cmd->modifier[0]) {
15400         case I915_FORMAT_MOD_Y_TILED:
15401         case I915_FORMAT_MOD_Yf_TILED:
15402                 if (INTEL_INFO(dev)->gen < 9) {
15403                         DRM_DEBUG("Unsupported tiling 0x%llx!\n",
15404                                   mode_cmd->modifier[0]);
15405                         return -EINVAL;
15406                 }
15407         case DRM_FORMAT_MOD_NONE:
15408         case I915_FORMAT_MOD_X_TILED:
15409                 break;
15410         default:
15411                 DRM_DEBUG("Unsupported fb modifier 0x%llx!\n",
15412                           mode_cmd->modifier[0]);
15413                 return -EINVAL;
15414         }
15415
15416         /*
15417          * gen2/3 display engine uses the fence if present,
15418          * so the tiling mode must match the fb modifier exactly.
15419          */
15420         if (INTEL_INFO(dev_priv)->gen < 4 &&
15421             tiling != intel_fb_modifier_to_tiling(mode_cmd->modifier[0])) {
15422                 DRM_DEBUG("tiling_mode must match fb modifier exactly on gen2/3\n");
15423                 return -EINVAL;
15424         }
15425
15426         stride_alignment = intel_fb_stride_alignment(dev_priv,
15427                                                      mode_cmd->modifier[0],
15428                                                      mode_cmd->pixel_format);
15429         if (mode_cmd->pitches[0] & (stride_alignment - 1)) {
15430                 DRM_DEBUG("pitch (%d) must be at least %u byte aligned\n",
15431                           mode_cmd->pitches[0], stride_alignment);
15432                 return -EINVAL;
15433         }
15434
15435         pitch_limit = intel_fb_pitch_limit(dev, mode_cmd->modifier[0],
15436                                            mode_cmd->pixel_format);
15437         if (mode_cmd->pitches[0] > pitch_limit) {
15438                 DRM_DEBUG("%s pitch (%u) must be at less than %d\n",
15439                           mode_cmd->modifier[0] != DRM_FORMAT_MOD_NONE ?
15440                           "tiled" : "linear",
15441                           mode_cmd->pitches[0], pitch_limit);
15442                 return -EINVAL;
15443         }
15444
15445         /*
15446          * If there's a fence, enforce that
15447          * the fb pitch and fence stride match.
15448          */
15449         if (tiling != I915_TILING_NONE &&
15450             mode_cmd->pitches[0] != i915_gem_object_get_stride(obj)) {
15451                 DRM_DEBUG("pitch (%d) must match tiling stride (%d)\n",
15452                           mode_cmd->pitches[0],
15453                           i915_gem_object_get_stride(obj));
15454                 return -EINVAL;
15455         }
15456
15457         /* Reject formats not supported by any plane early. */
15458         switch (mode_cmd->pixel_format) {
15459         case DRM_FORMAT_C8:
15460         case DRM_FORMAT_RGB565:
15461         case DRM_FORMAT_XRGB8888:
15462         case DRM_FORMAT_ARGB8888:
15463                 break;
15464         case DRM_FORMAT_XRGB1555:
15465                 if (INTEL_INFO(dev)->gen > 3) {
15466                         DRM_DEBUG("unsupported pixel format: %s\n",
15467                                   drm_get_format_name(mode_cmd->pixel_format));
15468                         return -EINVAL;
15469                 }
15470                 break;
15471         case DRM_FORMAT_ABGR8888:
15472                 if (!IS_VALLEYVIEW(dev) && !IS_CHERRYVIEW(dev) &&
15473                     INTEL_INFO(dev)->gen < 9) {
15474                         DRM_DEBUG("unsupported pixel format: %s\n",
15475                                   drm_get_format_name(mode_cmd->pixel_format));
15476                         return -EINVAL;
15477                 }
15478                 break;
15479         case DRM_FORMAT_XBGR8888:
15480         case DRM_FORMAT_XRGB2101010:
15481         case DRM_FORMAT_XBGR2101010:
15482                 if (INTEL_INFO(dev)->gen < 4) {
15483                         DRM_DEBUG("unsupported pixel format: %s\n",
15484                                   drm_get_format_name(mode_cmd->pixel_format));
15485                         return -EINVAL;
15486                 }
15487                 break;
15488         case DRM_FORMAT_ABGR2101010:
15489                 if (!IS_VALLEYVIEW(dev) && !IS_CHERRYVIEW(dev)) {
15490                         DRM_DEBUG("unsupported pixel format: %s\n",
15491                                   drm_get_format_name(mode_cmd->pixel_format));
15492                         return -EINVAL;
15493                 }
15494                 break;
15495         case DRM_FORMAT_YUYV:
15496         case DRM_FORMAT_UYVY:
15497         case DRM_FORMAT_YVYU:
15498         case DRM_FORMAT_VYUY:
15499                 if (INTEL_INFO(dev)->gen < 5) {
15500                         DRM_DEBUG("unsupported pixel format: %s\n",
15501                                   drm_get_format_name(mode_cmd->pixel_format));
15502                         return -EINVAL;
15503                 }
15504                 break;
15505         default:
15506                 DRM_DEBUG("unsupported pixel format: %s\n",
15507                           drm_get_format_name(mode_cmd->pixel_format));
15508                 return -EINVAL;
15509         }
15510
15511         /* FIXME need to adjust LINOFF/TILEOFF accordingly. */
15512         if (mode_cmd->offsets[0] != 0)
15513                 return -EINVAL;
15514
15515         drm_helper_mode_fill_fb_struct(&intel_fb->base, mode_cmd);
15516         intel_fb->obj = obj;
15517
15518         ret = intel_fill_fb_info(dev_priv, &intel_fb->base);
15519         if (ret)
15520                 return ret;
15521
15522         ret = drm_framebuffer_init(dev, &intel_fb->base, &intel_fb_funcs);
15523         if (ret) {
15524                 DRM_ERROR("framebuffer init failed %d\n", ret);
15525                 return ret;
15526         }
15527
15528         intel_fb->obj->framebuffer_references++;
15529
15530         return 0;
15531 }
15532
15533 static struct drm_framebuffer *
15534 intel_user_framebuffer_create(struct drm_device *dev,
15535                               struct drm_file *filp,
15536                               const struct drm_mode_fb_cmd2 *user_mode_cmd)
15537 {
15538         struct drm_framebuffer *fb;
15539         struct drm_i915_gem_object *obj;
15540         struct drm_mode_fb_cmd2 mode_cmd = *user_mode_cmd;
15541
15542         obj = i915_gem_object_lookup(filp, mode_cmd.handles[0]);
15543         if (!obj)
15544                 return ERR_PTR(-ENOENT);
15545
15546         fb = intel_framebuffer_create(dev, &mode_cmd, obj);
15547         if (IS_ERR(fb))
15548                 i915_gem_object_put_unlocked(obj);
15549
15550         return fb;
15551 }
15552
15553 #ifndef CONFIG_DRM_FBDEV_EMULATION
15554 static inline void intel_fbdev_output_poll_changed(struct drm_device *dev)
15555 {
15556 }
15557 #endif
15558
15559 static const struct drm_mode_config_funcs intel_mode_funcs = {
15560         .fb_create = intel_user_framebuffer_create,
15561         .output_poll_changed = intel_fbdev_output_poll_changed,
15562         .atomic_check = intel_atomic_check,
15563         .atomic_commit = intel_atomic_commit,
15564         .atomic_state_alloc = intel_atomic_state_alloc,
15565         .atomic_state_clear = intel_atomic_state_clear,
15566 };
15567
15568 /**
15569  * intel_init_display_hooks - initialize the display modesetting hooks
15570  * @dev_priv: device private
15571  */
15572 void intel_init_display_hooks(struct drm_i915_private *dev_priv)
15573 {
15574         if (INTEL_INFO(dev_priv)->gen >= 9) {
15575                 dev_priv->display.get_pipe_config = haswell_get_pipe_config;
15576                 dev_priv->display.get_initial_plane_config =
15577                         skylake_get_initial_plane_config;
15578                 dev_priv->display.crtc_compute_clock =
15579                         haswell_crtc_compute_clock;
15580                 dev_priv->display.crtc_enable = haswell_crtc_enable;
15581                 dev_priv->display.crtc_disable = haswell_crtc_disable;
15582         } else if (HAS_DDI(dev_priv)) {
15583                 dev_priv->display.get_pipe_config = haswell_get_pipe_config;
15584                 dev_priv->display.get_initial_plane_config =
15585                         ironlake_get_initial_plane_config;
15586                 dev_priv->display.crtc_compute_clock =
15587                         haswell_crtc_compute_clock;
15588                 dev_priv->display.crtc_enable = haswell_crtc_enable;
15589                 dev_priv->display.crtc_disable = haswell_crtc_disable;
15590         } else if (HAS_PCH_SPLIT(dev_priv)) {
15591                 dev_priv->display.get_pipe_config = ironlake_get_pipe_config;
15592                 dev_priv->display.get_initial_plane_config =
15593                         ironlake_get_initial_plane_config;
15594                 dev_priv->display.crtc_compute_clock =
15595                         ironlake_crtc_compute_clock;
15596                 dev_priv->display.crtc_enable = ironlake_crtc_enable;
15597                 dev_priv->display.crtc_disable = ironlake_crtc_disable;
15598         } else if (IS_CHERRYVIEW(dev_priv)) {
15599                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
15600                 dev_priv->display.get_initial_plane_config =
15601                         i9xx_get_initial_plane_config;
15602                 dev_priv->display.crtc_compute_clock = chv_crtc_compute_clock;
15603                 dev_priv->display.crtc_enable = valleyview_crtc_enable;
15604                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
15605         } else if (IS_VALLEYVIEW(dev_priv)) {
15606                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
15607                 dev_priv->display.get_initial_plane_config =
15608                         i9xx_get_initial_plane_config;
15609                 dev_priv->display.crtc_compute_clock = vlv_crtc_compute_clock;
15610                 dev_priv->display.crtc_enable = valleyview_crtc_enable;
15611                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
15612         } else if (IS_G4X(dev_priv)) {
15613                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
15614                 dev_priv->display.get_initial_plane_config =
15615                         i9xx_get_initial_plane_config;
15616                 dev_priv->display.crtc_compute_clock = g4x_crtc_compute_clock;
15617                 dev_priv->display.crtc_enable = i9xx_crtc_enable;
15618                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
15619         } else if (IS_PINEVIEW(dev_priv)) {
15620                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
15621                 dev_priv->display.get_initial_plane_config =
15622                         i9xx_get_initial_plane_config;
15623                 dev_priv->display.crtc_compute_clock = pnv_crtc_compute_clock;
15624                 dev_priv->display.crtc_enable = i9xx_crtc_enable;
15625                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
15626         } else if (!IS_GEN2(dev_priv)) {
15627                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
15628                 dev_priv->display.get_initial_plane_config =
15629                         i9xx_get_initial_plane_config;
15630                 dev_priv->display.crtc_compute_clock = i9xx_crtc_compute_clock;
15631                 dev_priv->display.crtc_enable = i9xx_crtc_enable;
15632                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
15633         } else {
15634                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
15635                 dev_priv->display.get_initial_plane_config =
15636                         i9xx_get_initial_plane_config;
15637                 dev_priv->display.crtc_compute_clock = i8xx_crtc_compute_clock;
15638                 dev_priv->display.crtc_enable = i9xx_crtc_enable;
15639                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
15640         }
15641
15642         /* Returns the core display clock speed */
15643         if (IS_SKYLAKE(dev_priv) || IS_KABYLAKE(dev_priv))
15644                 dev_priv->display.get_display_clock_speed =
15645                         skylake_get_display_clock_speed;
15646         else if (IS_BROXTON(dev_priv))
15647                 dev_priv->display.get_display_clock_speed =
15648                         broxton_get_display_clock_speed;
15649         else if (IS_BROADWELL(dev_priv))
15650                 dev_priv->display.get_display_clock_speed =
15651                         broadwell_get_display_clock_speed;
15652         else if (IS_HASWELL(dev_priv))
15653                 dev_priv->display.get_display_clock_speed =
15654                         haswell_get_display_clock_speed;
15655         else if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
15656                 dev_priv->display.get_display_clock_speed =
15657                         valleyview_get_display_clock_speed;
15658         else if (IS_GEN5(dev_priv))
15659                 dev_priv->display.get_display_clock_speed =
15660                         ilk_get_display_clock_speed;
15661         else if (IS_I945G(dev_priv) || IS_BROADWATER(dev_priv) ||
15662                  IS_GEN6(dev_priv) || IS_IVYBRIDGE(dev_priv))
15663                 dev_priv->display.get_display_clock_speed =
15664                         i945_get_display_clock_speed;
15665         else if (IS_GM45(dev_priv))
15666                 dev_priv->display.get_display_clock_speed =
15667                         gm45_get_display_clock_speed;
15668         else if (IS_CRESTLINE(dev_priv))
15669                 dev_priv->display.get_display_clock_speed =
15670                         i965gm_get_display_clock_speed;
15671         else if (IS_PINEVIEW(dev_priv))
15672                 dev_priv->display.get_display_clock_speed =
15673                         pnv_get_display_clock_speed;
15674         else if (IS_G33(dev_priv) || IS_G4X(dev_priv))
15675                 dev_priv->display.get_display_clock_speed =
15676                         g33_get_display_clock_speed;
15677         else if (IS_I915G(dev_priv))
15678                 dev_priv->display.get_display_clock_speed =
15679                         i915_get_display_clock_speed;
15680         else if (IS_I945GM(dev_priv) || IS_845G(dev_priv))
15681                 dev_priv->display.get_display_clock_speed =
15682                         i9xx_misc_get_display_clock_speed;
15683         else if (IS_I915GM(dev_priv))
15684                 dev_priv->display.get_display_clock_speed =
15685                         i915gm_get_display_clock_speed;
15686         else if (IS_I865G(dev_priv))
15687                 dev_priv->display.get_display_clock_speed =
15688                         i865_get_display_clock_speed;
15689         else if (IS_I85X(dev_priv))
15690                 dev_priv->display.get_display_clock_speed =
15691                         i85x_get_display_clock_speed;
15692         else { /* 830 */
15693                 WARN(!IS_I830(dev_priv), "Unknown platform. Assuming 133 MHz CDCLK\n");
15694                 dev_priv->display.get_display_clock_speed =
15695                         i830_get_display_clock_speed;
15696         }
15697
15698         if (IS_GEN5(dev_priv)) {
15699                 dev_priv->display.fdi_link_train = ironlake_fdi_link_train;
15700         } else if (IS_GEN6(dev_priv)) {
15701                 dev_priv->display.fdi_link_train = gen6_fdi_link_train;
15702         } else if (IS_IVYBRIDGE(dev_priv)) {
15703                 /* FIXME: detect B0+ stepping and use auto training */
15704                 dev_priv->display.fdi_link_train = ivb_manual_fdi_link_train;
15705         } else if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv)) {
15706                 dev_priv->display.fdi_link_train = hsw_fdi_link_train;
15707         }
15708
15709         if (IS_BROADWELL(dev_priv)) {
15710                 dev_priv->display.modeset_commit_cdclk =
15711                         broadwell_modeset_commit_cdclk;
15712                 dev_priv->display.modeset_calc_cdclk =
15713                         broadwell_modeset_calc_cdclk;
15714         } else if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv)) {
15715                 dev_priv->display.modeset_commit_cdclk =
15716                         valleyview_modeset_commit_cdclk;
15717                 dev_priv->display.modeset_calc_cdclk =
15718                         valleyview_modeset_calc_cdclk;
15719         } else if (IS_BROXTON(dev_priv)) {
15720                 dev_priv->display.modeset_commit_cdclk =
15721                         bxt_modeset_commit_cdclk;
15722                 dev_priv->display.modeset_calc_cdclk =
15723                         bxt_modeset_calc_cdclk;
15724         } else if (IS_SKYLAKE(dev_priv) || IS_KABYLAKE(dev_priv)) {
15725                 dev_priv->display.modeset_commit_cdclk =
15726                         skl_modeset_commit_cdclk;
15727                 dev_priv->display.modeset_calc_cdclk =
15728                         skl_modeset_calc_cdclk;
15729         }
15730
15731         switch (INTEL_INFO(dev_priv)->gen) {
15732         case 2:
15733                 dev_priv->display.queue_flip = intel_gen2_queue_flip;
15734                 break;
15735
15736         case 3:
15737                 dev_priv->display.queue_flip = intel_gen3_queue_flip;
15738                 break;
15739
15740         case 4:
15741         case 5:
15742                 dev_priv->display.queue_flip = intel_gen4_queue_flip;
15743                 break;
15744
15745         case 6:
15746                 dev_priv->display.queue_flip = intel_gen6_queue_flip;
15747                 break;
15748         case 7:
15749         case 8: /* FIXME(BDW): Check that the gen8 RCS flip works. */
15750                 dev_priv->display.queue_flip = intel_gen7_queue_flip;
15751                 break;
15752         case 9:
15753                 /* Drop through - unsupported since execlist only. */
15754         default:
15755                 /* Default just returns -ENODEV to indicate unsupported */
15756                 dev_priv->display.queue_flip = intel_default_queue_flip;
15757         }
15758 }
15759
15760 /*
15761  * Some BIOSes insist on assuming the GPU's pipe A is enabled at suspend,
15762  * resume, or other times.  This quirk makes sure that's the case for
15763  * affected systems.
15764  */
15765 static void quirk_pipea_force(struct drm_device *dev)
15766 {
15767         struct drm_i915_private *dev_priv = to_i915(dev);
15768
15769         dev_priv->quirks |= QUIRK_PIPEA_FORCE;
15770         DRM_INFO("applying pipe a force quirk\n");
15771 }
15772
15773 static void quirk_pipeb_force(struct drm_device *dev)
15774 {
15775         struct drm_i915_private *dev_priv = to_i915(dev);
15776
15777         dev_priv->quirks |= QUIRK_PIPEB_FORCE;
15778         DRM_INFO("applying pipe b force quirk\n");
15779 }
15780
15781 /*
15782  * Some machines (Lenovo U160) do not work with SSC on LVDS for some reason
15783  */
15784 static void quirk_ssc_force_disable(struct drm_device *dev)
15785 {
15786         struct drm_i915_private *dev_priv = to_i915(dev);
15787         dev_priv->quirks |= QUIRK_LVDS_SSC_DISABLE;
15788         DRM_INFO("applying lvds SSC disable quirk\n");
15789 }
15790
15791 /*
15792  * A machine (e.g. Acer Aspire 5734Z) may need to invert the panel backlight
15793  * brightness value
15794  */
15795 static void quirk_invert_brightness(struct drm_device *dev)
15796 {
15797         struct drm_i915_private *dev_priv = to_i915(dev);
15798         dev_priv->quirks |= QUIRK_INVERT_BRIGHTNESS;
15799         DRM_INFO("applying inverted panel brightness quirk\n");
15800 }
15801
15802 /* Some VBT's incorrectly indicate no backlight is present */
15803 static void quirk_backlight_present(struct drm_device *dev)
15804 {
15805         struct drm_i915_private *dev_priv = to_i915(dev);
15806         dev_priv->quirks |= QUIRK_BACKLIGHT_PRESENT;
15807         DRM_INFO("applying backlight present quirk\n");
15808 }
15809
15810 struct intel_quirk {
15811         int device;
15812         int subsystem_vendor;
15813         int subsystem_device;
15814         void (*hook)(struct drm_device *dev);
15815 };
15816
15817 /* For systems that don't have a meaningful PCI subdevice/subvendor ID */
15818 struct intel_dmi_quirk {
15819         void (*hook)(struct drm_device *dev);
15820         const struct dmi_system_id (*dmi_id_list)[];
15821 };
15822
15823 static int intel_dmi_reverse_brightness(const struct dmi_system_id *id)
15824 {
15825         DRM_INFO("Backlight polarity reversed on %s\n", id->ident);
15826         return 1;
15827 }
15828
15829 static const struct intel_dmi_quirk intel_dmi_quirks[] = {
15830         {
15831                 .dmi_id_list = &(const struct dmi_system_id[]) {
15832                         {
15833                                 .callback = intel_dmi_reverse_brightness,
15834                                 .ident = "NCR Corporation",
15835                                 .matches = {DMI_MATCH(DMI_SYS_VENDOR, "NCR Corporation"),
15836                                             DMI_MATCH(DMI_PRODUCT_NAME, ""),
15837                                 },
15838                         },
15839                         { }  /* terminating entry */
15840                 },
15841                 .hook = quirk_invert_brightness,
15842         },
15843 };
15844
15845 static struct intel_quirk intel_quirks[] = {
15846         /* Toshiba Protege R-205, S-209 needs pipe A force quirk */
15847         { 0x2592, 0x1179, 0x0001, quirk_pipea_force },
15848
15849         /* ThinkPad T60 needs pipe A force quirk (bug #16494) */
15850         { 0x2782, 0x17aa, 0x201a, quirk_pipea_force },
15851
15852         /* 830 needs to leave pipe A & dpll A up */
15853         { 0x3577, PCI_ANY_ID, PCI_ANY_ID, quirk_pipea_force },
15854
15855         /* 830 needs to leave pipe B & dpll B up */
15856         { 0x3577, PCI_ANY_ID, PCI_ANY_ID, quirk_pipeb_force },
15857
15858         /* Lenovo U160 cannot use SSC on LVDS */
15859         { 0x0046, 0x17aa, 0x3920, quirk_ssc_force_disable },
15860
15861         /* Sony Vaio Y cannot use SSC on LVDS */
15862         { 0x0046, 0x104d, 0x9076, quirk_ssc_force_disable },
15863
15864         /* Acer Aspire 5734Z must invert backlight brightness */
15865         { 0x2a42, 0x1025, 0x0459, quirk_invert_brightness },
15866
15867         /* Acer/eMachines G725 */
15868         { 0x2a42, 0x1025, 0x0210, quirk_invert_brightness },
15869
15870         /* Acer/eMachines e725 */
15871         { 0x2a42, 0x1025, 0x0212, quirk_invert_brightness },
15872
15873         /* Acer/Packard Bell NCL20 */
15874         { 0x2a42, 0x1025, 0x034b, quirk_invert_brightness },
15875
15876         /* Acer Aspire 4736Z */
15877         { 0x2a42, 0x1025, 0x0260, quirk_invert_brightness },
15878
15879         /* Acer Aspire 5336 */
15880         { 0x2a42, 0x1025, 0x048a, quirk_invert_brightness },
15881
15882         /* Acer C720 and C720P Chromebooks (Celeron 2955U) have backlights */
15883         { 0x0a06, 0x1025, 0x0a11, quirk_backlight_present },
15884
15885         /* Acer C720 Chromebook (Core i3 4005U) */
15886         { 0x0a16, 0x1025, 0x0a11, quirk_backlight_present },
15887
15888         /* Apple Macbook 2,1 (Core 2 T7400) */
15889         { 0x27a2, 0x8086, 0x7270, quirk_backlight_present },
15890
15891         /* Apple Macbook 4,1 */
15892         { 0x2a02, 0x106b, 0x00a1, quirk_backlight_present },
15893
15894         /* Toshiba CB35 Chromebook (Celeron 2955U) */
15895         { 0x0a06, 0x1179, 0x0a88, quirk_backlight_present },
15896
15897         /* HP Chromebook 14 (Celeron 2955U) */
15898         { 0x0a06, 0x103c, 0x21ed, quirk_backlight_present },
15899
15900         /* Dell Chromebook 11 */
15901         { 0x0a06, 0x1028, 0x0a35, quirk_backlight_present },
15902
15903         /* Dell Chromebook 11 (2015 version) */
15904         { 0x0a16, 0x1028, 0x0a35, quirk_backlight_present },
15905 };
15906
15907 static void intel_init_quirks(struct drm_device *dev)
15908 {
15909         struct pci_dev *d = dev->pdev;
15910         int i;
15911
15912         for (i = 0; i < ARRAY_SIZE(intel_quirks); i++) {
15913                 struct intel_quirk *q = &intel_quirks[i];
15914
15915                 if (d->device == q->device &&
15916                     (d->subsystem_vendor == q->subsystem_vendor ||
15917                      q->subsystem_vendor == PCI_ANY_ID) &&
15918                     (d->subsystem_device == q->subsystem_device ||
15919                      q->subsystem_device == PCI_ANY_ID))
15920                         q->hook(dev);
15921         }
15922         for (i = 0; i < ARRAY_SIZE(intel_dmi_quirks); i++) {
15923                 if (dmi_check_system(*intel_dmi_quirks[i].dmi_id_list) != 0)
15924                         intel_dmi_quirks[i].hook(dev);
15925         }
15926 }
15927
15928 /* Disable the VGA plane that we never use */
15929 static void i915_disable_vga(struct drm_device *dev)
15930 {
15931         struct drm_i915_private *dev_priv = to_i915(dev);
15932         u8 sr1;
15933         i915_reg_t vga_reg = i915_vgacntrl_reg(dev);
15934
15935         /* WaEnableVGAAccessThroughIOPort:ctg,elk,ilk,snb,ivb,vlv,hsw */
15936         vga_get_uninterruptible(dev->pdev, VGA_RSRC_LEGACY_IO);
15937         outb(SR01, VGA_SR_INDEX);
15938         sr1 = inb(VGA_SR_DATA);
15939         outb(sr1 | 1<<5, VGA_SR_DATA);
15940         vga_put(dev->pdev, VGA_RSRC_LEGACY_IO);
15941         udelay(300);
15942
15943         I915_WRITE(vga_reg, VGA_DISP_DISABLE);
15944         POSTING_READ(vga_reg);
15945 }
15946
15947 void intel_modeset_init_hw(struct drm_device *dev)
15948 {
15949         struct drm_i915_private *dev_priv = to_i915(dev);
15950
15951         intel_update_cdclk(dev);
15952
15953         dev_priv->atomic_cdclk_freq = dev_priv->cdclk_freq;
15954
15955         intel_init_clock_gating(dev);
15956 }
15957
15958 /*
15959  * Calculate what we think the watermarks should be for the state we've read
15960  * out of the hardware and then immediately program those watermarks so that
15961  * we ensure the hardware settings match our internal state.
15962  *
15963  * We can calculate what we think WM's should be by creating a duplicate of the
15964  * current state (which was constructed during hardware readout) and running it
15965  * through the atomic check code to calculate new watermark values in the
15966  * state object.
15967  */
15968 static void sanitize_watermarks(struct drm_device *dev)
15969 {
15970         struct drm_i915_private *dev_priv = to_i915(dev);
15971         struct drm_atomic_state *state;
15972         struct drm_crtc *crtc;
15973         struct drm_crtc_state *cstate;
15974         struct drm_modeset_acquire_ctx ctx;
15975         int ret;
15976         int i;
15977
15978         /* Only supported on platforms that use atomic watermark design */
15979         if (!dev_priv->display.optimize_watermarks)
15980                 return;
15981
15982         /*
15983          * We need to hold connection_mutex before calling duplicate_state so
15984          * that the connector loop is protected.
15985          */
15986         drm_modeset_acquire_init(&ctx, 0);
15987 retry:
15988         ret = drm_modeset_lock_all_ctx(dev, &ctx);
15989         if (ret == -EDEADLK) {
15990                 drm_modeset_backoff(&ctx);
15991                 goto retry;
15992         } else if (WARN_ON(ret)) {
15993                 goto fail;
15994         }
15995
15996         state = drm_atomic_helper_duplicate_state(dev, &ctx);
15997         if (WARN_ON(IS_ERR(state)))
15998                 goto fail;
15999
16000         /*
16001          * Hardware readout is the only time we don't want to calculate
16002          * intermediate watermarks (since we don't trust the current
16003          * watermarks).
16004          */
16005         to_intel_atomic_state(state)->skip_intermediate_wm = true;
16006
16007         ret = intel_atomic_check(dev, state);
16008         if (ret) {
16009                 /*
16010                  * If we fail here, it means that the hardware appears to be
16011                  * programmed in a way that shouldn't be possible, given our
16012                  * understanding of watermark requirements.  This might mean a
16013                  * mistake in the hardware readout code or a mistake in the
16014                  * watermark calculations for a given platform.  Raise a WARN
16015                  * so that this is noticeable.
16016                  *
16017                  * If this actually happens, we'll have to just leave the
16018                  * BIOS-programmed watermarks untouched and hope for the best.
16019                  */
16020                 WARN(true, "Could not determine valid watermarks for inherited state\n");
16021                 goto fail;
16022         }
16023
16024         /* Write calculated watermark values back */
16025         for_each_crtc_in_state(state, crtc, cstate, i) {
16026                 struct intel_crtc_state *cs = to_intel_crtc_state(cstate);
16027
16028                 cs->wm.need_postvbl_update = true;
16029                 dev_priv->display.optimize_watermarks(cs);
16030         }
16031
16032         drm_atomic_state_free(state);
16033 fail:
16034         drm_modeset_drop_locks(&ctx);
16035         drm_modeset_acquire_fini(&ctx);
16036 }
16037
16038 void intel_modeset_init(struct drm_device *dev)
16039 {
16040         struct drm_i915_private *dev_priv = to_i915(dev);
16041         struct i915_ggtt *ggtt = &dev_priv->ggtt;
16042         int sprite, ret;
16043         enum pipe pipe;
16044         struct intel_crtc *crtc;
16045
16046         drm_mode_config_init(dev);
16047
16048         dev->mode_config.min_width = 0;
16049         dev->mode_config.min_height = 0;
16050
16051         dev->mode_config.preferred_depth = 24;
16052         dev->mode_config.prefer_shadow = 1;
16053
16054         dev->mode_config.allow_fb_modifiers = true;
16055
16056         dev->mode_config.funcs = &intel_mode_funcs;
16057
16058         intel_init_quirks(dev);
16059
16060         intel_init_pm(dev);
16061
16062         if (INTEL_INFO(dev)->num_pipes == 0)
16063                 return;
16064
16065         /*
16066          * There may be no VBT; and if the BIOS enabled SSC we can
16067          * just keep using it to avoid unnecessary flicker.  Whereas if the
16068          * BIOS isn't using it, don't assume it will work even if the VBT
16069          * indicates as much.
16070          */
16071         if (HAS_PCH_IBX(dev) || HAS_PCH_CPT(dev)) {
16072                 bool bios_lvds_use_ssc = !!(I915_READ(PCH_DREF_CONTROL) &
16073                                             DREF_SSC1_ENABLE);
16074
16075                 if (dev_priv->vbt.lvds_use_ssc != bios_lvds_use_ssc) {
16076                         DRM_DEBUG_KMS("SSC %sabled by BIOS, overriding VBT which says %sabled\n",
16077                                      bios_lvds_use_ssc ? "en" : "dis",
16078                                      dev_priv->vbt.lvds_use_ssc ? "en" : "dis");
16079                         dev_priv->vbt.lvds_use_ssc = bios_lvds_use_ssc;
16080                 }
16081         }
16082
16083         if (IS_GEN2(dev)) {
16084                 dev->mode_config.max_width = 2048;
16085                 dev->mode_config.max_height = 2048;
16086         } else if (IS_GEN3(dev)) {
16087                 dev->mode_config.max_width = 4096;
16088                 dev->mode_config.max_height = 4096;
16089         } else {
16090                 dev->mode_config.max_width = 8192;
16091                 dev->mode_config.max_height = 8192;
16092         }
16093
16094         if (IS_845G(dev) || IS_I865G(dev)) {
16095                 dev->mode_config.cursor_width = IS_845G(dev) ? 64 : 512;
16096                 dev->mode_config.cursor_height = 1023;
16097         } else if (IS_GEN2(dev)) {
16098                 dev->mode_config.cursor_width = GEN2_CURSOR_WIDTH;
16099                 dev->mode_config.cursor_height = GEN2_CURSOR_HEIGHT;
16100         } else {
16101                 dev->mode_config.cursor_width = MAX_CURSOR_WIDTH;
16102                 dev->mode_config.cursor_height = MAX_CURSOR_HEIGHT;
16103         }
16104
16105         dev->mode_config.fb_base = ggtt->mappable_base;
16106
16107         DRM_DEBUG_KMS("%d display pipe%s available.\n",
16108                       INTEL_INFO(dev)->num_pipes,
16109                       INTEL_INFO(dev)->num_pipes > 1 ? "s" : "");
16110
16111         for_each_pipe(dev_priv, pipe) {
16112                 intel_crtc_init(dev, pipe);
16113                 for_each_sprite(dev_priv, pipe, sprite) {
16114                         ret = intel_plane_init(dev, pipe, sprite);
16115                         if (ret)
16116                                 DRM_DEBUG_KMS("pipe %c sprite %c init failed: %d\n",
16117                                               pipe_name(pipe), sprite_name(pipe, sprite), ret);
16118                 }
16119         }
16120
16121         intel_update_czclk(dev_priv);
16122         intel_update_cdclk(dev);
16123
16124         intel_shared_dpll_init(dev);
16125
16126         if (dev_priv->max_cdclk_freq == 0)
16127                 intel_update_max_cdclk(dev);
16128
16129         /* Just disable it once at startup */
16130         i915_disable_vga(dev);
16131         intel_setup_outputs(dev);
16132
16133         drm_modeset_lock_all(dev);
16134         intel_modeset_setup_hw_state(dev);
16135         drm_modeset_unlock_all(dev);
16136
16137         for_each_intel_crtc(dev, crtc) {
16138                 struct intel_initial_plane_config plane_config = {};
16139
16140                 if (!crtc->active)
16141                         continue;
16142
16143                 /*
16144                  * Note that reserving the BIOS fb up front prevents us
16145                  * from stuffing other stolen allocations like the ring
16146                  * on top.  This prevents some ugliness at boot time, and
16147                  * can even allow for smooth boot transitions if the BIOS
16148                  * fb is large enough for the active pipe configuration.
16149                  */
16150                 dev_priv->display.get_initial_plane_config(crtc,
16151                                                            &plane_config);
16152
16153                 /*
16154                  * If the fb is shared between multiple heads, we'll
16155                  * just get the first one.
16156                  */
16157                 intel_find_initial_plane_obj(crtc, &plane_config);
16158         }
16159
16160         /*
16161          * Make sure hardware watermarks really match the state we read out.
16162          * Note that we need to do this after reconstructing the BIOS fb's
16163          * since the watermark calculation done here will use pstate->fb.
16164          */
16165         sanitize_watermarks(dev);
16166 }
16167
16168 static void intel_enable_pipe_a(struct drm_device *dev)
16169 {
16170         struct intel_connector *connector;
16171         struct drm_connector *crt = NULL;
16172         struct intel_load_detect_pipe load_detect_temp;
16173         struct drm_modeset_acquire_ctx *ctx = dev->mode_config.acquire_ctx;
16174
16175         /* We can't just switch on the pipe A, we need to set things up with a
16176          * proper mode and output configuration. As a gross hack, enable pipe A
16177          * by enabling the load detect pipe once. */
16178         for_each_intel_connector(dev, connector) {
16179                 if (connector->encoder->type == INTEL_OUTPUT_ANALOG) {
16180                         crt = &connector->base;
16181                         break;
16182                 }
16183         }
16184
16185         if (!crt)
16186                 return;
16187
16188         if (intel_get_load_detect_pipe(crt, NULL, &load_detect_temp, ctx))
16189                 intel_release_load_detect_pipe(crt, &load_detect_temp, ctx);
16190 }
16191
16192 static bool
16193 intel_check_plane_mapping(struct intel_crtc *crtc)
16194 {
16195         struct drm_device *dev = crtc->base.dev;
16196         struct drm_i915_private *dev_priv = to_i915(dev);
16197         u32 val;
16198
16199         if (INTEL_INFO(dev)->num_pipes == 1)
16200                 return true;
16201
16202         val = I915_READ(DSPCNTR(!crtc->plane));
16203
16204         if ((val & DISPLAY_PLANE_ENABLE) &&
16205             (!!(val & DISPPLANE_SEL_PIPE_MASK) == crtc->pipe))
16206                 return false;
16207
16208         return true;
16209 }
16210
16211 static bool intel_crtc_has_encoders(struct intel_crtc *crtc)
16212 {
16213         struct drm_device *dev = crtc->base.dev;
16214         struct intel_encoder *encoder;
16215
16216         for_each_encoder_on_crtc(dev, &crtc->base, encoder)
16217                 return true;
16218
16219         return false;
16220 }
16221
16222 static bool intel_encoder_has_connectors(struct intel_encoder *encoder)
16223 {
16224         struct drm_device *dev = encoder->base.dev;
16225         struct intel_connector *connector;
16226
16227         for_each_connector_on_encoder(dev, &encoder->base, connector)
16228                 return true;
16229
16230         return false;
16231 }
16232
16233 static bool has_pch_trancoder(struct drm_i915_private *dev_priv,
16234                               enum transcoder pch_transcoder)
16235 {
16236         return HAS_PCH_IBX(dev_priv) || HAS_PCH_CPT(dev_priv) ||
16237                 (HAS_PCH_LPT_H(dev_priv) && pch_transcoder == TRANSCODER_A);
16238 }
16239
16240 static void intel_sanitize_crtc(struct intel_crtc *crtc)
16241 {
16242         struct drm_device *dev = crtc->base.dev;
16243         struct drm_i915_private *dev_priv = to_i915(dev);
16244         enum transcoder cpu_transcoder = crtc->config->cpu_transcoder;
16245
16246         /* Clear any frame start delays used for debugging left by the BIOS */
16247         if (!transcoder_is_dsi(cpu_transcoder)) {
16248                 i915_reg_t reg = PIPECONF(cpu_transcoder);
16249
16250                 I915_WRITE(reg,
16251                            I915_READ(reg) & ~PIPECONF_FRAME_START_DELAY_MASK);
16252         }
16253
16254         /* restore vblank interrupts to correct state */
16255         drm_crtc_vblank_reset(&crtc->base);
16256         if (crtc->active) {
16257                 struct intel_plane *plane;
16258
16259                 drm_crtc_vblank_on(&crtc->base);
16260
16261                 /* Disable everything but the primary plane */
16262                 for_each_intel_plane_on_crtc(dev, crtc, plane) {
16263                         if (plane->base.type == DRM_PLANE_TYPE_PRIMARY)
16264                                 continue;
16265
16266                         plane->disable_plane(&plane->base, &crtc->base);
16267                 }
16268         }
16269
16270         /* We need to sanitize the plane -> pipe mapping first because this will
16271          * disable the crtc (and hence change the state) if it is wrong. Note
16272          * that gen4+ has a fixed plane -> pipe mapping.  */
16273         if (INTEL_INFO(dev)->gen < 4 && !intel_check_plane_mapping(crtc)) {
16274                 bool plane;
16275
16276                 DRM_DEBUG_KMS("[CRTC:%d:%s] wrong plane connection detected!\n",
16277                               crtc->base.base.id, crtc->base.name);
16278
16279                 /* Pipe has the wrong plane attached and the plane is active.
16280                  * Temporarily change the plane mapping and disable everything
16281                  * ...  */
16282                 plane = crtc->plane;
16283                 to_intel_plane_state(crtc->base.primary->state)->visible = true;
16284                 crtc->plane = !plane;
16285                 intel_crtc_disable_noatomic(&crtc->base);
16286                 crtc->plane = plane;
16287         }
16288
16289         if (dev_priv->quirks & QUIRK_PIPEA_FORCE &&
16290             crtc->pipe == PIPE_A && !crtc->active) {
16291                 /* BIOS forgot to enable pipe A, this mostly happens after
16292                  * resume. Force-enable the pipe to fix this, the update_dpms
16293                  * call below we restore the pipe to the right state, but leave
16294                  * the required bits on. */
16295                 intel_enable_pipe_a(dev);
16296         }
16297
16298         /* Adjust the state of the output pipe according to whether we
16299          * have active connectors/encoders. */
16300         if (crtc->active && !intel_crtc_has_encoders(crtc))
16301                 intel_crtc_disable_noatomic(&crtc->base);
16302
16303         if (crtc->active || HAS_GMCH_DISPLAY(dev)) {
16304                 /*
16305                  * We start out with underrun reporting disabled to avoid races.
16306                  * For correct bookkeeping mark this on active crtcs.
16307                  *
16308                  * Also on gmch platforms we dont have any hardware bits to
16309                  * disable the underrun reporting. Which means we need to start
16310                  * out with underrun reporting disabled also on inactive pipes,
16311                  * since otherwise we'll complain about the garbage we read when
16312                  * e.g. coming up after runtime pm.
16313                  *
16314                  * No protection against concurrent access is required - at
16315                  * worst a fifo underrun happens which also sets this to false.
16316                  */
16317                 crtc->cpu_fifo_underrun_disabled = true;
16318                 /*
16319                  * We track the PCH trancoder underrun reporting state
16320                  * within the crtc. With crtc for pipe A housing the underrun
16321                  * reporting state for PCH transcoder A, crtc for pipe B housing
16322                  * it for PCH transcoder B, etc. LPT-H has only PCH transcoder A,
16323                  * and marking underrun reporting as disabled for the non-existing
16324                  * PCH transcoders B and C would prevent enabling the south
16325                  * error interrupt (see cpt_can_enable_serr_int()).
16326                  */
16327                 if (has_pch_trancoder(dev_priv, (enum transcoder)crtc->pipe))
16328                         crtc->pch_fifo_underrun_disabled = true;
16329         }
16330 }
16331
16332 static void intel_sanitize_encoder(struct intel_encoder *encoder)
16333 {
16334         struct intel_connector *connector;
16335         struct drm_device *dev = encoder->base.dev;
16336
16337         /* We need to check both for a crtc link (meaning that the
16338          * encoder is active and trying to read from a pipe) and the
16339          * pipe itself being active. */
16340         bool has_active_crtc = encoder->base.crtc &&
16341                 to_intel_crtc(encoder->base.crtc)->active;
16342
16343         if (intel_encoder_has_connectors(encoder) && !has_active_crtc) {
16344                 DRM_DEBUG_KMS("[ENCODER:%d:%s] has active connectors but no active pipe!\n",
16345                               encoder->base.base.id,
16346                               encoder->base.name);
16347
16348                 /* Connector is active, but has no active pipe. This is
16349                  * fallout from our resume register restoring. Disable
16350                  * the encoder manually again. */
16351                 if (encoder->base.crtc) {
16352                         DRM_DEBUG_KMS("[ENCODER:%d:%s] manually disabled\n",
16353                                       encoder->base.base.id,
16354                                       encoder->base.name);
16355                         encoder->disable(encoder);
16356                         if (encoder->post_disable)
16357                                 encoder->post_disable(encoder);
16358                 }
16359                 encoder->base.crtc = NULL;
16360
16361                 /* Inconsistent output/port/pipe state happens presumably due to
16362                  * a bug in one of the get_hw_state functions. Or someplace else
16363                  * in our code, like the register restore mess on resume. Clamp
16364                  * things to off as a safer default. */
16365                 for_each_intel_connector(dev, connector) {
16366                         if (connector->encoder != encoder)
16367                                 continue;
16368                         connector->base.dpms = DRM_MODE_DPMS_OFF;
16369                         connector->base.encoder = NULL;
16370                 }
16371         }
16372         /* Enabled encoders without active connectors will be fixed in
16373          * the crtc fixup. */
16374 }
16375
16376 void i915_redisable_vga_power_on(struct drm_device *dev)
16377 {
16378         struct drm_i915_private *dev_priv = to_i915(dev);
16379         i915_reg_t vga_reg = i915_vgacntrl_reg(dev);
16380
16381         if (!(I915_READ(vga_reg) & VGA_DISP_DISABLE)) {
16382                 DRM_DEBUG_KMS("Something enabled VGA plane, disabling it\n");
16383                 i915_disable_vga(dev);
16384         }
16385 }
16386
16387 void i915_redisable_vga(struct drm_device *dev)
16388 {
16389         struct drm_i915_private *dev_priv = to_i915(dev);
16390
16391         /* This function can be called both from intel_modeset_setup_hw_state or
16392          * at a very early point in our resume sequence, where the power well
16393          * structures are not yet restored. Since this function is at a very
16394          * paranoid "someone might have enabled VGA while we were not looking"
16395          * level, just check if the power well is enabled instead of trying to
16396          * follow the "don't touch the power well if we don't need it" policy
16397          * the rest of the driver uses. */
16398         if (!intel_display_power_get_if_enabled(dev_priv, POWER_DOMAIN_VGA))
16399                 return;
16400
16401         i915_redisable_vga_power_on(dev);
16402
16403         intel_display_power_put(dev_priv, POWER_DOMAIN_VGA);
16404 }
16405
16406 static bool primary_get_hw_state(struct intel_plane *plane)
16407 {
16408         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
16409
16410         return I915_READ(DSPCNTR(plane->plane)) & DISPLAY_PLANE_ENABLE;
16411 }
16412
16413 /* FIXME read out full plane state for all planes */
16414 static void readout_plane_state(struct intel_crtc *crtc)
16415 {
16416         struct drm_plane *primary = crtc->base.primary;
16417         struct intel_plane_state *plane_state =
16418                 to_intel_plane_state(primary->state);
16419
16420         plane_state->visible = crtc->active &&
16421                 primary_get_hw_state(to_intel_plane(primary));
16422
16423         if (plane_state->visible)
16424                 crtc->base.state->plane_mask |= 1 << drm_plane_index(primary);
16425 }
16426
16427 static void intel_modeset_readout_hw_state(struct drm_device *dev)
16428 {
16429         struct drm_i915_private *dev_priv = to_i915(dev);
16430         enum pipe pipe;
16431         struct intel_crtc *crtc;
16432         struct intel_encoder *encoder;
16433         struct intel_connector *connector;
16434         int i;
16435
16436         dev_priv->active_crtcs = 0;
16437
16438         for_each_intel_crtc(dev, crtc) {
16439                 struct intel_crtc_state *crtc_state = crtc->config;
16440                 int pixclk = 0;
16441
16442                 __drm_atomic_helper_crtc_destroy_state(&crtc_state->base);
16443                 memset(crtc_state, 0, sizeof(*crtc_state));
16444                 crtc_state->base.crtc = &crtc->base;
16445
16446                 crtc_state->base.active = crtc_state->base.enable =
16447                         dev_priv->display.get_pipe_config(crtc, crtc_state);
16448
16449                 crtc->base.enabled = crtc_state->base.enable;
16450                 crtc->active = crtc_state->base.active;
16451
16452                 if (crtc_state->base.active) {
16453                         dev_priv->active_crtcs |= 1 << crtc->pipe;
16454
16455                         if (INTEL_GEN(dev_priv) >= 9 || IS_BROADWELL(dev_priv))
16456                                 pixclk = ilk_pipe_pixel_rate(crtc_state);
16457                         else if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
16458                                 pixclk = crtc_state->base.adjusted_mode.crtc_clock;
16459                         else
16460                                 WARN_ON(dev_priv->display.modeset_calc_cdclk);
16461
16462                         /* pixel rate mustn't exceed 95% of cdclk with IPS on BDW */
16463                         if (IS_BROADWELL(dev_priv) && crtc_state->ips_enabled)
16464                                 pixclk = DIV_ROUND_UP(pixclk * 100, 95);
16465                 }
16466
16467                 dev_priv->min_pixclk[crtc->pipe] = pixclk;
16468
16469                 readout_plane_state(crtc);
16470
16471                 DRM_DEBUG_KMS("[CRTC:%d:%s] hw state readout: %s\n",
16472                               crtc->base.base.id, crtc->base.name,
16473                               crtc->active ? "enabled" : "disabled");
16474         }
16475
16476         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
16477                 struct intel_shared_dpll *pll = &dev_priv->shared_dplls[i];
16478
16479                 pll->on = pll->funcs.get_hw_state(dev_priv, pll,
16480                                                   &pll->config.hw_state);
16481                 pll->config.crtc_mask = 0;
16482                 for_each_intel_crtc(dev, crtc) {
16483                         if (crtc->active && crtc->config->shared_dpll == pll)
16484                                 pll->config.crtc_mask |= 1 << crtc->pipe;
16485                 }
16486                 pll->active_mask = pll->config.crtc_mask;
16487
16488                 DRM_DEBUG_KMS("%s hw state readout: crtc_mask 0x%08x, on %i\n",
16489                               pll->name, pll->config.crtc_mask, pll->on);
16490         }
16491
16492         for_each_intel_encoder(dev, encoder) {
16493                 pipe = 0;
16494
16495                 if (encoder->get_hw_state(encoder, &pipe)) {
16496                         crtc = to_intel_crtc(dev_priv->pipe_to_crtc_mapping[pipe]);
16497                         encoder->base.crtc = &crtc->base;
16498                         crtc->config->output_types |= 1 << encoder->type;
16499                         encoder->get_config(encoder, crtc->config);
16500                 } else {
16501                         encoder->base.crtc = NULL;
16502                 }
16503
16504                 DRM_DEBUG_KMS("[ENCODER:%d:%s] hw state readout: %s, pipe %c\n",
16505                               encoder->base.base.id,
16506                               encoder->base.name,
16507                               encoder->base.crtc ? "enabled" : "disabled",
16508                               pipe_name(pipe));
16509         }
16510
16511         for_each_intel_connector(dev, connector) {
16512                 if (connector->get_hw_state(connector)) {
16513                         connector->base.dpms = DRM_MODE_DPMS_ON;
16514
16515                         encoder = connector->encoder;
16516                         connector->base.encoder = &encoder->base;
16517
16518                         if (encoder->base.crtc &&
16519                             encoder->base.crtc->state->active) {
16520                                 /*
16521                                  * This has to be done during hardware readout
16522                                  * because anything calling .crtc_disable may
16523                                  * rely on the connector_mask being accurate.
16524                                  */
16525                                 encoder->base.crtc->state->connector_mask |=
16526                                         1 << drm_connector_index(&connector->base);
16527                                 encoder->base.crtc->state->encoder_mask |=
16528                                         1 << drm_encoder_index(&encoder->base);
16529                         }
16530
16531                 } else {
16532                         connector->base.dpms = DRM_MODE_DPMS_OFF;
16533                         connector->base.encoder = NULL;
16534                 }
16535                 DRM_DEBUG_KMS("[CONNECTOR:%d:%s] hw state readout: %s\n",
16536                               connector->base.base.id,
16537                               connector->base.name,
16538                               connector->base.encoder ? "enabled" : "disabled");
16539         }
16540
16541         for_each_intel_crtc(dev, crtc) {
16542                 crtc->base.hwmode = crtc->config->base.adjusted_mode;
16543
16544                 memset(&crtc->base.mode, 0, sizeof(crtc->base.mode));
16545                 if (crtc->base.state->active) {
16546                         intel_mode_from_pipe_config(&crtc->base.mode, crtc->config);
16547                         intel_mode_from_pipe_config(&crtc->base.state->adjusted_mode, crtc->config);
16548                         WARN_ON(drm_atomic_set_mode_for_crtc(crtc->base.state, &crtc->base.mode));
16549
16550                         /*
16551                          * The initial mode needs to be set in order to keep
16552                          * the atomic core happy. It wants a valid mode if the
16553                          * crtc's enabled, so we do the above call.
16554                          *
16555                          * At this point some state updated by the connectors
16556                          * in their ->detect() callback has not run yet, so
16557                          * no recalculation can be done yet.
16558                          *
16559                          * Even if we could do a recalculation and modeset
16560                          * right now it would cause a double modeset if
16561                          * fbdev or userspace chooses a different initial mode.
16562                          *
16563                          * If that happens, someone indicated they wanted a
16564                          * mode change, which means it's safe to do a full
16565                          * recalculation.
16566                          */
16567                         crtc->base.state->mode.private_flags = I915_MODE_FLAG_INHERITED;
16568
16569                         drm_calc_timestamping_constants(&crtc->base, &crtc->base.hwmode);
16570                         update_scanline_offset(crtc);
16571                 }
16572
16573                 intel_pipe_config_sanity_check(dev_priv, crtc->config);
16574         }
16575 }
16576
16577 /* Scan out the current hw modeset state,
16578  * and sanitizes it to the current state
16579  */
16580 static void
16581 intel_modeset_setup_hw_state(struct drm_device *dev)
16582 {
16583         struct drm_i915_private *dev_priv = to_i915(dev);
16584         enum pipe pipe;
16585         struct intel_crtc *crtc;
16586         struct intel_encoder *encoder;
16587         int i;
16588
16589         intel_modeset_readout_hw_state(dev);
16590
16591         /* HW state is read out, now we need to sanitize this mess. */
16592         for_each_intel_encoder(dev, encoder) {
16593                 intel_sanitize_encoder(encoder);
16594         }
16595
16596         for_each_pipe(dev_priv, pipe) {
16597                 crtc = to_intel_crtc(dev_priv->pipe_to_crtc_mapping[pipe]);
16598                 intel_sanitize_crtc(crtc);
16599                 intel_dump_pipe_config(crtc, crtc->config,
16600                                        "[setup_hw_state]");
16601         }
16602
16603         intel_modeset_update_connector_atomic_state(dev);
16604
16605         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
16606                 struct intel_shared_dpll *pll = &dev_priv->shared_dplls[i];
16607
16608                 if (!pll->on || pll->active_mask)
16609                         continue;
16610
16611                 DRM_DEBUG_KMS("%s enabled but not in use, disabling\n", pll->name);
16612
16613                 pll->funcs.disable(dev_priv, pll);
16614                 pll->on = false;
16615         }
16616
16617         if (IS_VALLEYVIEW(dev) || IS_CHERRYVIEW(dev))
16618                 vlv_wm_get_hw_state(dev);
16619         else if (IS_GEN9(dev))
16620                 skl_wm_get_hw_state(dev);
16621         else if (HAS_PCH_SPLIT(dev))
16622                 ilk_wm_get_hw_state(dev);
16623
16624         for_each_intel_crtc(dev, crtc) {
16625                 unsigned long put_domains;
16626
16627                 put_domains = modeset_get_crtc_power_domains(&crtc->base, crtc->config);
16628                 if (WARN_ON(put_domains))
16629                         modeset_put_power_domains(dev_priv, put_domains);
16630         }
16631         intel_display_set_init_power(dev_priv, false);
16632
16633         intel_fbc_init_pipe_state(dev_priv);
16634 }
16635
16636 void intel_display_resume(struct drm_device *dev)
16637 {
16638         struct drm_i915_private *dev_priv = to_i915(dev);
16639         struct drm_atomic_state *state = dev_priv->modeset_restore_state;
16640         struct drm_modeset_acquire_ctx ctx;
16641         int ret;
16642
16643         dev_priv->modeset_restore_state = NULL;
16644         if (state)
16645                 state->acquire_ctx = &ctx;
16646
16647         /*
16648          * This is a cludge because with real atomic modeset mode_config.mutex
16649          * won't be taken. Unfortunately some probed state like
16650          * audio_codec_enable is still protected by mode_config.mutex, so lock
16651          * it here for now.
16652          */
16653         mutex_lock(&dev->mode_config.mutex);
16654         drm_modeset_acquire_init(&ctx, 0);
16655
16656         while (1) {
16657                 ret = drm_modeset_lock_all_ctx(dev, &ctx);
16658                 if (ret != -EDEADLK)
16659                         break;
16660
16661                 drm_modeset_backoff(&ctx);
16662         }
16663
16664         if (!ret)
16665                 ret = __intel_display_resume(dev, state);
16666
16667         drm_modeset_drop_locks(&ctx);
16668         drm_modeset_acquire_fini(&ctx);
16669         mutex_unlock(&dev->mode_config.mutex);
16670
16671         if (ret) {
16672                 DRM_ERROR("Restoring old state failed with %i\n", ret);
16673                 drm_atomic_state_free(state);
16674         }
16675 }
16676
16677 void intel_modeset_gem_init(struct drm_device *dev)
16678 {
16679         struct drm_i915_private *dev_priv = to_i915(dev);
16680         struct drm_crtc *c;
16681         struct drm_i915_gem_object *obj;
16682         int ret;
16683
16684         intel_init_gt_powersave(dev_priv);
16685
16686         intel_modeset_init_hw(dev);
16687
16688         intel_setup_overlay(dev_priv);
16689
16690         /*
16691          * Make sure any fbs we allocated at startup are properly
16692          * pinned & fenced.  When we do the allocation it's too early
16693          * for this.
16694          */
16695         for_each_crtc(dev, c) {
16696                 obj = intel_fb_obj(c->primary->fb);
16697                 if (obj == NULL)
16698                         continue;
16699
16700                 mutex_lock(&dev->struct_mutex);
16701                 ret = intel_pin_and_fence_fb_obj(c->primary->fb,
16702                                                  c->primary->state->rotation);
16703                 mutex_unlock(&dev->struct_mutex);
16704                 if (ret) {
16705                         DRM_ERROR("failed to pin boot fb on pipe %d\n",
16706                                   to_intel_crtc(c)->pipe);
16707                         drm_framebuffer_unreference(c->primary->fb);
16708                         c->primary->fb = NULL;
16709                         c->primary->crtc = c->primary->state->crtc = NULL;
16710                         update_state_fb(c->primary);
16711                         c->state->plane_mask &= ~(1 << drm_plane_index(c->primary));
16712                 }
16713         }
16714 }
16715
16716 int intel_connector_register(struct drm_connector *connector)
16717 {
16718         struct intel_connector *intel_connector = to_intel_connector(connector);
16719         int ret;
16720
16721         ret = intel_backlight_device_register(intel_connector);
16722         if (ret)
16723                 goto err;
16724
16725         return 0;
16726
16727 err:
16728         return ret;
16729 }
16730
16731 void intel_connector_unregister(struct drm_connector *connector)
16732 {
16733         struct intel_connector *intel_connector = to_intel_connector(connector);
16734
16735         intel_backlight_device_unregister(intel_connector);
16736         intel_panel_destroy_backlight(connector);
16737 }
16738
16739 void intel_modeset_cleanup(struct drm_device *dev)
16740 {
16741         struct drm_i915_private *dev_priv = to_i915(dev);
16742
16743         intel_disable_gt_powersave(dev_priv);
16744
16745         /*
16746          * Interrupts and polling as the first thing to avoid creating havoc.
16747          * Too much stuff here (turning of connectors, ...) would
16748          * experience fancy races otherwise.
16749          */
16750         intel_irq_uninstall(dev_priv);
16751
16752         /*
16753          * Due to the hpd irq storm handling the hotplug work can re-arm the
16754          * poll handlers. Hence disable polling after hpd handling is shut down.
16755          */
16756         drm_kms_helper_poll_fini(dev);
16757
16758         intel_unregister_dsm_handler();
16759
16760         intel_fbc_global_disable(dev_priv);
16761
16762         /* flush any delayed tasks or pending work */
16763         flush_scheduled_work();
16764
16765         drm_mode_config_cleanup(dev);
16766
16767         intel_cleanup_overlay(dev_priv);
16768
16769         intel_cleanup_gt_powersave(dev_priv);
16770
16771         intel_teardown_gmbus(dev);
16772 }
16773
16774 void intel_connector_attach_encoder(struct intel_connector *connector,
16775                                     struct intel_encoder *encoder)
16776 {
16777         connector->encoder = encoder;
16778         drm_mode_connector_attach_encoder(&connector->base,
16779                                           &encoder->base);
16780 }
16781
16782 /*
16783  * set vga decode state - true == enable VGA decode
16784  */
16785 int intel_modeset_vga_set_state(struct drm_device *dev, bool state)
16786 {
16787         struct drm_i915_private *dev_priv = to_i915(dev);
16788         unsigned reg = INTEL_INFO(dev)->gen >= 6 ? SNB_GMCH_CTRL : INTEL_GMCH_CTRL;
16789         u16 gmch_ctrl;
16790
16791         if (pci_read_config_word(dev_priv->bridge_dev, reg, &gmch_ctrl)) {
16792                 DRM_ERROR("failed to read control word\n");
16793                 return -EIO;
16794         }
16795
16796         if (!!(gmch_ctrl & INTEL_GMCH_VGA_DISABLE) == !state)
16797                 return 0;
16798
16799         if (state)
16800                 gmch_ctrl &= ~INTEL_GMCH_VGA_DISABLE;
16801         else
16802                 gmch_ctrl |= INTEL_GMCH_VGA_DISABLE;
16803
16804         if (pci_write_config_word(dev_priv->bridge_dev, reg, gmch_ctrl)) {
16805                 DRM_ERROR("failed to write control word\n");
16806                 return -EIO;
16807         }
16808
16809         return 0;
16810 }
16811
16812 struct intel_display_error_state {
16813
16814         u32 power_well_driver;
16815
16816         int num_transcoders;
16817
16818         struct intel_cursor_error_state {
16819                 u32 control;
16820                 u32 position;
16821                 u32 base;
16822                 u32 size;
16823         } cursor[I915_MAX_PIPES];
16824
16825         struct intel_pipe_error_state {
16826                 bool power_domain_on;
16827                 u32 source;
16828                 u32 stat;
16829         } pipe[I915_MAX_PIPES];
16830
16831         struct intel_plane_error_state {
16832                 u32 control;
16833                 u32 stride;
16834                 u32 size;
16835                 u32 pos;
16836                 u32 addr;
16837                 u32 surface;
16838                 u32 tile_offset;
16839         } plane[I915_MAX_PIPES];
16840
16841         struct intel_transcoder_error_state {
16842                 bool power_domain_on;
16843                 enum transcoder cpu_transcoder;
16844
16845                 u32 conf;
16846
16847                 u32 htotal;
16848                 u32 hblank;
16849                 u32 hsync;
16850                 u32 vtotal;
16851                 u32 vblank;
16852                 u32 vsync;
16853         } transcoder[4];
16854 };
16855
16856 struct intel_display_error_state *
16857 intel_display_capture_error_state(struct drm_i915_private *dev_priv)
16858 {
16859         struct intel_display_error_state *error;
16860         int transcoders[] = {
16861                 TRANSCODER_A,
16862                 TRANSCODER_B,
16863                 TRANSCODER_C,
16864                 TRANSCODER_EDP,
16865         };
16866         int i;
16867
16868         if (INTEL_INFO(dev_priv)->num_pipes == 0)
16869                 return NULL;
16870
16871         error = kzalloc(sizeof(*error), GFP_ATOMIC);
16872         if (error == NULL)
16873                 return NULL;
16874
16875         if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv))
16876                 error->power_well_driver = I915_READ(HSW_PWR_WELL_DRIVER);
16877
16878         for_each_pipe(dev_priv, i) {
16879                 error->pipe[i].power_domain_on =
16880                         __intel_display_power_is_enabled(dev_priv,
16881                                                          POWER_DOMAIN_PIPE(i));
16882                 if (!error->pipe[i].power_domain_on)
16883                         continue;
16884
16885                 error->cursor[i].control = I915_READ(CURCNTR(i));
16886                 error->cursor[i].position = I915_READ(CURPOS(i));
16887                 error->cursor[i].base = I915_READ(CURBASE(i));
16888
16889                 error->plane[i].control = I915_READ(DSPCNTR(i));
16890                 error->plane[i].stride = I915_READ(DSPSTRIDE(i));
16891                 if (INTEL_GEN(dev_priv) <= 3) {
16892                         error->plane[i].size = I915_READ(DSPSIZE(i));
16893                         error->plane[i].pos = I915_READ(DSPPOS(i));
16894                 }
16895                 if (INTEL_GEN(dev_priv) <= 7 && !IS_HASWELL(dev_priv))
16896                         error->plane[i].addr = I915_READ(DSPADDR(i));
16897                 if (INTEL_GEN(dev_priv) >= 4) {
16898                         error->plane[i].surface = I915_READ(DSPSURF(i));
16899                         error->plane[i].tile_offset = I915_READ(DSPTILEOFF(i));
16900                 }
16901
16902                 error->pipe[i].source = I915_READ(PIPESRC(i));
16903
16904                 if (HAS_GMCH_DISPLAY(dev_priv))
16905                         error->pipe[i].stat = I915_READ(PIPESTAT(i));
16906         }
16907
16908         /* Note: this does not include DSI transcoders. */
16909         error->num_transcoders = INTEL_INFO(dev_priv)->num_pipes;
16910         if (HAS_DDI(dev_priv))
16911                 error->num_transcoders++; /* Account for eDP. */
16912
16913         for (i = 0; i < error->num_transcoders; i++) {
16914                 enum transcoder cpu_transcoder = transcoders[i];
16915
16916                 error->transcoder[i].power_domain_on =
16917                         __intel_display_power_is_enabled(dev_priv,
16918                                 POWER_DOMAIN_TRANSCODER(cpu_transcoder));
16919                 if (!error->transcoder[i].power_domain_on)
16920                         continue;
16921
16922                 error->transcoder[i].cpu_transcoder = cpu_transcoder;
16923
16924                 error->transcoder[i].conf = I915_READ(PIPECONF(cpu_transcoder));
16925                 error->transcoder[i].htotal = I915_READ(HTOTAL(cpu_transcoder));
16926                 error->transcoder[i].hblank = I915_READ(HBLANK(cpu_transcoder));
16927                 error->transcoder[i].hsync = I915_READ(HSYNC(cpu_transcoder));
16928                 error->transcoder[i].vtotal = I915_READ(VTOTAL(cpu_transcoder));
16929                 error->transcoder[i].vblank = I915_READ(VBLANK(cpu_transcoder));
16930                 error->transcoder[i].vsync = I915_READ(VSYNC(cpu_transcoder));
16931         }
16932
16933         return error;
16934 }
16935
16936 #define err_printf(e, ...) i915_error_printf(e, __VA_ARGS__)
16937
16938 void
16939 intel_display_print_error_state(struct drm_i915_error_state_buf *m,
16940                                 struct drm_device *dev,
16941                                 struct intel_display_error_state *error)
16942 {
16943         struct drm_i915_private *dev_priv = to_i915(dev);
16944         int i;
16945
16946         if (!error)
16947                 return;
16948
16949         err_printf(m, "Num Pipes: %d\n", INTEL_INFO(dev)->num_pipes);
16950         if (IS_HASWELL(dev) || IS_BROADWELL(dev))
16951                 err_printf(m, "PWR_WELL_CTL2: %08x\n",
16952                            error->power_well_driver);
16953         for_each_pipe(dev_priv, i) {
16954                 err_printf(m, "Pipe [%d]:\n", i);
16955                 err_printf(m, "  Power: %s\n",
16956                            onoff(error->pipe[i].power_domain_on));
16957                 err_printf(m, "  SRC: %08x\n", error->pipe[i].source);
16958                 err_printf(m, "  STAT: %08x\n", error->pipe[i].stat);
16959
16960                 err_printf(m, "Plane [%d]:\n", i);
16961                 err_printf(m, "  CNTR: %08x\n", error->plane[i].control);
16962                 err_printf(m, "  STRIDE: %08x\n", error->plane[i].stride);
16963                 if (INTEL_INFO(dev)->gen <= 3) {
16964                         err_printf(m, "  SIZE: %08x\n", error->plane[i].size);
16965                         err_printf(m, "  POS: %08x\n", error->plane[i].pos);
16966                 }
16967                 if (INTEL_INFO(dev)->gen <= 7 && !IS_HASWELL(dev))
16968                         err_printf(m, "  ADDR: %08x\n", error->plane[i].addr);
16969                 if (INTEL_INFO(dev)->gen >= 4) {
16970                         err_printf(m, "  SURF: %08x\n", error->plane[i].surface);
16971                         err_printf(m, "  TILEOFF: %08x\n", error->plane[i].tile_offset);
16972                 }
16973
16974                 err_printf(m, "Cursor [%d]:\n", i);
16975                 err_printf(m, "  CNTR: %08x\n", error->cursor[i].control);
16976                 err_printf(m, "  POS: %08x\n", error->cursor[i].position);
16977                 err_printf(m, "  BASE: %08x\n", error->cursor[i].base);
16978         }
16979
16980         for (i = 0; i < error->num_transcoders; i++) {
16981                 err_printf(m, "CPU transcoder: %s\n",
16982                            transcoder_name(error->transcoder[i].cpu_transcoder));
16983                 err_printf(m, "  Power: %s\n",
16984                            onoff(error->transcoder[i].power_domain_on));
16985                 err_printf(m, "  CONF: %08x\n", error->transcoder[i].conf);
16986                 err_printf(m, "  HTOTAL: %08x\n", error->transcoder[i].htotal);
16987                 err_printf(m, "  HBLANK: %08x\n", error->transcoder[i].hblank);
16988                 err_printf(m, "  HSYNC: %08x\n", error->transcoder[i].hsync);
16989                 err_printf(m, "  VTOTAL: %08x\n", error->transcoder[i].vtotal);
16990                 err_printf(m, "  VBLANK: %08x\n", error->transcoder[i].vblank);
16991                 err_printf(m, "  VSYNC: %08x\n", error->transcoder[i].vsync);
16992         }
16993 }