Merge remote-tracking branches 'asoc/topic/es7134', 'asoc/topic/es8328', 'asoc/topic...
[sfrench/cifs-2.6.git] / drivers / gpu / drm / i915 / intel_display.c
1 /*
2  * Copyright © 2006-2007 Intel Corporation
3  *
4  * Permission is hereby granted, free of charge, to any person obtaining a
5  * copy of this software and associated documentation files (the "Software"),
6  * to deal in the Software without restriction, including without limitation
7  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
8  * and/or sell copies of the Software, and to permit persons to whom the
9  * Software is furnished to do so, subject to the following conditions:
10  *
11  * The above copyright notice and this permission notice (including the next
12  * paragraph) shall be included in all copies or substantial portions of the
13  * Software.
14  *
15  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
18  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
21  * DEALINGS IN THE SOFTWARE.
22  *
23  * Authors:
24  *      Eric Anholt <eric@anholt.net>
25  */
26
27 #include <linux/dmi.h>
28 #include <linux/module.h>
29 #include <linux/input.h>
30 #include <linux/i2c.h>
31 #include <linux/kernel.h>
32 #include <linux/slab.h>
33 #include <linux/vgaarb.h>
34 #include <drm/drm_edid.h>
35 #include <drm/drmP.h>
36 #include "intel_drv.h"
37 #include "intel_frontbuffer.h"
38 #include <drm/i915_drm.h>
39 #include "i915_drv.h"
40 #include "intel_dsi.h"
41 #include "i915_trace.h"
42 #include <drm/drm_atomic.h>
43 #include <drm/drm_atomic_helper.h>
44 #include <drm/drm_dp_helper.h>
45 #include <drm/drm_crtc_helper.h>
46 #include <drm/drm_plane_helper.h>
47 #include <drm/drm_rect.h>
48 #include <linux/dma_remapping.h>
49 #include <linux/reservation.h>
50
51 static bool is_mmio_work(struct intel_flip_work *work)
52 {
53         return work->mmio_work.func;
54 }
55
56 /* Primary plane formats for gen <= 3 */
57 static const uint32_t i8xx_primary_formats[] = {
58         DRM_FORMAT_C8,
59         DRM_FORMAT_RGB565,
60         DRM_FORMAT_XRGB1555,
61         DRM_FORMAT_XRGB8888,
62 };
63
64 /* Primary plane formats for gen >= 4 */
65 static const uint32_t i965_primary_formats[] = {
66         DRM_FORMAT_C8,
67         DRM_FORMAT_RGB565,
68         DRM_FORMAT_XRGB8888,
69         DRM_FORMAT_XBGR8888,
70         DRM_FORMAT_XRGB2101010,
71         DRM_FORMAT_XBGR2101010,
72 };
73
74 static const uint32_t skl_primary_formats[] = {
75         DRM_FORMAT_C8,
76         DRM_FORMAT_RGB565,
77         DRM_FORMAT_XRGB8888,
78         DRM_FORMAT_XBGR8888,
79         DRM_FORMAT_ARGB8888,
80         DRM_FORMAT_ABGR8888,
81         DRM_FORMAT_XRGB2101010,
82         DRM_FORMAT_XBGR2101010,
83         DRM_FORMAT_YUYV,
84         DRM_FORMAT_YVYU,
85         DRM_FORMAT_UYVY,
86         DRM_FORMAT_VYUY,
87 };
88
89 /* Cursor formats */
90 static const uint32_t intel_cursor_formats[] = {
91         DRM_FORMAT_ARGB8888,
92 };
93
94 static void i9xx_crtc_clock_get(struct intel_crtc *crtc,
95                                 struct intel_crtc_state *pipe_config);
96 static void ironlake_pch_clock_get(struct intel_crtc *crtc,
97                                    struct intel_crtc_state *pipe_config);
98
99 static int intel_framebuffer_init(struct drm_device *dev,
100                                   struct intel_framebuffer *ifb,
101                                   struct drm_mode_fb_cmd2 *mode_cmd,
102                                   struct drm_i915_gem_object *obj);
103 static void i9xx_set_pipeconf(struct intel_crtc *intel_crtc);
104 static void intel_set_pipe_timings(struct intel_crtc *intel_crtc);
105 static void intel_set_pipe_src_size(struct intel_crtc *intel_crtc);
106 static void intel_cpu_transcoder_set_m_n(struct intel_crtc *crtc,
107                                          struct intel_link_m_n *m_n,
108                                          struct intel_link_m_n *m2_n2);
109 static void ironlake_set_pipeconf(struct drm_crtc *crtc);
110 static void haswell_set_pipeconf(struct drm_crtc *crtc);
111 static void haswell_set_pipemisc(struct drm_crtc *crtc);
112 static void vlv_prepare_pll(struct intel_crtc *crtc,
113                             const struct intel_crtc_state *pipe_config);
114 static void chv_prepare_pll(struct intel_crtc *crtc,
115                             const struct intel_crtc_state *pipe_config);
116 static void intel_begin_crtc_commit(struct drm_crtc *, struct drm_crtc_state *);
117 static void intel_finish_crtc_commit(struct drm_crtc *, struct drm_crtc_state *);
118 static void intel_crtc_init_scalers(struct intel_crtc *crtc,
119                                     struct intel_crtc_state *crtc_state);
120 static void skylake_pfit_enable(struct intel_crtc *crtc);
121 static void ironlake_pfit_disable(struct intel_crtc *crtc, bool force);
122 static void ironlake_pfit_enable(struct intel_crtc *crtc);
123 static void intel_modeset_setup_hw_state(struct drm_device *dev);
124 static void intel_pre_disable_primary_noatomic(struct drm_crtc *crtc);
125 static int ilk_max_pixel_rate(struct drm_atomic_state *state);
126 static int glk_calc_cdclk(int max_pixclk);
127 static int bxt_calc_cdclk(int max_pixclk);
128
129 struct intel_limit {
130         struct {
131                 int min, max;
132         } dot, vco, n, m, m1, m2, p, p1;
133
134         struct {
135                 int dot_limit;
136                 int p2_slow, p2_fast;
137         } p2;
138 };
139
140 /* returns HPLL frequency in kHz */
141 static int valleyview_get_vco(struct drm_i915_private *dev_priv)
142 {
143         int hpll_freq, vco_freq[] = { 800, 1600, 2000, 2400 };
144
145         /* Obtain SKU information */
146         mutex_lock(&dev_priv->sb_lock);
147         hpll_freq = vlv_cck_read(dev_priv, CCK_FUSE_REG) &
148                 CCK_FUSE_HPLL_FREQ_MASK;
149         mutex_unlock(&dev_priv->sb_lock);
150
151         return vco_freq[hpll_freq] * 1000;
152 }
153
154 int vlv_get_cck_clock(struct drm_i915_private *dev_priv,
155                       const char *name, u32 reg, int ref_freq)
156 {
157         u32 val;
158         int divider;
159
160         mutex_lock(&dev_priv->sb_lock);
161         val = vlv_cck_read(dev_priv, reg);
162         mutex_unlock(&dev_priv->sb_lock);
163
164         divider = val & CCK_FREQUENCY_VALUES;
165
166         WARN((val & CCK_FREQUENCY_STATUS) !=
167              (divider << CCK_FREQUENCY_STATUS_SHIFT),
168              "%s change in progress\n", name);
169
170         return DIV_ROUND_CLOSEST(ref_freq << 1, divider + 1);
171 }
172
173 static int vlv_get_cck_clock_hpll(struct drm_i915_private *dev_priv,
174                                   const char *name, u32 reg)
175 {
176         if (dev_priv->hpll_freq == 0)
177                 dev_priv->hpll_freq = valleyview_get_vco(dev_priv);
178
179         return vlv_get_cck_clock(dev_priv, name, reg,
180                                  dev_priv->hpll_freq);
181 }
182
183 static int
184 intel_pch_rawclk(struct drm_i915_private *dev_priv)
185 {
186         return (I915_READ(PCH_RAWCLK_FREQ) & RAWCLK_FREQ_MASK) * 1000;
187 }
188
189 static int
190 intel_vlv_hrawclk(struct drm_i915_private *dev_priv)
191 {
192         /* RAWCLK_FREQ_VLV register updated from power well code */
193         return vlv_get_cck_clock_hpll(dev_priv, "hrawclk",
194                                       CCK_DISPLAY_REF_CLOCK_CONTROL);
195 }
196
197 static int
198 intel_g4x_hrawclk(struct drm_i915_private *dev_priv)
199 {
200         uint32_t clkcfg;
201
202         /* hrawclock is 1/4 the FSB frequency */
203         clkcfg = I915_READ(CLKCFG);
204         switch (clkcfg & CLKCFG_FSB_MASK) {
205         case CLKCFG_FSB_400:
206                 return 100000;
207         case CLKCFG_FSB_533:
208                 return 133333;
209         case CLKCFG_FSB_667:
210                 return 166667;
211         case CLKCFG_FSB_800:
212                 return 200000;
213         case CLKCFG_FSB_1067:
214                 return 266667;
215         case CLKCFG_FSB_1333:
216                 return 333333;
217         /* these two are just a guess; one of them might be right */
218         case CLKCFG_FSB_1600:
219         case CLKCFG_FSB_1600_ALT:
220                 return 400000;
221         default:
222                 return 133333;
223         }
224 }
225
226 void intel_update_rawclk(struct drm_i915_private *dev_priv)
227 {
228         if (HAS_PCH_SPLIT(dev_priv))
229                 dev_priv->rawclk_freq = intel_pch_rawclk(dev_priv);
230         else if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
231                 dev_priv->rawclk_freq = intel_vlv_hrawclk(dev_priv);
232         else if (IS_G4X(dev_priv) || IS_PINEVIEW(dev_priv))
233                 dev_priv->rawclk_freq = intel_g4x_hrawclk(dev_priv);
234         else
235                 return; /* no rawclk on other platforms, or no need to know it */
236
237         DRM_DEBUG_DRIVER("rawclk rate: %d kHz\n", dev_priv->rawclk_freq);
238 }
239
240 static void intel_update_czclk(struct drm_i915_private *dev_priv)
241 {
242         if (!(IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv)))
243                 return;
244
245         dev_priv->czclk_freq = vlv_get_cck_clock_hpll(dev_priv, "czclk",
246                                                       CCK_CZ_CLOCK_CONTROL);
247
248         DRM_DEBUG_DRIVER("CZ clock rate: %d kHz\n", dev_priv->czclk_freq);
249 }
250
251 static inline u32 /* units of 100MHz */
252 intel_fdi_link_freq(struct drm_i915_private *dev_priv,
253                     const struct intel_crtc_state *pipe_config)
254 {
255         if (HAS_DDI(dev_priv))
256                 return pipe_config->port_clock; /* SPLL */
257         else if (IS_GEN5(dev_priv))
258                 return ((I915_READ(FDI_PLL_BIOS_0) & FDI_PLL_FB_CLOCK_MASK) + 2) * 10000;
259         else
260                 return 270000;
261 }
262
263 static const struct intel_limit intel_limits_i8xx_dac = {
264         .dot = { .min = 25000, .max = 350000 },
265         .vco = { .min = 908000, .max = 1512000 },
266         .n = { .min = 2, .max = 16 },
267         .m = { .min = 96, .max = 140 },
268         .m1 = { .min = 18, .max = 26 },
269         .m2 = { .min = 6, .max = 16 },
270         .p = { .min = 4, .max = 128 },
271         .p1 = { .min = 2, .max = 33 },
272         .p2 = { .dot_limit = 165000,
273                 .p2_slow = 4, .p2_fast = 2 },
274 };
275
276 static const struct intel_limit intel_limits_i8xx_dvo = {
277         .dot = { .min = 25000, .max = 350000 },
278         .vco = { .min = 908000, .max = 1512000 },
279         .n = { .min = 2, .max = 16 },
280         .m = { .min = 96, .max = 140 },
281         .m1 = { .min = 18, .max = 26 },
282         .m2 = { .min = 6, .max = 16 },
283         .p = { .min = 4, .max = 128 },
284         .p1 = { .min = 2, .max = 33 },
285         .p2 = { .dot_limit = 165000,
286                 .p2_slow = 4, .p2_fast = 4 },
287 };
288
289 static const struct intel_limit intel_limits_i8xx_lvds = {
290         .dot = { .min = 25000, .max = 350000 },
291         .vco = { .min = 908000, .max = 1512000 },
292         .n = { .min = 2, .max = 16 },
293         .m = { .min = 96, .max = 140 },
294         .m1 = { .min = 18, .max = 26 },
295         .m2 = { .min = 6, .max = 16 },
296         .p = { .min = 4, .max = 128 },
297         .p1 = { .min = 1, .max = 6 },
298         .p2 = { .dot_limit = 165000,
299                 .p2_slow = 14, .p2_fast = 7 },
300 };
301
302 static const struct intel_limit intel_limits_i9xx_sdvo = {
303         .dot = { .min = 20000, .max = 400000 },
304         .vco = { .min = 1400000, .max = 2800000 },
305         .n = { .min = 1, .max = 6 },
306         .m = { .min = 70, .max = 120 },
307         .m1 = { .min = 8, .max = 18 },
308         .m2 = { .min = 3, .max = 7 },
309         .p = { .min = 5, .max = 80 },
310         .p1 = { .min = 1, .max = 8 },
311         .p2 = { .dot_limit = 200000,
312                 .p2_slow = 10, .p2_fast = 5 },
313 };
314
315 static const struct intel_limit intel_limits_i9xx_lvds = {
316         .dot = { .min = 20000, .max = 400000 },
317         .vco = { .min = 1400000, .max = 2800000 },
318         .n = { .min = 1, .max = 6 },
319         .m = { .min = 70, .max = 120 },
320         .m1 = { .min = 8, .max = 18 },
321         .m2 = { .min = 3, .max = 7 },
322         .p = { .min = 7, .max = 98 },
323         .p1 = { .min = 1, .max = 8 },
324         .p2 = { .dot_limit = 112000,
325                 .p2_slow = 14, .p2_fast = 7 },
326 };
327
328
329 static const struct intel_limit intel_limits_g4x_sdvo = {
330         .dot = { .min = 25000, .max = 270000 },
331         .vco = { .min = 1750000, .max = 3500000},
332         .n = { .min = 1, .max = 4 },
333         .m = { .min = 104, .max = 138 },
334         .m1 = { .min = 17, .max = 23 },
335         .m2 = { .min = 5, .max = 11 },
336         .p = { .min = 10, .max = 30 },
337         .p1 = { .min = 1, .max = 3},
338         .p2 = { .dot_limit = 270000,
339                 .p2_slow = 10,
340                 .p2_fast = 10
341         },
342 };
343
344 static const struct intel_limit intel_limits_g4x_hdmi = {
345         .dot = { .min = 22000, .max = 400000 },
346         .vco = { .min = 1750000, .max = 3500000},
347         .n = { .min = 1, .max = 4 },
348         .m = { .min = 104, .max = 138 },
349         .m1 = { .min = 16, .max = 23 },
350         .m2 = { .min = 5, .max = 11 },
351         .p = { .min = 5, .max = 80 },
352         .p1 = { .min = 1, .max = 8},
353         .p2 = { .dot_limit = 165000,
354                 .p2_slow = 10, .p2_fast = 5 },
355 };
356
357 static const struct intel_limit intel_limits_g4x_single_channel_lvds = {
358         .dot = { .min = 20000, .max = 115000 },
359         .vco = { .min = 1750000, .max = 3500000 },
360         .n = { .min = 1, .max = 3 },
361         .m = { .min = 104, .max = 138 },
362         .m1 = { .min = 17, .max = 23 },
363         .m2 = { .min = 5, .max = 11 },
364         .p = { .min = 28, .max = 112 },
365         .p1 = { .min = 2, .max = 8 },
366         .p2 = { .dot_limit = 0,
367                 .p2_slow = 14, .p2_fast = 14
368         },
369 };
370
371 static const struct intel_limit intel_limits_g4x_dual_channel_lvds = {
372         .dot = { .min = 80000, .max = 224000 },
373         .vco = { .min = 1750000, .max = 3500000 },
374         .n = { .min = 1, .max = 3 },
375         .m = { .min = 104, .max = 138 },
376         .m1 = { .min = 17, .max = 23 },
377         .m2 = { .min = 5, .max = 11 },
378         .p = { .min = 14, .max = 42 },
379         .p1 = { .min = 2, .max = 6 },
380         .p2 = { .dot_limit = 0,
381                 .p2_slow = 7, .p2_fast = 7
382         },
383 };
384
385 static const struct intel_limit intel_limits_pineview_sdvo = {
386         .dot = { .min = 20000, .max = 400000},
387         .vco = { .min = 1700000, .max = 3500000 },
388         /* Pineview's Ncounter is a ring counter */
389         .n = { .min = 3, .max = 6 },
390         .m = { .min = 2, .max = 256 },
391         /* Pineview only has one combined m divider, which we treat as m2. */
392         .m1 = { .min = 0, .max = 0 },
393         .m2 = { .min = 0, .max = 254 },
394         .p = { .min = 5, .max = 80 },
395         .p1 = { .min = 1, .max = 8 },
396         .p2 = { .dot_limit = 200000,
397                 .p2_slow = 10, .p2_fast = 5 },
398 };
399
400 static const struct intel_limit intel_limits_pineview_lvds = {
401         .dot = { .min = 20000, .max = 400000 },
402         .vco = { .min = 1700000, .max = 3500000 },
403         .n = { .min = 3, .max = 6 },
404         .m = { .min = 2, .max = 256 },
405         .m1 = { .min = 0, .max = 0 },
406         .m2 = { .min = 0, .max = 254 },
407         .p = { .min = 7, .max = 112 },
408         .p1 = { .min = 1, .max = 8 },
409         .p2 = { .dot_limit = 112000,
410                 .p2_slow = 14, .p2_fast = 14 },
411 };
412
413 /* Ironlake / Sandybridge
414  *
415  * We calculate clock using (register_value + 2) for N/M1/M2, so here
416  * the range value for them is (actual_value - 2).
417  */
418 static const struct intel_limit intel_limits_ironlake_dac = {
419         .dot = { .min = 25000, .max = 350000 },
420         .vco = { .min = 1760000, .max = 3510000 },
421         .n = { .min = 1, .max = 5 },
422         .m = { .min = 79, .max = 127 },
423         .m1 = { .min = 12, .max = 22 },
424         .m2 = { .min = 5, .max = 9 },
425         .p = { .min = 5, .max = 80 },
426         .p1 = { .min = 1, .max = 8 },
427         .p2 = { .dot_limit = 225000,
428                 .p2_slow = 10, .p2_fast = 5 },
429 };
430
431 static const struct intel_limit intel_limits_ironlake_single_lvds = {
432         .dot = { .min = 25000, .max = 350000 },
433         .vco = { .min = 1760000, .max = 3510000 },
434         .n = { .min = 1, .max = 3 },
435         .m = { .min = 79, .max = 118 },
436         .m1 = { .min = 12, .max = 22 },
437         .m2 = { .min = 5, .max = 9 },
438         .p = { .min = 28, .max = 112 },
439         .p1 = { .min = 2, .max = 8 },
440         .p2 = { .dot_limit = 225000,
441                 .p2_slow = 14, .p2_fast = 14 },
442 };
443
444 static const struct intel_limit intel_limits_ironlake_dual_lvds = {
445         .dot = { .min = 25000, .max = 350000 },
446         .vco = { .min = 1760000, .max = 3510000 },
447         .n = { .min = 1, .max = 3 },
448         .m = { .min = 79, .max = 127 },
449         .m1 = { .min = 12, .max = 22 },
450         .m2 = { .min = 5, .max = 9 },
451         .p = { .min = 14, .max = 56 },
452         .p1 = { .min = 2, .max = 8 },
453         .p2 = { .dot_limit = 225000,
454                 .p2_slow = 7, .p2_fast = 7 },
455 };
456
457 /* LVDS 100mhz refclk limits. */
458 static const struct intel_limit intel_limits_ironlake_single_lvds_100m = {
459         .dot = { .min = 25000, .max = 350000 },
460         .vco = { .min = 1760000, .max = 3510000 },
461         .n = { .min = 1, .max = 2 },
462         .m = { .min = 79, .max = 126 },
463         .m1 = { .min = 12, .max = 22 },
464         .m2 = { .min = 5, .max = 9 },
465         .p = { .min = 28, .max = 112 },
466         .p1 = { .min = 2, .max = 8 },
467         .p2 = { .dot_limit = 225000,
468                 .p2_slow = 14, .p2_fast = 14 },
469 };
470
471 static const struct intel_limit intel_limits_ironlake_dual_lvds_100m = {
472         .dot = { .min = 25000, .max = 350000 },
473         .vco = { .min = 1760000, .max = 3510000 },
474         .n = { .min = 1, .max = 3 },
475         .m = { .min = 79, .max = 126 },
476         .m1 = { .min = 12, .max = 22 },
477         .m2 = { .min = 5, .max = 9 },
478         .p = { .min = 14, .max = 42 },
479         .p1 = { .min = 2, .max = 6 },
480         .p2 = { .dot_limit = 225000,
481                 .p2_slow = 7, .p2_fast = 7 },
482 };
483
484 static const struct intel_limit intel_limits_vlv = {
485          /*
486           * These are the data rate limits (measured in fast clocks)
487           * since those are the strictest limits we have. The fast
488           * clock and actual rate limits are more relaxed, so checking
489           * them would make no difference.
490           */
491         .dot = { .min = 25000 * 5, .max = 270000 * 5 },
492         .vco = { .min = 4000000, .max = 6000000 },
493         .n = { .min = 1, .max = 7 },
494         .m1 = { .min = 2, .max = 3 },
495         .m2 = { .min = 11, .max = 156 },
496         .p1 = { .min = 2, .max = 3 },
497         .p2 = { .p2_slow = 2, .p2_fast = 20 }, /* slow=min, fast=max */
498 };
499
500 static const struct intel_limit intel_limits_chv = {
501         /*
502          * These are the data rate limits (measured in fast clocks)
503          * since those are the strictest limits we have.  The fast
504          * clock and actual rate limits are more relaxed, so checking
505          * them would make no difference.
506          */
507         .dot = { .min = 25000 * 5, .max = 540000 * 5},
508         .vco = { .min = 4800000, .max = 6480000 },
509         .n = { .min = 1, .max = 1 },
510         .m1 = { .min = 2, .max = 2 },
511         .m2 = { .min = 24 << 22, .max = 175 << 22 },
512         .p1 = { .min = 2, .max = 4 },
513         .p2 = { .p2_slow = 1, .p2_fast = 14 },
514 };
515
516 static const struct intel_limit intel_limits_bxt = {
517         /* FIXME: find real dot limits */
518         .dot = { .min = 0, .max = INT_MAX },
519         .vco = { .min = 4800000, .max = 6700000 },
520         .n = { .min = 1, .max = 1 },
521         .m1 = { .min = 2, .max = 2 },
522         /* FIXME: find real m2 limits */
523         .m2 = { .min = 2 << 22, .max = 255 << 22 },
524         .p1 = { .min = 2, .max = 4 },
525         .p2 = { .p2_slow = 1, .p2_fast = 20 },
526 };
527
528 static bool
529 needs_modeset(struct drm_crtc_state *state)
530 {
531         return drm_atomic_crtc_needs_modeset(state);
532 }
533
534 /*
535  * Platform specific helpers to calculate the port PLL loopback- (clock.m),
536  * and post-divider (clock.p) values, pre- (clock.vco) and post-divided fast
537  * (clock.dot) clock rates. This fast dot clock is fed to the port's IO logic.
538  * The helpers' return value is the rate of the clock that is fed to the
539  * display engine's pipe which can be the above fast dot clock rate or a
540  * divided-down version of it.
541  */
542 /* m1 is reserved as 0 in Pineview, n is a ring counter */
543 static int pnv_calc_dpll_params(int refclk, struct dpll *clock)
544 {
545         clock->m = clock->m2 + 2;
546         clock->p = clock->p1 * clock->p2;
547         if (WARN_ON(clock->n == 0 || clock->p == 0))
548                 return 0;
549         clock->vco = DIV_ROUND_CLOSEST(refclk * clock->m, clock->n);
550         clock->dot = DIV_ROUND_CLOSEST(clock->vco, clock->p);
551
552         return clock->dot;
553 }
554
555 static uint32_t i9xx_dpll_compute_m(struct dpll *dpll)
556 {
557         return 5 * (dpll->m1 + 2) + (dpll->m2 + 2);
558 }
559
560 static int i9xx_calc_dpll_params(int refclk, struct dpll *clock)
561 {
562         clock->m = i9xx_dpll_compute_m(clock);
563         clock->p = clock->p1 * clock->p2;
564         if (WARN_ON(clock->n + 2 == 0 || clock->p == 0))
565                 return 0;
566         clock->vco = DIV_ROUND_CLOSEST(refclk * clock->m, clock->n + 2);
567         clock->dot = DIV_ROUND_CLOSEST(clock->vco, clock->p);
568
569         return clock->dot;
570 }
571
572 static int vlv_calc_dpll_params(int refclk, struct dpll *clock)
573 {
574         clock->m = clock->m1 * clock->m2;
575         clock->p = clock->p1 * clock->p2;
576         if (WARN_ON(clock->n == 0 || clock->p == 0))
577                 return 0;
578         clock->vco = DIV_ROUND_CLOSEST(refclk * clock->m, clock->n);
579         clock->dot = DIV_ROUND_CLOSEST(clock->vco, clock->p);
580
581         return clock->dot / 5;
582 }
583
584 int chv_calc_dpll_params(int refclk, struct dpll *clock)
585 {
586         clock->m = clock->m1 * clock->m2;
587         clock->p = clock->p1 * clock->p2;
588         if (WARN_ON(clock->n == 0 || clock->p == 0))
589                 return 0;
590         clock->vco = DIV_ROUND_CLOSEST_ULL((uint64_t)refclk * clock->m,
591                         clock->n << 22);
592         clock->dot = DIV_ROUND_CLOSEST(clock->vco, clock->p);
593
594         return clock->dot / 5;
595 }
596
597 #define INTELPllInvalid(s)   do { /* DRM_DEBUG(s); */ return false; } while (0)
598 /**
599  * Returns whether the given set of divisors are valid for a given refclk with
600  * the given connectors.
601  */
602
603 static bool intel_PLL_is_valid(struct drm_i915_private *dev_priv,
604                                const struct intel_limit *limit,
605                                const struct dpll *clock)
606 {
607         if (clock->n   < limit->n.min   || limit->n.max   < clock->n)
608                 INTELPllInvalid("n out of range\n");
609         if (clock->p1  < limit->p1.min  || limit->p1.max  < clock->p1)
610                 INTELPllInvalid("p1 out of range\n");
611         if (clock->m2  < limit->m2.min  || limit->m2.max  < clock->m2)
612                 INTELPllInvalid("m2 out of range\n");
613         if (clock->m1  < limit->m1.min  || limit->m1.max  < clock->m1)
614                 INTELPllInvalid("m1 out of range\n");
615
616         if (!IS_PINEVIEW(dev_priv) && !IS_VALLEYVIEW(dev_priv) &&
617             !IS_CHERRYVIEW(dev_priv) && !IS_GEN9_LP(dev_priv))
618                 if (clock->m1 <= clock->m2)
619                         INTELPllInvalid("m1 <= m2\n");
620
621         if (!IS_VALLEYVIEW(dev_priv) && !IS_CHERRYVIEW(dev_priv) &&
622             !IS_GEN9_LP(dev_priv)) {
623                 if (clock->p < limit->p.min || limit->p.max < clock->p)
624                         INTELPllInvalid("p out of range\n");
625                 if (clock->m < limit->m.min || limit->m.max < clock->m)
626                         INTELPllInvalid("m out of range\n");
627         }
628
629         if (clock->vco < limit->vco.min || limit->vco.max < clock->vco)
630                 INTELPllInvalid("vco out of range\n");
631         /* XXX: We may need to be checking "Dot clock" depending on the multiplier,
632          * connector, etc., rather than just a single range.
633          */
634         if (clock->dot < limit->dot.min || limit->dot.max < clock->dot)
635                 INTELPllInvalid("dot out of range\n");
636
637         return true;
638 }
639
640 static int
641 i9xx_select_p2_div(const struct intel_limit *limit,
642                    const struct intel_crtc_state *crtc_state,
643                    int target)
644 {
645         struct drm_device *dev = crtc_state->base.crtc->dev;
646
647         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
648                 /*
649                  * For LVDS just rely on its current settings for dual-channel.
650                  * We haven't figured out how to reliably set up different
651                  * single/dual channel state, if we even can.
652                  */
653                 if (intel_is_dual_link_lvds(dev))
654                         return limit->p2.p2_fast;
655                 else
656                         return limit->p2.p2_slow;
657         } else {
658                 if (target < limit->p2.dot_limit)
659                         return limit->p2.p2_slow;
660                 else
661                         return limit->p2.p2_fast;
662         }
663 }
664
665 /*
666  * Returns a set of divisors for the desired target clock with the given
667  * refclk, or FALSE.  The returned values represent the clock equation:
668  * reflck * (5 * (m1 + 2) + (m2 + 2)) / (n + 2) / p1 / p2.
669  *
670  * Target and reference clocks are specified in kHz.
671  *
672  * If match_clock is provided, then best_clock P divider must match the P
673  * divider from @match_clock used for LVDS downclocking.
674  */
675 static bool
676 i9xx_find_best_dpll(const struct intel_limit *limit,
677                     struct intel_crtc_state *crtc_state,
678                     int target, int refclk, struct dpll *match_clock,
679                     struct dpll *best_clock)
680 {
681         struct drm_device *dev = crtc_state->base.crtc->dev;
682         struct dpll clock;
683         int err = target;
684
685         memset(best_clock, 0, sizeof(*best_clock));
686
687         clock.p2 = i9xx_select_p2_div(limit, crtc_state, target);
688
689         for (clock.m1 = limit->m1.min; clock.m1 <= limit->m1.max;
690              clock.m1++) {
691                 for (clock.m2 = limit->m2.min;
692                      clock.m2 <= limit->m2.max; clock.m2++) {
693                         if (clock.m2 >= clock.m1)
694                                 break;
695                         for (clock.n = limit->n.min;
696                              clock.n <= limit->n.max; clock.n++) {
697                                 for (clock.p1 = limit->p1.min;
698                                         clock.p1 <= limit->p1.max; clock.p1++) {
699                                         int this_err;
700
701                                         i9xx_calc_dpll_params(refclk, &clock);
702                                         if (!intel_PLL_is_valid(to_i915(dev),
703                                                                 limit,
704                                                                 &clock))
705                                                 continue;
706                                         if (match_clock &&
707                                             clock.p != match_clock->p)
708                                                 continue;
709
710                                         this_err = abs(clock.dot - target);
711                                         if (this_err < err) {
712                                                 *best_clock = clock;
713                                                 err = this_err;
714                                         }
715                                 }
716                         }
717                 }
718         }
719
720         return (err != target);
721 }
722
723 /*
724  * Returns a set of divisors for the desired target clock with the given
725  * refclk, or FALSE.  The returned values represent the clock equation:
726  * reflck * (5 * (m1 + 2) + (m2 + 2)) / (n + 2) / p1 / p2.
727  *
728  * Target and reference clocks are specified in kHz.
729  *
730  * If match_clock is provided, then best_clock P divider must match the P
731  * divider from @match_clock used for LVDS downclocking.
732  */
733 static bool
734 pnv_find_best_dpll(const struct intel_limit *limit,
735                    struct intel_crtc_state *crtc_state,
736                    int target, int refclk, struct dpll *match_clock,
737                    struct dpll *best_clock)
738 {
739         struct drm_device *dev = crtc_state->base.crtc->dev;
740         struct dpll clock;
741         int err = target;
742
743         memset(best_clock, 0, sizeof(*best_clock));
744
745         clock.p2 = i9xx_select_p2_div(limit, crtc_state, target);
746
747         for (clock.m1 = limit->m1.min; clock.m1 <= limit->m1.max;
748              clock.m1++) {
749                 for (clock.m2 = limit->m2.min;
750                      clock.m2 <= limit->m2.max; clock.m2++) {
751                         for (clock.n = limit->n.min;
752                              clock.n <= limit->n.max; clock.n++) {
753                                 for (clock.p1 = limit->p1.min;
754                                         clock.p1 <= limit->p1.max; clock.p1++) {
755                                         int this_err;
756
757                                         pnv_calc_dpll_params(refclk, &clock);
758                                         if (!intel_PLL_is_valid(to_i915(dev),
759                                                                 limit,
760                                                                 &clock))
761                                                 continue;
762                                         if (match_clock &&
763                                             clock.p != match_clock->p)
764                                                 continue;
765
766                                         this_err = abs(clock.dot - target);
767                                         if (this_err < err) {
768                                                 *best_clock = clock;
769                                                 err = this_err;
770                                         }
771                                 }
772                         }
773                 }
774         }
775
776         return (err != target);
777 }
778
779 /*
780  * Returns a set of divisors for the desired target clock with the given
781  * refclk, or FALSE.  The returned values represent the clock equation:
782  * reflck * (5 * (m1 + 2) + (m2 + 2)) / (n + 2) / p1 / p2.
783  *
784  * Target and reference clocks are specified in kHz.
785  *
786  * If match_clock is provided, then best_clock P divider must match the P
787  * divider from @match_clock used for LVDS downclocking.
788  */
789 static bool
790 g4x_find_best_dpll(const struct intel_limit *limit,
791                    struct intel_crtc_state *crtc_state,
792                    int target, int refclk, struct dpll *match_clock,
793                    struct dpll *best_clock)
794 {
795         struct drm_device *dev = crtc_state->base.crtc->dev;
796         struct dpll clock;
797         int max_n;
798         bool found = false;
799         /* approximately equals target * 0.00585 */
800         int err_most = (target >> 8) + (target >> 9);
801
802         memset(best_clock, 0, sizeof(*best_clock));
803
804         clock.p2 = i9xx_select_p2_div(limit, crtc_state, target);
805
806         max_n = limit->n.max;
807         /* based on hardware requirement, prefer smaller n to precision */
808         for (clock.n = limit->n.min; clock.n <= max_n; clock.n++) {
809                 /* based on hardware requirement, prefere larger m1,m2 */
810                 for (clock.m1 = limit->m1.max;
811                      clock.m1 >= limit->m1.min; clock.m1--) {
812                         for (clock.m2 = limit->m2.max;
813                              clock.m2 >= limit->m2.min; clock.m2--) {
814                                 for (clock.p1 = limit->p1.max;
815                                      clock.p1 >= limit->p1.min; clock.p1--) {
816                                         int this_err;
817
818                                         i9xx_calc_dpll_params(refclk, &clock);
819                                         if (!intel_PLL_is_valid(to_i915(dev),
820                                                                 limit,
821                                                                 &clock))
822                                                 continue;
823
824                                         this_err = abs(clock.dot - target);
825                                         if (this_err < err_most) {
826                                                 *best_clock = clock;
827                                                 err_most = this_err;
828                                                 max_n = clock.n;
829                                                 found = true;
830                                         }
831                                 }
832                         }
833                 }
834         }
835         return found;
836 }
837
838 /*
839  * Check if the calculated PLL configuration is more optimal compared to the
840  * best configuration and error found so far. Return the calculated error.
841  */
842 static bool vlv_PLL_is_optimal(struct drm_device *dev, int target_freq,
843                                const struct dpll *calculated_clock,
844                                const struct dpll *best_clock,
845                                unsigned int best_error_ppm,
846                                unsigned int *error_ppm)
847 {
848         /*
849          * For CHV ignore the error and consider only the P value.
850          * Prefer a bigger P value based on HW requirements.
851          */
852         if (IS_CHERRYVIEW(to_i915(dev))) {
853                 *error_ppm = 0;
854
855                 return calculated_clock->p > best_clock->p;
856         }
857
858         if (WARN_ON_ONCE(!target_freq))
859                 return false;
860
861         *error_ppm = div_u64(1000000ULL *
862                                 abs(target_freq - calculated_clock->dot),
863                              target_freq);
864         /*
865          * Prefer a better P value over a better (smaller) error if the error
866          * is small. Ensure this preference for future configurations too by
867          * setting the error to 0.
868          */
869         if (*error_ppm < 100 && calculated_clock->p > best_clock->p) {
870                 *error_ppm = 0;
871
872                 return true;
873         }
874
875         return *error_ppm + 10 < best_error_ppm;
876 }
877
878 /*
879  * Returns a set of divisors for the desired target clock with the given
880  * refclk, or FALSE.  The returned values represent the clock equation:
881  * reflck * (5 * (m1 + 2) + (m2 + 2)) / (n + 2) / p1 / p2.
882  */
883 static bool
884 vlv_find_best_dpll(const struct intel_limit *limit,
885                    struct intel_crtc_state *crtc_state,
886                    int target, int refclk, struct dpll *match_clock,
887                    struct dpll *best_clock)
888 {
889         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
890         struct drm_device *dev = crtc->base.dev;
891         struct dpll clock;
892         unsigned int bestppm = 1000000;
893         /* min update 19.2 MHz */
894         int max_n = min(limit->n.max, refclk / 19200);
895         bool found = false;
896
897         target *= 5; /* fast clock */
898
899         memset(best_clock, 0, sizeof(*best_clock));
900
901         /* based on hardware requirement, prefer smaller n to precision */
902         for (clock.n = limit->n.min; clock.n <= max_n; clock.n++) {
903                 for (clock.p1 = limit->p1.max; clock.p1 >= limit->p1.min; clock.p1--) {
904                         for (clock.p2 = limit->p2.p2_fast; clock.p2 >= limit->p2.p2_slow;
905                              clock.p2 -= clock.p2 > 10 ? 2 : 1) {
906                                 clock.p = clock.p1 * clock.p2;
907                                 /* based on hardware requirement, prefer bigger m1,m2 values */
908                                 for (clock.m1 = limit->m1.min; clock.m1 <= limit->m1.max; clock.m1++) {
909                                         unsigned int ppm;
910
911                                         clock.m2 = DIV_ROUND_CLOSEST(target * clock.p * clock.n,
912                                                                      refclk * clock.m1);
913
914                                         vlv_calc_dpll_params(refclk, &clock);
915
916                                         if (!intel_PLL_is_valid(to_i915(dev),
917                                                                 limit,
918                                                                 &clock))
919                                                 continue;
920
921                                         if (!vlv_PLL_is_optimal(dev, target,
922                                                                 &clock,
923                                                                 best_clock,
924                                                                 bestppm, &ppm))
925                                                 continue;
926
927                                         *best_clock = clock;
928                                         bestppm = ppm;
929                                         found = true;
930                                 }
931                         }
932                 }
933         }
934
935         return found;
936 }
937
938 /*
939  * Returns a set of divisors for the desired target clock with the given
940  * refclk, or FALSE.  The returned values represent the clock equation:
941  * reflck * (5 * (m1 + 2) + (m2 + 2)) / (n + 2) / p1 / p2.
942  */
943 static bool
944 chv_find_best_dpll(const struct intel_limit *limit,
945                    struct intel_crtc_state *crtc_state,
946                    int target, int refclk, struct dpll *match_clock,
947                    struct dpll *best_clock)
948 {
949         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
950         struct drm_device *dev = crtc->base.dev;
951         unsigned int best_error_ppm;
952         struct dpll clock;
953         uint64_t m2;
954         int found = false;
955
956         memset(best_clock, 0, sizeof(*best_clock));
957         best_error_ppm = 1000000;
958
959         /*
960          * Based on hardware doc, the n always set to 1, and m1 always
961          * set to 2.  If requires to support 200Mhz refclk, we need to
962          * revisit this because n may not 1 anymore.
963          */
964         clock.n = 1, clock.m1 = 2;
965         target *= 5;    /* fast clock */
966
967         for (clock.p1 = limit->p1.max; clock.p1 >= limit->p1.min; clock.p1--) {
968                 for (clock.p2 = limit->p2.p2_fast;
969                                 clock.p2 >= limit->p2.p2_slow;
970                                 clock.p2 -= clock.p2 > 10 ? 2 : 1) {
971                         unsigned int error_ppm;
972
973                         clock.p = clock.p1 * clock.p2;
974
975                         m2 = DIV_ROUND_CLOSEST_ULL(((uint64_t)target * clock.p *
976                                         clock.n) << 22, refclk * clock.m1);
977
978                         if (m2 > INT_MAX/clock.m1)
979                                 continue;
980
981                         clock.m2 = m2;
982
983                         chv_calc_dpll_params(refclk, &clock);
984
985                         if (!intel_PLL_is_valid(to_i915(dev), limit, &clock))
986                                 continue;
987
988                         if (!vlv_PLL_is_optimal(dev, target, &clock, best_clock,
989                                                 best_error_ppm, &error_ppm))
990                                 continue;
991
992                         *best_clock = clock;
993                         best_error_ppm = error_ppm;
994                         found = true;
995                 }
996         }
997
998         return found;
999 }
1000
1001 bool bxt_find_best_dpll(struct intel_crtc_state *crtc_state, int target_clock,
1002                         struct dpll *best_clock)
1003 {
1004         int refclk = 100000;
1005         const struct intel_limit *limit = &intel_limits_bxt;
1006
1007         return chv_find_best_dpll(limit, crtc_state,
1008                                   target_clock, refclk, NULL, best_clock);
1009 }
1010
1011 bool intel_crtc_active(struct intel_crtc *crtc)
1012 {
1013         /* Be paranoid as we can arrive here with only partial
1014          * state retrieved from the hardware during setup.
1015          *
1016          * We can ditch the adjusted_mode.crtc_clock check as soon
1017          * as Haswell has gained clock readout/fastboot support.
1018          *
1019          * We can ditch the crtc->primary->fb check as soon as we can
1020          * properly reconstruct framebuffers.
1021          *
1022          * FIXME: The intel_crtc->active here should be switched to
1023          * crtc->state->active once we have proper CRTC states wired up
1024          * for atomic.
1025          */
1026         return crtc->active && crtc->base.primary->state->fb &&
1027                 crtc->config->base.adjusted_mode.crtc_clock;
1028 }
1029
1030 enum transcoder intel_pipe_to_cpu_transcoder(struct drm_i915_private *dev_priv,
1031                                              enum pipe pipe)
1032 {
1033         struct intel_crtc *crtc = intel_get_crtc_for_pipe(dev_priv, pipe);
1034
1035         return crtc->config->cpu_transcoder;
1036 }
1037
1038 static bool pipe_dsl_stopped(struct drm_i915_private *dev_priv, enum pipe pipe)
1039 {
1040         i915_reg_t reg = PIPEDSL(pipe);
1041         u32 line1, line2;
1042         u32 line_mask;
1043
1044         if (IS_GEN2(dev_priv))
1045                 line_mask = DSL_LINEMASK_GEN2;
1046         else
1047                 line_mask = DSL_LINEMASK_GEN3;
1048
1049         line1 = I915_READ(reg) & line_mask;
1050         msleep(5);
1051         line2 = I915_READ(reg) & line_mask;
1052
1053         return line1 == line2;
1054 }
1055
1056 /*
1057  * intel_wait_for_pipe_off - wait for pipe to turn off
1058  * @crtc: crtc whose pipe to wait for
1059  *
1060  * After disabling a pipe, we can't wait for vblank in the usual way,
1061  * spinning on the vblank interrupt status bit, since we won't actually
1062  * see an interrupt when the pipe is disabled.
1063  *
1064  * On Gen4 and above:
1065  *   wait for the pipe register state bit to turn off
1066  *
1067  * Otherwise:
1068  *   wait for the display line value to settle (it usually
1069  *   ends up stopping at the start of the next frame).
1070  *
1071  */
1072 static void intel_wait_for_pipe_off(struct intel_crtc *crtc)
1073 {
1074         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1075         enum transcoder cpu_transcoder = crtc->config->cpu_transcoder;
1076         enum pipe pipe = crtc->pipe;
1077
1078         if (INTEL_GEN(dev_priv) >= 4) {
1079                 i915_reg_t reg = PIPECONF(cpu_transcoder);
1080
1081                 /* Wait for the Pipe State to go off */
1082                 if (intel_wait_for_register(dev_priv,
1083                                             reg, I965_PIPECONF_ACTIVE, 0,
1084                                             100))
1085                         WARN(1, "pipe_off wait timed out\n");
1086         } else {
1087                 /* Wait for the display line to settle */
1088                 if (wait_for(pipe_dsl_stopped(dev_priv, pipe), 100))
1089                         WARN(1, "pipe_off wait timed out\n");
1090         }
1091 }
1092
1093 /* Only for pre-ILK configs */
1094 void assert_pll(struct drm_i915_private *dev_priv,
1095                 enum pipe pipe, bool state)
1096 {
1097         u32 val;
1098         bool cur_state;
1099
1100         val = I915_READ(DPLL(pipe));
1101         cur_state = !!(val & DPLL_VCO_ENABLE);
1102         I915_STATE_WARN(cur_state != state,
1103              "PLL state assertion failure (expected %s, current %s)\n",
1104                         onoff(state), onoff(cur_state));
1105 }
1106
1107 /* XXX: the dsi pll is shared between MIPI DSI ports */
1108 void assert_dsi_pll(struct drm_i915_private *dev_priv, bool state)
1109 {
1110         u32 val;
1111         bool cur_state;
1112
1113         mutex_lock(&dev_priv->sb_lock);
1114         val = vlv_cck_read(dev_priv, CCK_REG_DSI_PLL_CONTROL);
1115         mutex_unlock(&dev_priv->sb_lock);
1116
1117         cur_state = val & DSI_PLL_VCO_EN;
1118         I915_STATE_WARN(cur_state != state,
1119              "DSI PLL state assertion failure (expected %s, current %s)\n",
1120                         onoff(state), onoff(cur_state));
1121 }
1122
1123 static void assert_fdi_tx(struct drm_i915_private *dev_priv,
1124                           enum pipe pipe, bool state)
1125 {
1126         bool cur_state;
1127         enum transcoder cpu_transcoder = intel_pipe_to_cpu_transcoder(dev_priv,
1128                                                                       pipe);
1129
1130         if (HAS_DDI(dev_priv)) {
1131                 /* DDI does not have a specific FDI_TX register */
1132                 u32 val = I915_READ(TRANS_DDI_FUNC_CTL(cpu_transcoder));
1133                 cur_state = !!(val & TRANS_DDI_FUNC_ENABLE);
1134         } else {
1135                 u32 val = I915_READ(FDI_TX_CTL(pipe));
1136                 cur_state = !!(val & FDI_TX_ENABLE);
1137         }
1138         I915_STATE_WARN(cur_state != state,
1139              "FDI TX state assertion failure (expected %s, current %s)\n",
1140                         onoff(state), onoff(cur_state));
1141 }
1142 #define assert_fdi_tx_enabled(d, p) assert_fdi_tx(d, p, true)
1143 #define assert_fdi_tx_disabled(d, p) assert_fdi_tx(d, p, false)
1144
1145 static void assert_fdi_rx(struct drm_i915_private *dev_priv,
1146                           enum pipe pipe, bool state)
1147 {
1148         u32 val;
1149         bool cur_state;
1150
1151         val = I915_READ(FDI_RX_CTL(pipe));
1152         cur_state = !!(val & FDI_RX_ENABLE);
1153         I915_STATE_WARN(cur_state != state,
1154              "FDI RX state assertion failure (expected %s, current %s)\n",
1155                         onoff(state), onoff(cur_state));
1156 }
1157 #define assert_fdi_rx_enabled(d, p) assert_fdi_rx(d, p, true)
1158 #define assert_fdi_rx_disabled(d, p) assert_fdi_rx(d, p, false)
1159
1160 static void assert_fdi_tx_pll_enabled(struct drm_i915_private *dev_priv,
1161                                       enum pipe pipe)
1162 {
1163         u32 val;
1164
1165         /* ILK FDI PLL is always enabled */
1166         if (IS_GEN5(dev_priv))
1167                 return;
1168
1169         /* On Haswell, DDI ports are responsible for the FDI PLL setup */
1170         if (HAS_DDI(dev_priv))
1171                 return;
1172
1173         val = I915_READ(FDI_TX_CTL(pipe));
1174         I915_STATE_WARN(!(val & FDI_TX_PLL_ENABLE), "FDI TX PLL assertion failure, should be active but is disabled\n");
1175 }
1176
1177 void assert_fdi_rx_pll(struct drm_i915_private *dev_priv,
1178                        enum pipe pipe, bool state)
1179 {
1180         u32 val;
1181         bool cur_state;
1182
1183         val = I915_READ(FDI_RX_CTL(pipe));
1184         cur_state = !!(val & FDI_RX_PLL_ENABLE);
1185         I915_STATE_WARN(cur_state != state,
1186              "FDI RX PLL assertion failure (expected %s, current %s)\n",
1187                         onoff(state), onoff(cur_state));
1188 }
1189
1190 void assert_panel_unlocked(struct drm_i915_private *dev_priv, enum pipe pipe)
1191 {
1192         i915_reg_t pp_reg;
1193         u32 val;
1194         enum pipe panel_pipe = PIPE_A;
1195         bool locked = true;
1196
1197         if (WARN_ON(HAS_DDI(dev_priv)))
1198                 return;
1199
1200         if (HAS_PCH_SPLIT(dev_priv)) {
1201                 u32 port_sel;
1202
1203                 pp_reg = PP_CONTROL(0);
1204                 port_sel = I915_READ(PP_ON_DELAYS(0)) & PANEL_PORT_SELECT_MASK;
1205
1206                 if (port_sel == PANEL_PORT_SELECT_LVDS &&
1207                     I915_READ(PCH_LVDS) & LVDS_PIPEB_SELECT)
1208                         panel_pipe = PIPE_B;
1209                 /* XXX: else fix for eDP */
1210         } else if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv)) {
1211                 /* presumably write lock depends on pipe, not port select */
1212                 pp_reg = PP_CONTROL(pipe);
1213                 panel_pipe = pipe;
1214         } else {
1215                 pp_reg = PP_CONTROL(0);
1216                 if (I915_READ(LVDS) & LVDS_PIPEB_SELECT)
1217                         panel_pipe = PIPE_B;
1218         }
1219
1220         val = I915_READ(pp_reg);
1221         if (!(val & PANEL_POWER_ON) ||
1222             ((val & PANEL_UNLOCK_MASK) == PANEL_UNLOCK_REGS))
1223                 locked = false;
1224
1225         I915_STATE_WARN(panel_pipe == pipe && locked,
1226              "panel assertion failure, pipe %c regs locked\n",
1227              pipe_name(pipe));
1228 }
1229
1230 static void assert_cursor(struct drm_i915_private *dev_priv,
1231                           enum pipe pipe, bool state)
1232 {
1233         bool cur_state;
1234
1235         if (IS_I845G(dev_priv) || IS_I865G(dev_priv))
1236                 cur_state = I915_READ(CURCNTR(PIPE_A)) & CURSOR_ENABLE;
1237         else
1238                 cur_state = I915_READ(CURCNTR(pipe)) & CURSOR_MODE;
1239
1240         I915_STATE_WARN(cur_state != state,
1241              "cursor on pipe %c assertion failure (expected %s, current %s)\n",
1242                         pipe_name(pipe), onoff(state), onoff(cur_state));
1243 }
1244 #define assert_cursor_enabled(d, p) assert_cursor(d, p, true)
1245 #define assert_cursor_disabled(d, p) assert_cursor(d, p, false)
1246
1247 void assert_pipe(struct drm_i915_private *dev_priv,
1248                  enum pipe pipe, bool state)
1249 {
1250         bool cur_state;
1251         enum transcoder cpu_transcoder = intel_pipe_to_cpu_transcoder(dev_priv,
1252                                                                       pipe);
1253         enum intel_display_power_domain power_domain;
1254
1255         /* if we need the pipe quirk it must be always on */
1256         if ((pipe == PIPE_A && dev_priv->quirks & QUIRK_PIPEA_FORCE) ||
1257             (pipe == PIPE_B && dev_priv->quirks & QUIRK_PIPEB_FORCE))
1258                 state = true;
1259
1260         power_domain = POWER_DOMAIN_TRANSCODER(cpu_transcoder);
1261         if (intel_display_power_get_if_enabled(dev_priv, power_domain)) {
1262                 u32 val = I915_READ(PIPECONF(cpu_transcoder));
1263                 cur_state = !!(val & PIPECONF_ENABLE);
1264
1265                 intel_display_power_put(dev_priv, power_domain);
1266         } else {
1267                 cur_state = false;
1268         }
1269
1270         I915_STATE_WARN(cur_state != state,
1271              "pipe %c assertion failure (expected %s, current %s)\n",
1272                         pipe_name(pipe), onoff(state), onoff(cur_state));
1273 }
1274
1275 static void assert_plane(struct drm_i915_private *dev_priv,
1276                          enum plane plane, bool state)
1277 {
1278         u32 val;
1279         bool cur_state;
1280
1281         val = I915_READ(DSPCNTR(plane));
1282         cur_state = !!(val & DISPLAY_PLANE_ENABLE);
1283         I915_STATE_WARN(cur_state != state,
1284              "plane %c assertion failure (expected %s, current %s)\n",
1285                         plane_name(plane), onoff(state), onoff(cur_state));
1286 }
1287
1288 #define assert_plane_enabled(d, p) assert_plane(d, p, true)
1289 #define assert_plane_disabled(d, p) assert_plane(d, p, false)
1290
1291 static void assert_planes_disabled(struct drm_i915_private *dev_priv,
1292                                    enum pipe pipe)
1293 {
1294         int i;
1295
1296         /* Primary planes are fixed to pipes on gen4+ */
1297         if (INTEL_GEN(dev_priv) >= 4) {
1298                 u32 val = I915_READ(DSPCNTR(pipe));
1299                 I915_STATE_WARN(val & DISPLAY_PLANE_ENABLE,
1300                      "plane %c assertion failure, should be disabled but not\n",
1301                      plane_name(pipe));
1302                 return;
1303         }
1304
1305         /* Need to check both planes against the pipe */
1306         for_each_pipe(dev_priv, i) {
1307                 u32 val = I915_READ(DSPCNTR(i));
1308                 enum pipe cur_pipe = (val & DISPPLANE_SEL_PIPE_MASK) >>
1309                         DISPPLANE_SEL_PIPE_SHIFT;
1310                 I915_STATE_WARN((val & DISPLAY_PLANE_ENABLE) && pipe == cur_pipe,
1311                      "plane %c assertion failure, should be off on pipe %c but is still active\n",
1312                      plane_name(i), pipe_name(pipe));
1313         }
1314 }
1315
1316 static void assert_sprites_disabled(struct drm_i915_private *dev_priv,
1317                                     enum pipe pipe)
1318 {
1319         int sprite;
1320
1321         if (INTEL_GEN(dev_priv) >= 9) {
1322                 for_each_sprite(dev_priv, pipe, sprite) {
1323                         u32 val = I915_READ(PLANE_CTL(pipe, sprite));
1324                         I915_STATE_WARN(val & PLANE_CTL_ENABLE,
1325                              "plane %d assertion failure, should be off on pipe %c but is still active\n",
1326                              sprite, pipe_name(pipe));
1327                 }
1328         } else if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv)) {
1329                 for_each_sprite(dev_priv, pipe, sprite) {
1330                         u32 val = I915_READ(SPCNTR(pipe, PLANE_SPRITE0 + sprite));
1331                         I915_STATE_WARN(val & SP_ENABLE,
1332                              "sprite %c assertion failure, should be off on pipe %c but is still active\n",
1333                              sprite_name(pipe, sprite), pipe_name(pipe));
1334                 }
1335         } else if (INTEL_GEN(dev_priv) >= 7) {
1336                 u32 val = I915_READ(SPRCTL(pipe));
1337                 I915_STATE_WARN(val & SPRITE_ENABLE,
1338                      "sprite %c assertion failure, should be off on pipe %c but is still active\n",
1339                      plane_name(pipe), pipe_name(pipe));
1340         } else if (INTEL_GEN(dev_priv) >= 5) {
1341                 u32 val = I915_READ(DVSCNTR(pipe));
1342                 I915_STATE_WARN(val & DVS_ENABLE,
1343                      "sprite %c assertion failure, should be off on pipe %c but is still active\n",
1344                      plane_name(pipe), pipe_name(pipe));
1345         }
1346 }
1347
1348 static void assert_vblank_disabled(struct drm_crtc *crtc)
1349 {
1350         if (I915_STATE_WARN_ON(drm_crtc_vblank_get(crtc) == 0))
1351                 drm_crtc_vblank_put(crtc);
1352 }
1353
1354 void assert_pch_transcoder_disabled(struct drm_i915_private *dev_priv,
1355                                     enum pipe pipe)
1356 {
1357         u32 val;
1358         bool enabled;
1359
1360         val = I915_READ(PCH_TRANSCONF(pipe));
1361         enabled = !!(val & TRANS_ENABLE);
1362         I915_STATE_WARN(enabled,
1363              "transcoder assertion failed, should be off on pipe %c but is still active\n",
1364              pipe_name(pipe));
1365 }
1366
1367 static bool dp_pipe_enabled(struct drm_i915_private *dev_priv,
1368                             enum pipe pipe, u32 port_sel, u32 val)
1369 {
1370         if ((val & DP_PORT_EN) == 0)
1371                 return false;
1372
1373         if (HAS_PCH_CPT(dev_priv)) {
1374                 u32 trans_dp_ctl = I915_READ(TRANS_DP_CTL(pipe));
1375                 if ((trans_dp_ctl & TRANS_DP_PORT_SEL_MASK) != port_sel)
1376                         return false;
1377         } else if (IS_CHERRYVIEW(dev_priv)) {
1378                 if ((val & DP_PIPE_MASK_CHV) != DP_PIPE_SELECT_CHV(pipe))
1379                         return false;
1380         } else {
1381                 if ((val & DP_PIPE_MASK) != (pipe << 30))
1382                         return false;
1383         }
1384         return true;
1385 }
1386
1387 static bool hdmi_pipe_enabled(struct drm_i915_private *dev_priv,
1388                               enum pipe pipe, u32 val)
1389 {
1390         if ((val & SDVO_ENABLE) == 0)
1391                 return false;
1392
1393         if (HAS_PCH_CPT(dev_priv)) {
1394                 if ((val & SDVO_PIPE_SEL_MASK_CPT) != SDVO_PIPE_SEL_CPT(pipe))
1395                         return false;
1396         } else if (IS_CHERRYVIEW(dev_priv)) {
1397                 if ((val & SDVO_PIPE_SEL_MASK_CHV) != SDVO_PIPE_SEL_CHV(pipe))
1398                         return false;
1399         } else {
1400                 if ((val & SDVO_PIPE_SEL_MASK) != SDVO_PIPE_SEL(pipe))
1401                         return false;
1402         }
1403         return true;
1404 }
1405
1406 static bool lvds_pipe_enabled(struct drm_i915_private *dev_priv,
1407                               enum pipe pipe, u32 val)
1408 {
1409         if ((val & LVDS_PORT_EN) == 0)
1410                 return false;
1411
1412         if (HAS_PCH_CPT(dev_priv)) {
1413                 if ((val & PORT_TRANS_SEL_MASK) != PORT_TRANS_SEL_CPT(pipe))
1414                         return false;
1415         } else {
1416                 if ((val & LVDS_PIPE_MASK) != LVDS_PIPE(pipe))
1417                         return false;
1418         }
1419         return true;
1420 }
1421
1422 static bool adpa_pipe_enabled(struct drm_i915_private *dev_priv,
1423                               enum pipe pipe, u32 val)
1424 {
1425         if ((val & ADPA_DAC_ENABLE) == 0)
1426                 return false;
1427         if (HAS_PCH_CPT(dev_priv)) {
1428                 if ((val & PORT_TRANS_SEL_MASK) != PORT_TRANS_SEL_CPT(pipe))
1429                         return false;
1430         } else {
1431                 if ((val & ADPA_PIPE_SELECT_MASK) != ADPA_PIPE_SELECT(pipe))
1432                         return false;
1433         }
1434         return true;
1435 }
1436
1437 static void assert_pch_dp_disabled(struct drm_i915_private *dev_priv,
1438                                    enum pipe pipe, i915_reg_t reg,
1439                                    u32 port_sel)
1440 {
1441         u32 val = I915_READ(reg);
1442         I915_STATE_WARN(dp_pipe_enabled(dev_priv, pipe, port_sel, val),
1443              "PCH DP (0x%08x) enabled on transcoder %c, should be disabled\n",
1444              i915_mmio_reg_offset(reg), pipe_name(pipe));
1445
1446         I915_STATE_WARN(HAS_PCH_IBX(dev_priv) && (val & DP_PORT_EN) == 0
1447              && (val & DP_PIPEB_SELECT),
1448              "IBX PCH dp port still using transcoder B\n");
1449 }
1450
1451 static void assert_pch_hdmi_disabled(struct drm_i915_private *dev_priv,
1452                                      enum pipe pipe, i915_reg_t reg)
1453 {
1454         u32 val = I915_READ(reg);
1455         I915_STATE_WARN(hdmi_pipe_enabled(dev_priv, pipe, val),
1456              "PCH HDMI (0x%08x) enabled on transcoder %c, should be disabled\n",
1457              i915_mmio_reg_offset(reg), pipe_name(pipe));
1458
1459         I915_STATE_WARN(HAS_PCH_IBX(dev_priv) && (val & SDVO_ENABLE) == 0
1460              && (val & SDVO_PIPE_B_SELECT),
1461              "IBX PCH hdmi port still using transcoder B\n");
1462 }
1463
1464 static void assert_pch_ports_disabled(struct drm_i915_private *dev_priv,
1465                                       enum pipe pipe)
1466 {
1467         u32 val;
1468
1469         assert_pch_dp_disabled(dev_priv, pipe, PCH_DP_B, TRANS_DP_PORT_SEL_B);
1470         assert_pch_dp_disabled(dev_priv, pipe, PCH_DP_C, TRANS_DP_PORT_SEL_C);
1471         assert_pch_dp_disabled(dev_priv, pipe, PCH_DP_D, TRANS_DP_PORT_SEL_D);
1472
1473         val = I915_READ(PCH_ADPA);
1474         I915_STATE_WARN(adpa_pipe_enabled(dev_priv, pipe, val),
1475              "PCH VGA enabled on transcoder %c, should be disabled\n",
1476              pipe_name(pipe));
1477
1478         val = I915_READ(PCH_LVDS);
1479         I915_STATE_WARN(lvds_pipe_enabled(dev_priv, pipe, val),
1480              "PCH LVDS enabled on transcoder %c, should be disabled\n",
1481              pipe_name(pipe));
1482
1483         assert_pch_hdmi_disabled(dev_priv, pipe, PCH_HDMIB);
1484         assert_pch_hdmi_disabled(dev_priv, pipe, PCH_HDMIC);
1485         assert_pch_hdmi_disabled(dev_priv, pipe, PCH_HDMID);
1486 }
1487
1488 static void _vlv_enable_pll(struct intel_crtc *crtc,
1489                             const struct intel_crtc_state *pipe_config)
1490 {
1491         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1492         enum pipe pipe = crtc->pipe;
1493
1494         I915_WRITE(DPLL(pipe), pipe_config->dpll_hw_state.dpll);
1495         POSTING_READ(DPLL(pipe));
1496         udelay(150);
1497
1498         if (intel_wait_for_register(dev_priv,
1499                                     DPLL(pipe),
1500                                     DPLL_LOCK_VLV,
1501                                     DPLL_LOCK_VLV,
1502                                     1))
1503                 DRM_ERROR("DPLL %d failed to lock\n", pipe);
1504 }
1505
1506 static void vlv_enable_pll(struct intel_crtc *crtc,
1507                            const struct intel_crtc_state *pipe_config)
1508 {
1509         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1510         enum pipe pipe = crtc->pipe;
1511
1512         assert_pipe_disabled(dev_priv, pipe);
1513
1514         /* PLL is protected by panel, make sure we can write it */
1515         assert_panel_unlocked(dev_priv, pipe);
1516
1517         if (pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE)
1518                 _vlv_enable_pll(crtc, pipe_config);
1519
1520         I915_WRITE(DPLL_MD(pipe), pipe_config->dpll_hw_state.dpll_md);
1521         POSTING_READ(DPLL_MD(pipe));
1522 }
1523
1524
1525 static void _chv_enable_pll(struct intel_crtc *crtc,
1526                             const struct intel_crtc_state *pipe_config)
1527 {
1528         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1529         enum pipe pipe = crtc->pipe;
1530         enum dpio_channel port = vlv_pipe_to_channel(pipe);
1531         u32 tmp;
1532
1533         mutex_lock(&dev_priv->sb_lock);
1534
1535         /* Enable back the 10bit clock to display controller */
1536         tmp = vlv_dpio_read(dev_priv, pipe, CHV_CMN_DW14(port));
1537         tmp |= DPIO_DCLKP_EN;
1538         vlv_dpio_write(dev_priv, pipe, CHV_CMN_DW14(port), tmp);
1539
1540         mutex_unlock(&dev_priv->sb_lock);
1541
1542         /*
1543          * Need to wait > 100ns between dclkp clock enable bit and PLL enable.
1544          */
1545         udelay(1);
1546
1547         /* Enable PLL */
1548         I915_WRITE(DPLL(pipe), pipe_config->dpll_hw_state.dpll);
1549
1550         /* Check PLL is locked */
1551         if (intel_wait_for_register(dev_priv,
1552                                     DPLL(pipe), DPLL_LOCK_VLV, DPLL_LOCK_VLV,
1553                                     1))
1554                 DRM_ERROR("PLL %d failed to lock\n", pipe);
1555 }
1556
1557 static void chv_enable_pll(struct intel_crtc *crtc,
1558                            const struct intel_crtc_state *pipe_config)
1559 {
1560         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1561         enum pipe pipe = crtc->pipe;
1562
1563         assert_pipe_disabled(dev_priv, pipe);
1564
1565         /* PLL is protected by panel, make sure we can write it */
1566         assert_panel_unlocked(dev_priv, pipe);
1567
1568         if (pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE)
1569                 _chv_enable_pll(crtc, pipe_config);
1570
1571         if (pipe != PIPE_A) {
1572                 /*
1573                  * WaPixelRepeatModeFixForC0:chv
1574                  *
1575                  * DPLLCMD is AWOL. Use chicken bits to propagate
1576                  * the value from DPLLBMD to either pipe B or C.
1577                  */
1578                 I915_WRITE(CBR4_VLV, pipe == PIPE_B ? CBR_DPLLBMD_PIPE_B : CBR_DPLLBMD_PIPE_C);
1579                 I915_WRITE(DPLL_MD(PIPE_B), pipe_config->dpll_hw_state.dpll_md);
1580                 I915_WRITE(CBR4_VLV, 0);
1581                 dev_priv->chv_dpll_md[pipe] = pipe_config->dpll_hw_state.dpll_md;
1582
1583                 /*
1584                  * DPLLB VGA mode also seems to cause problems.
1585                  * We should always have it disabled.
1586                  */
1587                 WARN_ON((I915_READ(DPLL(PIPE_B)) & DPLL_VGA_MODE_DIS) == 0);
1588         } else {
1589                 I915_WRITE(DPLL_MD(pipe), pipe_config->dpll_hw_state.dpll_md);
1590                 POSTING_READ(DPLL_MD(pipe));
1591         }
1592 }
1593
1594 static int intel_num_dvo_pipes(struct drm_i915_private *dev_priv)
1595 {
1596         struct intel_crtc *crtc;
1597         int count = 0;
1598
1599         for_each_intel_crtc(&dev_priv->drm, crtc) {
1600                 count += crtc->base.state->active &&
1601                         intel_crtc_has_type(crtc->config, INTEL_OUTPUT_DVO);
1602         }
1603
1604         return count;
1605 }
1606
1607 static void i9xx_enable_pll(struct intel_crtc *crtc)
1608 {
1609         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1610         i915_reg_t reg = DPLL(crtc->pipe);
1611         u32 dpll = crtc->config->dpll_hw_state.dpll;
1612
1613         assert_pipe_disabled(dev_priv, crtc->pipe);
1614
1615         /* PLL is protected by panel, make sure we can write it */
1616         if (IS_MOBILE(dev_priv) && !IS_I830(dev_priv))
1617                 assert_panel_unlocked(dev_priv, crtc->pipe);
1618
1619         /* Enable DVO 2x clock on both PLLs if necessary */
1620         if (IS_I830(dev_priv) && intel_num_dvo_pipes(dev_priv) > 0) {
1621                 /*
1622                  * It appears to be important that we don't enable this
1623                  * for the current pipe before otherwise configuring the
1624                  * PLL. No idea how this should be handled if multiple
1625                  * DVO outputs are enabled simultaneosly.
1626                  */
1627                 dpll |= DPLL_DVO_2X_MODE;
1628                 I915_WRITE(DPLL(!crtc->pipe),
1629                            I915_READ(DPLL(!crtc->pipe)) | DPLL_DVO_2X_MODE);
1630         }
1631
1632         /*
1633          * Apparently we need to have VGA mode enabled prior to changing
1634          * the P1/P2 dividers. Otherwise the DPLL will keep using the old
1635          * dividers, even though the register value does change.
1636          */
1637         I915_WRITE(reg, 0);
1638
1639         I915_WRITE(reg, dpll);
1640
1641         /* Wait for the clocks to stabilize. */
1642         POSTING_READ(reg);
1643         udelay(150);
1644
1645         if (INTEL_GEN(dev_priv) >= 4) {
1646                 I915_WRITE(DPLL_MD(crtc->pipe),
1647                            crtc->config->dpll_hw_state.dpll_md);
1648         } else {
1649                 /* The pixel multiplier can only be updated once the
1650                  * DPLL is enabled and the clocks are stable.
1651                  *
1652                  * So write it again.
1653                  */
1654                 I915_WRITE(reg, dpll);
1655         }
1656
1657         /* We do this three times for luck */
1658         I915_WRITE(reg, dpll);
1659         POSTING_READ(reg);
1660         udelay(150); /* wait for warmup */
1661         I915_WRITE(reg, dpll);
1662         POSTING_READ(reg);
1663         udelay(150); /* wait for warmup */
1664         I915_WRITE(reg, dpll);
1665         POSTING_READ(reg);
1666         udelay(150); /* wait for warmup */
1667 }
1668
1669 /**
1670  * i9xx_disable_pll - disable a PLL
1671  * @dev_priv: i915 private structure
1672  * @pipe: pipe PLL to disable
1673  *
1674  * Disable the PLL for @pipe, making sure the pipe is off first.
1675  *
1676  * Note!  This is for pre-ILK only.
1677  */
1678 static void i9xx_disable_pll(struct intel_crtc *crtc)
1679 {
1680         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1681         enum pipe pipe = crtc->pipe;
1682
1683         /* Disable DVO 2x clock on both PLLs if necessary */
1684         if (IS_I830(dev_priv) &&
1685             intel_crtc_has_type(crtc->config, INTEL_OUTPUT_DVO) &&
1686             !intel_num_dvo_pipes(dev_priv)) {
1687                 I915_WRITE(DPLL(PIPE_B),
1688                            I915_READ(DPLL(PIPE_B)) & ~DPLL_DVO_2X_MODE);
1689                 I915_WRITE(DPLL(PIPE_A),
1690                            I915_READ(DPLL(PIPE_A)) & ~DPLL_DVO_2X_MODE);
1691         }
1692
1693         /* Don't disable pipe or pipe PLLs if needed */
1694         if ((pipe == PIPE_A && dev_priv->quirks & QUIRK_PIPEA_FORCE) ||
1695             (pipe == PIPE_B && dev_priv->quirks & QUIRK_PIPEB_FORCE))
1696                 return;
1697
1698         /* Make sure the pipe isn't still relying on us */
1699         assert_pipe_disabled(dev_priv, pipe);
1700
1701         I915_WRITE(DPLL(pipe), DPLL_VGA_MODE_DIS);
1702         POSTING_READ(DPLL(pipe));
1703 }
1704
1705 static void vlv_disable_pll(struct drm_i915_private *dev_priv, enum pipe pipe)
1706 {
1707         u32 val;
1708
1709         /* Make sure the pipe isn't still relying on us */
1710         assert_pipe_disabled(dev_priv, pipe);
1711
1712         val = DPLL_INTEGRATED_REF_CLK_VLV |
1713                 DPLL_REF_CLK_ENABLE_VLV | DPLL_VGA_MODE_DIS;
1714         if (pipe != PIPE_A)
1715                 val |= DPLL_INTEGRATED_CRI_CLK_VLV;
1716
1717         I915_WRITE(DPLL(pipe), val);
1718         POSTING_READ(DPLL(pipe));
1719 }
1720
1721 static void chv_disable_pll(struct drm_i915_private *dev_priv, enum pipe pipe)
1722 {
1723         enum dpio_channel port = vlv_pipe_to_channel(pipe);
1724         u32 val;
1725
1726         /* Make sure the pipe isn't still relying on us */
1727         assert_pipe_disabled(dev_priv, pipe);
1728
1729         val = DPLL_SSC_REF_CLK_CHV |
1730                 DPLL_REF_CLK_ENABLE_VLV | DPLL_VGA_MODE_DIS;
1731         if (pipe != PIPE_A)
1732                 val |= DPLL_INTEGRATED_CRI_CLK_VLV;
1733
1734         I915_WRITE(DPLL(pipe), val);
1735         POSTING_READ(DPLL(pipe));
1736
1737         mutex_lock(&dev_priv->sb_lock);
1738
1739         /* Disable 10bit clock to display controller */
1740         val = vlv_dpio_read(dev_priv, pipe, CHV_CMN_DW14(port));
1741         val &= ~DPIO_DCLKP_EN;
1742         vlv_dpio_write(dev_priv, pipe, CHV_CMN_DW14(port), val);
1743
1744         mutex_unlock(&dev_priv->sb_lock);
1745 }
1746
1747 void vlv_wait_port_ready(struct drm_i915_private *dev_priv,
1748                          struct intel_digital_port *dport,
1749                          unsigned int expected_mask)
1750 {
1751         u32 port_mask;
1752         i915_reg_t dpll_reg;
1753
1754         switch (dport->port) {
1755         case PORT_B:
1756                 port_mask = DPLL_PORTB_READY_MASK;
1757                 dpll_reg = DPLL(0);
1758                 break;
1759         case PORT_C:
1760                 port_mask = DPLL_PORTC_READY_MASK;
1761                 dpll_reg = DPLL(0);
1762                 expected_mask <<= 4;
1763                 break;
1764         case PORT_D:
1765                 port_mask = DPLL_PORTD_READY_MASK;
1766                 dpll_reg = DPIO_PHY_STATUS;
1767                 break;
1768         default:
1769                 BUG();
1770         }
1771
1772         if (intel_wait_for_register(dev_priv,
1773                                     dpll_reg, port_mask, expected_mask,
1774                                     1000))
1775                 WARN(1, "timed out waiting for port %c ready: got 0x%x, expected 0x%x\n",
1776                      port_name(dport->port), I915_READ(dpll_reg) & port_mask, expected_mask);
1777 }
1778
1779 static void ironlake_enable_pch_transcoder(struct drm_i915_private *dev_priv,
1780                                            enum pipe pipe)
1781 {
1782         struct intel_crtc *intel_crtc = intel_get_crtc_for_pipe(dev_priv,
1783                                                                 pipe);
1784         i915_reg_t reg;
1785         uint32_t val, pipeconf_val;
1786
1787         /* Make sure PCH DPLL is enabled */
1788         assert_shared_dpll_enabled(dev_priv, intel_crtc->config->shared_dpll);
1789
1790         /* FDI must be feeding us bits for PCH ports */
1791         assert_fdi_tx_enabled(dev_priv, pipe);
1792         assert_fdi_rx_enabled(dev_priv, pipe);
1793
1794         if (HAS_PCH_CPT(dev_priv)) {
1795                 /* Workaround: Set the timing override bit before enabling the
1796                  * pch transcoder. */
1797                 reg = TRANS_CHICKEN2(pipe);
1798                 val = I915_READ(reg);
1799                 val |= TRANS_CHICKEN2_TIMING_OVERRIDE;
1800                 I915_WRITE(reg, val);
1801         }
1802
1803         reg = PCH_TRANSCONF(pipe);
1804         val = I915_READ(reg);
1805         pipeconf_val = I915_READ(PIPECONF(pipe));
1806
1807         if (HAS_PCH_IBX(dev_priv)) {
1808                 /*
1809                  * Make the BPC in transcoder be consistent with
1810                  * that in pipeconf reg. For HDMI we must use 8bpc
1811                  * here for both 8bpc and 12bpc.
1812                  */
1813                 val &= ~PIPECONF_BPC_MASK;
1814                 if (intel_crtc_has_type(intel_crtc->config, INTEL_OUTPUT_HDMI))
1815                         val |= PIPECONF_8BPC;
1816                 else
1817                         val |= pipeconf_val & PIPECONF_BPC_MASK;
1818         }
1819
1820         val &= ~TRANS_INTERLACE_MASK;
1821         if ((pipeconf_val & PIPECONF_INTERLACE_MASK) == PIPECONF_INTERLACED_ILK)
1822                 if (HAS_PCH_IBX(dev_priv) &&
1823                     intel_crtc_has_type(intel_crtc->config, INTEL_OUTPUT_SDVO))
1824                         val |= TRANS_LEGACY_INTERLACED_ILK;
1825                 else
1826                         val |= TRANS_INTERLACED;
1827         else
1828                 val |= TRANS_PROGRESSIVE;
1829
1830         I915_WRITE(reg, val | TRANS_ENABLE);
1831         if (intel_wait_for_register(dev_priv,
1832                                     reg, TRANS_STATE_ENABLE, TRANS_STATE_ENABLE,
1833                                     100))
1834                 DRM_ERROR("failed to enable transcoder %c\n", pipe_name(pipe));
1835 }
1836
1837 static void lpt_enable_pch_transcoder(struct drm_i915_private *dev_priv,
1838                                       enum transcoder cpu_transcoder)
1839 {
1840         u32 val, pipeconf_val;
1841
1842         /* FDI must be feeding us bits for PCH ports */
1843         assert_fdi_tx_enabled(dev_priv, (enum pipe) cpu_transcoder);
1844         assert_fdi_rx_enabled(dev_priv, TRANSCODER_A);
1845
1846         /* Workaround: set timing override bit. */
1847         val = I915_READ(TRANS_CHICKEN2(PIPE_A));
1848         val |= TRANS_CHICKEN2_TIMING_OVERRIDE;
1849         I915_WRITE(TRANS_CHICKEN2(PIPE_A), val);
1850
1851         val = TRANS_ENABLE;
1852         pipeconf_val = I915_READ(PIPECONF(cpu_transcoder));
1853
1854         if ((pipeconf_val & PIPECONF_INTERLACE_MASK_HSW) ==
1855             PIPECONF_INTERLACED_ILK)
1856                 val |= TRANS_INTERLACED;
1857         else
1858                 val |= TRANS_PROGRESSIVE;
1859
1860         I915_WRITE(LPT_TRANSCONF, val);
1861         if (intel_wait_for_register(dev_priv,
1862                                     LPT_TRANSCONF,
1863                                     TRANS_STATE_ENABLE,
1864                                     TRANS_STATE_ENABLE,
1865                                     100))
1866                 DRM_ERROR("Failed to enable PCH transcoder\n");
1867 }
1868
1869 static void ironlake_disable_pch_transcoder(struct drm_i915_private *dev_priv,
1870                                             enum pipe pipe)
1871 {
1872         i915_reg_t reg;
1873         uint32_t val;
1874
1875         /* FDI relies on the transcoder */
1876         assert_fdi_tx_disabled(dev_priv, pipe);
1877         assert_fdi_rx_disabled(dev_priv, pipe);
1878
1879         /* Ports must be off as well */
1880         assert_pch_ports_disabled(dev_priv, pipe);
1881
1882         reg = PCH_TRANSCONF(pipe);
1883         val = I915_READ(reg);
1884         val &= ~TRANS_ENABLE;
1885         I915_WRITE(reg, val);
1886         /* wait for PCH transcoder off, transcoder state */
1887         if (intel_wait_for_register(dev_priv,
1888                                     reg, TRANS_STATE_ENABLE, 0,
1889                                     50))
1890                 DRM_ERROR("failed to disable transcoder %c\n", pipe_name(pipe));
1891
1892         if (HAS_PCH_CPT(dev_priv)) {
1893                 /* Workaround: Clear the timing override chicken bit again. */
1894                 reg = TRANS_CHICKEN2(pipe);
1895                 val = I915_READ(reg);
1896                 val &= ~TRANS_CHICKEN2_TIMING_OVERRIDE;
1897                 I915_WRITE(reg, val);
1898         }
1899 }
1900
1901 void lpt_disable_pch_transcoder(struct drm_i915_private *dev_priv)
1902 {
1903         u32 val;
1904
1905         val = I915_READ(LPT_TRANSCONF);
1906         val &= ~TRANS_ENABLE;
1907         I915_WRITE(LPT_TRANSCONF, val);
1908         /* wait for PCH transcoder off, transcoder state */
1909         if (intel_wait_for_register(dev_priv,
1910                                     LPT_TRANSCONF, TRANS_STATE_ENABLE, 0,
1911                                     50))
1912                 DRM_ERROR("Failed to disable PCH transcoder\n");
1913
1914         /* Workaround: clear timing override bit. */
1915         val = I915_READ(TRANS_CHICKEN2(PIPE_A));
1916         val &= ~TRANS_CHICKEN2_TIMING_OVERRIDE;
1917         I915_WRITE(TRANS_CHICKEN2(PIPE_A), val);
1918 }
1919
1920 enum transcoder intel_crtc_pch_transcoder(struct intel_crtc *crtc)
1921 {
1922         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1923
1924         WARN_ON(!crtc->config->has_pch_encoder);
1925
1926         if (HAS_PCH_LPT(dev_priv))
1927                 return TRANSCODER_A;
1928         else
1929                 return (enum transcoder) crtc->pipe;
1930 }
1931
1932 /**
1933  * intel_enable_pipe - enable a pipe, asserting requirements
1934  * @crtc: crtc responsible for the pipe
1935  *
1936  * Enable @crtc's pipe, making sure that various hardware specific requirements
1937  * are met, if applicable, e.g. PLL enabled, LVDS pairs enabled, etc.
1938  */
1939 static void intel_enable_pipe(struct intel_crtc *crtc)
1940 {
1941         struct drm_device *dev = crtc->base.dev;
1942         struct drm_i915_private *dev_priv = to_i915(dev);
1943         enum pipe pipe = crtc->pipe;
1944         enum transcoder cpu_transcoder = crtc->config->cpu_transcoder;
1945         i915_reg_t reg;
1946         u32 val;
1947
1948         DRM_DEBUG_KMS("enabling pipe %c\n", pipe_name(pipe));
1949
1950         assert_planes_disabled(dev_priv, pipe);
1951         assert_cursor_disabled(dev_priv, pipe);
1952         assert_sprites_disabled(dev_priv, pipe);
1953
1954         /*
1955          * A pipe without a PLL won't actually be able to drive bits from
1956          * a plane.  On ILK+ the pipe PLLs are integrated, so we don't
1957          * need the check.
1958          */
1959         if (HAS_GMCH_DISPLAY(dev_priv)) {
1960                 if (intel_crtc_has_type(crtc->config, INTEL_OUTPUT_DSI))
1961                         assert_dsi_pll_enabled(dev_priv);
1962                 else
1963                         assert_pll_enabled(dev_priv, pipe);
1964         } else {
1965                 if (crtc->config->has_pch_encoder) {
1966                         /* if driving the PCH, we need FDI enabled */
1967                         assert_fdi_rx_pll_enabled(dev_priv,
1968                                                   (enum pipe) intel_crtc_pch_transcoder(crtc));
1969                         assert_fdi_tx_pll_enabled(dev_priv,
1970                                                   (enum pipe) cpu_transcoder);
1971                 }
1972                 /* FIXME: assert CPU port conditions for SNB+ */
1973         }
1974
1975         reg = PIPECONF(cpu_transcoder);
1976         val = I915_READ(reg);
1977         if (val & PIPECONF_ENABLE) {
1978                 WARN_ON(!((pipe == PIPE_A && dev_priv->quirks & QUIRK_PIPEA_FORCE) ||
1979                           (pipe == PIPE_B && dev_priv->quirks & QUIRK_PIPEB_FORCE)));
1980                 return;
1981         }
1982
1983         I915_WRITE(reg, val | PIPECONF_ENABLE);
1984         POSTING_READ(reg);
1985
1986         /*
1987          * Until the pipe starts DSL will read as 0, which would cause
1988          * an apparent vblank timestamp jump, which messes up also the
1989          * frame count when it's derived from the timestamps. So let's
1990          * wait for the pipe to start properly before we call
1991          * drm_crtc_vblank_on()
1992          */
1993         if (dev->max_vblank_count == 0 &&
1994             wait_for(intel_get_crtc_scanline(crtc) != crtc->scanline_offset, 50))
1995                 DRM_ERROR("pipe %c didn't start\n", pipe_name(pipe));
1996 }
1997
1998 /**
1999  * intel_disable_pipe - disable a pipe, asserting requirements
2000  * @crtc: crtc whose pipes is to be disabled
2001  *
2002  * Disable the pipe of @crtc, making sure that various hardware
2003  * specific requirements are met, if applicable, e.g. plane
2004  * disabled, panel fitter off, etc.
2005  *
2006  * Will wait until the pipe has shut down before returning.
2007  */
2008 static void intel_disable_pipe(struct intel_crtc *crtc)
2009 {
2010         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
2011         enum transcoder cpu_transcoder = crtc->config->cpu_transcoder;
2012         enum pipe pipe = crtc->pipe;
2013         i915_reg_t reg;
2014         u32 val;
2015
2016         DRM_DEBUG_KMS("disabling pipe %c\n", pipe_name(pipe));
2017
2018         /*
2019          * Make sure planes won't keep trying to pump pixels to us,
2020          * or we might hang the display.
2021          */
2022         assert_planes_disabled(dev_priv, pipe);
2023         assert_cursor_disabled(dev_priv, pipe);
2024         assert_sprites_disabled(dev_priv, pipe);
2025
2026         reg = PIPECONF(cpu_transcoder);
2027         val = I915_READ(reg);
2028         if ((val & PIPECONF_ENABLE) == 0)
2029                 return;
2030
2031         /*
2032          * Double wide has implications for planes
2033          * so best keep it disabled when not needed.
2034          */
2035         if (crtc->config->double_wide)
2036                 val &= ~PIPECONF_DOUBLE_WIDE;
2037
2038         /* Don't disable pipe or pipe PLLs if needed */
2039         if (!(pipe == PIPE_A && dev_priv->quirks & QUIRK_PIPEA_FORCE) &&
2040             !(pipe == PIPE_B && dev_priv->quirks & QUIRK_PIPEB_FORCE))
2041                 val &= ~PIPECONF_ENABLE;
2042
2043         I915_WRITE(reg, val);
2044         if ((val & PIPECONF_ENABLE) == 0)
2045                 intel_wait_for_pipe_off(crtc);
2046 }
2047
2048 static unsigned int intel_tile_size(const struct drm_i915_private *dev_priv)
2049 {
2050         return IS_GEN2(dev_priv) ? 2048 : 4096;
2051 }
2052
2053 static unsigned int intel_tile_width_bytes(const struct drm_i915_private *dev_priv,
2054                                            uint64_t fb_modifier, unsigned int cpp)
2055 {
2056         switch (fb_modifier) {
2057         case DRM_FORMAT_MOD_NONE:
2058                 return cpp;
2059         case I915_FORMAT_MOD_X_TILED:
2060                 if (IS_GEN2(dev_priv))
2061                         return 128;
2062                 else
2063                         return 512;
2064         case I915_FORMAT_MOD_Y_TILED:
2065                 if (IS_GEN2(dev_priv) || HAS_128_BYTE_Y_TILING(dev_priv))
2066                         return 128;
2067                 else
2068                         return 512;
2069         case I915_FORMAT_MOD_Yf_TILED:
2070                 switch (cpp) {
2071                 case 1:
2072                         return 64;
2073                 case 2:
2074                 case 4:
2075                         return 128;
2076                 case 8:
2077                 case 16:
2078                         return 256;
2079                 default:
2080                         MISSING_CASE(cpp);
2081                         return cpp;
2082                 }
2083                 break;
2084         default:
2085                 MISSING_CASE(fb_modifier);
2086                 return cpp;
2087         }
2088 }
2089
2090 unsigned int intel_tile_height(const struct drm_i915_private *dev_priv,
2091                                uint64_t fb_modifier, unsigned int cpp)
2092 {
2093         if (fb_modifier == DRM_FORMAT_MOD_NONE)
2094                 return 1;
2095         else
2096                 return intel_tile_size(dev_priv) /
2097                         intel_tile_width_bytes(dev_priv, fb_modifier, cpp);
2098 }
2099
2100 /* Return the tile dimensions in pixel units */
2101 static void intel_tile_dims(const struct drm_i915_private *dev_priv,
2102                             unsigned int *tile_width,
2103                             unsigned int *tile_height,
2104                             uint64_t fb_modifier,
2105                             unsigned int cpp)
2106 {
2107         unsigned int tile_width_bytes =
2108                 intel_tile_width_bytes(dev_priv, fb_modifier, cpp);
2109
2110         *tile_width = tile_width_bytes / cpp;
2111         *tile_height = intel_tile_size(dev_priv) / tile_width_bytes;
2112 }
2113
2114 unsigned int
2115 intel_fb_align_height(struct drm_device *dev, unsigned int height,
2116                       uint32_t pixel_format, uint64_t fb_modifier)
2117 {
2118         unsigned int cpp = drm_format_plane_cpp(pixel_format, 0);
2119         unsigned int tile_height = intel_tile_height(to_i915(dev), fb_modifier, cpp);
2120
2121         return ALIGN(height, tile_height);
2122 }
2123
2124 unsigned int intel_rotation_info_size(const struct intel_rotation_info *rot_info)
2125 {
2126         unsigned int size = 0;
2127         int i;
2128
2129         for (i = 0 ; i < ARRAY_SIZE(rot_info->plane); i++)
2130                 size += rot_info->plane[i].width * rot_info->plane[i].height;
2131
2132         return size;
2133 }
2134
2135 static void
2136 intel_fill_fb_ggtt_view(struct i915_ggtt_view *view,
2137                         const struct drm_framebuffer *fb,
2138                         unsigned int rotation)
2139 {
2140         view->type = I915_GGTT_VIEW_NORMAL;
2141         if (drm_rotation_90_or_270(rotation)) {
2142                 view->type = I915_GGTT_VIEW_ROTATED;
2143                 view->rotated = to_intel_framebuffer(fb)->rot_info;
2144         }
2145 }
2146
2147 static unsigned int intel_linear_alignment(const struct drm_i915_private *dev_priv)
2148 {
2149         if (INTEL_INFO(dev_priv)->gen >= 9)
2150                 return 256 * 1024;
2151         else if (IS_I965G(dev_priv) || IS_I965GM(dev_priv) ||
2152                  IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
2153                 return 128 * 1024;
2154         else if (INTEL_INFO(dev_priv)->gen >= 4)
2155                 return 4 * 1024;
2156         else
2157                 return 0;
2158 }
2159
2160 static unsigned int intel_surf_alignment(const struct drm_i915_private *dev_priv,
2161                                          uint64_t fb_modifier)
2162 {
2163         switch (fb_modifier) {
2164         case DRM_FORMAT_MOD_NONE:
2165                 return intel_linear_alignment(dev_priv);
2166         case I915_FORMAT_MOD_X_TILED:
2167                 if (INTEL_INFO(dev_priv)->gen >= 9)
2168                         return 256 * 1024;
2169                 return 0;
2170         case I915_FORMAT_MOD_Y_TILED:
2171         case I915_FORMAT_MOD_Yf_TILED:
2172                 return 1 * 1024 * 1024;
2173         default:
2174                 MISSING_CASE(fb_modifier);
2175                 return 0;
2176         }
2177 }
2178
2179 struct i915_vma *
2180 intel_pin_and_fence_fb_obj(struct drm_framebuffer *fb, unsigned int rotation)
2181 {
2182         struct drm_device *dev = fb->dev;
2183         struct drm_i915_private *dev_priv = to_i915(dev);
2184         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
2185         struct i915_ggtt_view view;
2186         struct i915_vma *vma;
2187         u32 alignment;
2188
2189         WARN_ON(!mutex_is_locked(&dev->struct_mutex));
2190
2191         alignment = intel_surf_alignment(dev_priv, fb->modifier);
2192
2193         intel_fill_fb_ggtt_view(&view, fb, rotation);
2194
2195         /* Note that the w/a also requires 64 PTE of padding following the
2196          * bo. We currently fill all unused PTE with the shadow page and so
2197          * we should always have valid PTE following the scanout preventing
2198          * the VT-d warning.
2199          */
2200         if (intel_scanout_needs_vtd_wa(dev_priv) && alignment < 256 * 1024)
2201                 alignment = 256 * 1024;
2202
2203         /*
2204          * Global gtt pte registers are special registers which actually forward
2205          * writes to a chunk of system memory. Which means that there is no risk
2206          * that the register values disappear as soon as we call
2207          * intel_runtime_pm_put(), so it is correct to wrap only the
2208          * pin/unpin/fence and not more.
2209          */
2210         intel_runtime_pm_get(dev_priv);
2211
2212         vma = i915_gem_object_pin_to_display_plane(obj, alignment, &view);
2213         if (IS_ERR(vma))
2214                 goto err;
2215
2216         if (i915_vma_is_map_and_fenceable(vma)) {
2217                 /* Install a fence for tiled scan-out. Pre-i965 always needs a
2218                  * fence, whereas 965+ only requires a fence if using
2219                  * framebuffer compression.  For simplicity, we always, when
2220                  * possible, install a fence as the cost is not that onerous.
2221                  *
2222                  * If we fail to fence the tiled scanout, then either the
2223                  * modeset will reject the change (which is highly unlikely as
2224                  * the affected systems, all but one, do not have unmappable
2225                  * space) or we will not be able to enable full powersaving
2226                  * techniques (also likely not to apply due to various limits
2227                  * FBC and the like impose on the size of the buffer, which
2228                  * presumably we violated anyway with this unmappable buffer).
2229                  * Anyway, it is presumably better to stumble onwards with
2230                  * something and try to run the system in a "less than optimal"
2231                  * mode that matches the user configuration.
2232                  */
2233                 if (i915_vma_get_fence(vma) == 0)
2234                         i915_vma_pin_fence(vma);
2235         }
2236
2237         i915_vma_get(vma);
2238 err:
2239         intel_runtime_pm_put(dev_priv);
2240         return vma;
2241 }
2242
2243 void intel_unpin_fb_vma(struct i915_vma *vma)
2244 {
2245         lockdep_assert_held(&vma->vm->i915->drm.struct_mutex);
2246
2247         i915_vma_unpin_fence(vma);
2248         i915_gem_object_unpin_from_display_plane(vma);
2249         i915_vma_put(vma);
2250 }
2251
2252 static int intel_fb_pitch(const struct drm_framebuffer *fb, int plane,
2253                           unsigned int rotation)
2254 {
2255         if (drm_rotation_90_or_270(rotation))
2256                 return to_intel_framebuffer(fb)->rotated[plane].pitch;
2257         else
2258                 return fb->pitches[plane];
2259 }
2260
2261 /*
2262  * Convert the x/y offsets into a linear offset.
2263  * Only valid with 0/180 degree rotation, which is fine since linear
2264  * offset is only used with linear buffers on pre-hsw and tiled buffers
2265  * with gen2/3, and 90/270 degree rotations isn't supported on any of them.
2266  */
2267 u32 intel_fb_xy_to_linear(int x, int y,
2268                           const struct intel_plane_state *state,
2269                           int plane)
2270 {
2271         const struct drm_framebuffer *fb = state->base.fb;
2272         unsigned int cpp = fb->format->cpp[plane];
2273         unsigned int pitch = fb->pitches[plane];
2274
2275         return y * pitch + x * cpp;
2276 }
2277
2278 /*
2279  * Add the x/y offsets derived from fb->offsets[] to the user
2280  * specified plane src x/y offsets. The resulting x/y offsets
2281  * specify the start of scanout from the beginning of the gtt mapping.
2282  */
2283 void intel_add_fb_offsets(int *x, int *y,
2284                           const struct intel_plane_state *state,
2285                           int plane)
2286
2287 {
2288         const struct intel_framebuffer *intel_fb = to_intel_framebuffer(state->base.fb);
2289         unsigned int rotation = state->base.rotation;
2290
2291         if (drm_rotation_90_or_270(rotation)) {
2292                 *x += intel_fb->rotated[plane].x;
2293                 *y += intel_fb->rotated[plane].y;
2294         } else {
2295                 *x += intel_fb->normal[plane].x;
2296                 *y += intel_fb->normal[plane].y;
2297         }
2298 }
2299
2300 /*
2301  * Input tile dimensions and pitch must already be
2302  * rotated to match x and y, and in pixel units.
2303  */
2304 static u32 _intel_adjust_tile_offset(int *x, int *y,
2305                                      unsigned int tile_width,
2306                                      unsigned int tile_height,
2307                                      unsigned int tile_size,
2308                                      unsigned int pitch_tiles,
2309                                      u32 old_offset,
2310                                      u32 new_offset)
2311 {
2312         unsigned int pitch_pixels = pitch_tiles * tile_width;
2313         unsigned int tiles;
2314
2315         WARN_ON(old_offset & (tile_size - 1));
2316         WARN_ON(new_offset & (tile_size - 1));
2317         WARN_ON(new_offset > old_offset);
2318
2319         tiles = (old_offset - new_offset) / tile_size;
2320
2321         *y += tiles / pitch_tiles * tile_height;
2322         *x += tiles % pitch_tiles * tile_width;
2323
2324         /* minimize x in case it got needlessly big */
2325         *y += *x / pitch_pixels * tile_height;
2326         *x %= pitch_pixels;
2327
2328         return new_offset;
2329 }
2330
2331 /*
2332  * Adjust the tile offset by moving the difference into
2333  * the x/y offsets.
2334  */
2335 static u32 intel_adjust_tile_offset(int *x, int *y,
2336                                     const struct intel_plane_state *state, int plane,
2337                                     u32 old_offset, u32 new_offset)
2338 {
2339         const struct drm_i915_private *dev_priv = to_i915(state->base.plane->dev);
2340         const struct drm_framebuffer *fb = state->base.fb;
2341         unsigned int cpp = fb->format->cpp[plane];
2342         unsigned int rotation = state->base.rotation;
2343         unsigned int pitch = intel_fb_pitch(fb, plane, rotation);
2344
2345         WARN_ON(new_offset > old_offset);
2346
2347         if (fb->modifier != DRM_FORMAT_MOD_NONE) {
2348                 unsigned int tile_size, tile_width, tile_height;
2349                 unsigned int pitch_tiles;
2350
2351                 tile_size = intel_tile_size(dev_priv);
2352                 intel_tile_dims(dev_priv, &tile_width, &tile_height,
2353                                 fb->modifier, cpp);
2354
2355                 if (drm_rotation_90_or_270(rotation)) {
2356                         pitch_tiles = pitch / tile_height;
2357                         swap(tile_width, tile_height);
2358                 } else {
2359                         pitch_tiles = pitch / (tile_width * cpp);
2360                 }
2361
2362                 _intel_adjust_tile_offset(x, y, tile_width, tile_height,
2363                                           tile_size, pitch_tiles,
2364                                           old_offset, new_offset);
2365         } else {
2366                 old_offset += *y * pitch + *x * cpp;
2367
2368                 *y = (old_offset - new_offset) / pitch;
2369                 *x = ((old_offset - new_offset) - *y * pitch) / cpp;
2370         }
2371
2372         return new_offset;
2373 }
2374
2375 /*
2376  * Computes the linear offset to the base tile and adjusts
2377  * x, y. bytes per pixel is assumed to be a power-of-two.
2378  *
2379  * In the 90/270 rotated case, x and y are assumed
2380  * to be already rotated to match the rotated GTT view, and
2381  * pitch is the tile_height aligned framebuffer height.
2382  *
2383  * This function is used when computing the derived information
2384  * under intel_framebuffer, so using any of that information
2385  * here is not allowed. Anything under drm_framebuffer can be
2386  * used. This is why the user has to pass in the pitch since it
2387  * is specified in the rotated orientation.
2388  */
2389 static u32 _intel_compute_tile_offset(const struct drm_i915_private *dev_priv,
2390                                       int *x, int *y,
2391                                       const struct drm_framebuffer *fb, int plane,
2392                                       unsigned int pitch,
2393                                       unsigned int rotation,
2394                                       u32 alignment)
2395 {
2396         uint64_t fb_modifier = fb->modifier;
2397         unsigned int cpp = fb->format->cpp[plane];
2398         u32 offset, offset_aligned;
2399
2400         if (alignment)
2401                 alignment--;
2402
2403         if (fb_modifier != DRM_FORMAT_MOD_NONE) {
2404                 unsigned int tile_size, tile_width, tile_height;
2405                 unsigned int tile_rows, tiles, pitch_tiles;
2406
2407                 tile_size = intel_tile_size(dev_priv);
2408                 intel_tile_dims(dev_priv, &tile_width, &tile_height,
2409                                 fb_modifier, cpp);
2410
2411                 if (drm_rotation_90_or_270(rotation)) {
2412                         pitch_tiles = pitch / tile_height;
2413                         swap(tile_width, tile_height);
2414                 } else {
2415                         pitch_tiles = pitch / (tile_width * cpp);
2416                 }
2417
2418                 tile_rows = *y / tile_height;
2419                 *y %= tile_height;
2420
2421                 tiles = *x / tile_width;
2422                 *x %= tile_width;
2423
2424                 offset = (tile_rows * pitch_tiles + tiles) * tile_size;
2425                 offset_aligned = offset & ~alignment;
2426
2427                 _intel_adjust_tile_offset(x, y, tile_width, tile_height,
2428                                           tile_size, pitch_tiles,
2429                                           offset, offset_aligned);
2430         } else {
2431                 offset = *y * pitch + *x * cpp;
2432                 offset_aligned = offset & ~alignment;
2433
2434                 *y = (offset & alignment) / pitch;
2435                 *x = ((offset & alignment) - *y * pitch) / cpp;
2436         }
2437
2438         return offset_aligned;
2439 }
2440
2441 u32 intel_compute_tile_offset(int *x, int *y,
2442                               const struct intel_plane_state *state,
2443                               int plane)
2444 {
2445         const struct drm_i915_private *dev_priv = to_i915(state->base.plane->dev);
2446         const struct drm_framebuffer *fb = state->base.fb;
2447         unsigned int rotation = state->base.rotation;
2448         int pitch = intel_fb_pitch(fb, plane, rotation);
2449         u32 alignment;
2450
2451         /* AUX_DIST needs only 4K alignment */
2452         if (fb->format->format == DRM_FORMAT_NV12 && plane == 1)
2453                 alignment = 4096;
2454         else
2455                 alignment = intel_surf_alignment(dev_priv, fb->modifier);
2456
2457         return _intel_compute_tile_offset(dev_priv, x, y, fb, plane, pitch,
2458                                           rotation, alignment);
2459 }
2460
2461 /* Convert the fb->offset[] linear offset into x/y offsets */
2462 static void intel_fb_offset_to_xy(int *x, int *y,
2463                                   const struct drm_framebuffer *fb, int plane)
2464 {
2465         unsigned int cpp = fb->format->cpp[plane];
2466         unsigned int pitch = fb->pitches[plane];
2467         u32 linear_offset = fb->offsets[plane];
2468
2469         *y = linear_offset / pitch;
2470         *x = linear_offset % pitch / cpp;
2471 }
2472
2473 static unsigned int intel_fb_modifier_to_tiling(uint64_t fb_modifier)
2474 {
2475         switch (fb_modifier) {
2476         case I915_FORMAT_MOD_X_TILED:
2477                 return I915_TILING_X;
2478         case I915_FORMAT_MOD_Y_TILED:
2479                 return I915_TILING_Y;
2480         default:
2481                 return I915_TILING_NONE;
2482         }
2483 }
2484
2485 static int
2486 intel_fill_fb_info(struct drm_i915_private *dev_priv,
2487                    struct drm_framebuffer *fb)
2488 {
2489         struct intel_framebuffer *intel_fb = to_intel_framebuffer(fb);
2490         struct intel_rotation_info *rot_info = &intel_fb->rot_info;
2491         u32 gtt_offset_rotated = 0;
2492         unsigned int max_size = 0;
2493         int i, num_planes = fb->format->num_planes;
2494         unsigned int tile_size = intel_tile_size(dev_priv);
2495
2496         for (i = 0; i < num_planes; i++) {
2497                 unsigned int width, height;
2498                 unsigned int cpp, size;
2499                 u32 offset;
2500                 int x, y;
2501
2502                 cpp = fb->format->cpp[i];
2503                 width = drm_framebuffer_plane_width(fb->width, fb, i);
2504                 height = drm_framebuffer_plane_height(fb->height, fb, i);
2505
2506                 intel_fb_offset_to_xy(&x, &y, fb, i);
2507
2508                 /*
2509                  * The fence (if used) is aligned to the start of the object
2510                  * so having the framebuffer wrap around across the edge of the
2511                  * fenced region doesn't really work. We have no API to configure
2512                  * the fence start offset within the object (nor could we probably
2513                  * on gen2/3). So it's just easier if we just require that the
2514                  * fb layout agrees with the fence layout. We already check that the
2515                  * fb stride matches the fence stride elsewhere.
2516                  */
2517                 if (i915_gem_object_is_tiled(intel_fb->obj) &&
2518                     (x + width) * cpp > fb->pitches[i]) {
2519                         DRM_DEBUG("bad fb plane %d offset: 0x%x\n",
2520                                   i, fb->offsets[i]);
2521                         return -EINVAL;
2522                 }
2523
2524                 /*
2525                  * First pixel of the framebuffer from
2526                  * the start of the normal gtt mapping.
2527                  */
2528                 intel_fb->normal[i].x = x;
2529                 intel_fb->normal[i].y = y;
2530
2531                 offset = _intel_compute_tile_offset(dev_priv, &x, &y,
2532                                                     fb, 0, fb->pitches[i],
2533                                                     DRM_ROTATE_0, tile_size);
2534                 offset /= tile_size;
2535
2536                 if (fb->modifier != DRM_FORMAT_MOD_NONE) {
2537                         unsigned int tile_width, tile_height;
2538                         unsigned int pitch_tiles;
2539                         struct drm_rect r;
2540
2541                         intel_tile_dims(dev_priv, &tile_width, &tile_height,
2542                                         fb->modifier, cpp);
2543
2544                         rot_info->plane[i].offset = offset;
2545                         rot_info->plane[i].stride = DIV_ROUND_UP(fb->pitches[i], tile_width * cpp);
2546                         rot_info->plane[i].width = DIV_ROUND_UP(x + width, tile_width);
2547                         rot_info->plane[i].height = DIV_ROUND_UP(y + height, tile_height);
2548
2549                         intel_fb->rotated[i].pitch =
2550                                 rot_info->plane[i].height * tile_height;
2551
2552                         /* how many tiles does this plane need */
2553                         size = rot_info->plane[i].stride * rot_info->plane[i].height;
2554                         /*
2555                          * If the plane isn't horizontally tile aligned,
2556                          * we need one more tile.
2557                          */
2558                         if (x != 0)
2559                                 size++;
2560
2561                         /* rotate the x/y offsets to match the GTT view */
2562                         r.x1 = x;
2563                         r.y1 = y;
2564                         r.x2 = x + width;
2565                         r.y2 = y + height;
2566                         drm_rect_rotate(&r,
2567                                         rot_info->plane[i].width * tile_width,
2568                                         rot_info->plane[i].height * tile_height,
2569                                         DRM_ROTATE_270);
2570                         x = r.x1;
2571                         y = r.y1;
2572
2573                         /* rotate the tile dimensions to match the GTT view */
2574                         pitch_tiles = intel_fb->rotated[i].pitch / tile_height;
2575                         swap(tile_width, tile_height);
2576
2577                         /*
2578                          * We only keep the x/y offsets, so push all of the
2579                          * gtt offset into the x/y offsets.
2580                          */
2581                         _intel_adjust_tile_offset(&x, &y,
2582                                                   tile_width, tile_height,
2583                                                   tile_size, pitch_tiles,
2584                                                   gtt_offset_rotated * tile_size, 0);
2585
2586                         gtt_offset_rotated += rot_info->plane[i].width * rot_info->plane[i].height;
2587
2588                         /*
2589                          * First pixel of the framebuffer from
2590                          * the start of the rotated gtt mapping.
2591                          */
2592                         intel_fb->rotated[i].x = x;
2593                         intel_fb->rotated[i].y = y;
2594                 } else {
2595                         size = DIV_ROUND_UP((y + height) * fb->pitches[i] +
2596                                             x * cpp, tile_size);
2597                 }
2598
2599                 /* how many tiles in total needed in the bo */
2600                 max_size = max(max_size, offset + size);
2601         }
2602
2603         if (max_size * tile_size > to_intel_framebuffer(fb)->obj->base.size) {
2604                 DRM_DEBUG("fb too big for bo (need %u bytes, have %zu bytes)\n",
2605                           max_size * tile_size, to_intel_framebuffer(fb)->obj->base.size);
2606                 return -EINVAL;
2607         }
2608
2609         return 0;
2610 }
2611
2612 static int i9xx_format_to_fourcc(int format)
2613 {
2614         switch (format) {
2615         case DISPPLANE_8BPP:
2616                 return DRM_FORMAT_C8;
2617         case DISPPLANE_BGRX555:
2618                 return DRM_FORMAT_XRGB1555;
2619         case DISPPLANE_BGRX565:
2620                 return DRM_FORMAT_RGB565;
2621         default:
2622         case DISPPLANE_BGRX888:
2623                 return DRM_FORMAT_XRGB8888;
2624         case DISPPLANE_RGBX888:
2625                 return DRM_FORMAT_XBGR8888;
2626         case DISPPLANE_BGRX101010:
2627                 return DRM_FORMAT_XRGB2101010;
2628         case DISPPLANE_RGBX101010:
2629                 return DRM_FORMAT_XBGR2101010;
2630         }
2631 }
2632
2633 static int skl_format_to_fourcc(int format, bool rgb_order, bool alpha)
2634 {
2635         switch (format) {
2636         case PLANE_CTL_FORMAT_RGB_565:
2637                 return DRM_FORMAT_RGB565;
2638         default:
2639         case PLANE_CTL_FORMAT_XRGB_8888:
2640                 if (rgb_order) {
2641                         if (alpha)
2642                                 return DRM_FORMAT_ABGR8888;
2643                         else
2644                                 return DRM_FORMAT_XBGR8888;
2645                 } else {
2646                         if (alpha)
2647                                 return DRM_FORMAT_ARGB8888;
2648                         else
2649                                 return DRM_FORMAT_XRGB8888;
2650                 }
2651         case PLANE_CTL_FORMAT_XRGB_2101010:
2652                 if (rgb_order)
2653                         return DRM_FORMAT_XBGR2101010;
2654                 else
2655                         return DRM_FORMAT_XRGB2101010;
2656         }
2657 }
2658
2659 static bool
2660 intel_alloc_initial_plane_obj(struct intel_crtc *crtc,
2661                               struct intel_initial_plane_config *plane_config)
2662 {
2663         struct drm_device *dev = crtc->base.dev;
2664         struct drm_i915_private *dev_priv = to_i915(dev);
2665         struct i915_ggtt *ggtt = &dev_priv->ggtt;
2666         struct drm_i915_gem_object *obj = NULL;
2667         struct drm_mode_fb_cmd2 mode_cmd = { 0 };
2668         struct drm_framebuffer *fb = &plane_config->fb->base;
2669         u32 base_aligned = round_down(plane_config->base, PAGE_SIZE);
2670         u32 size_aligned = round_up(plane_config->base + plane_config->size,
2671                                     PAGE_SIZE);
2672
2673         size_aligned -= base_aligned;
2674
2675         if (plane_config->size == 0)
2676                 return false;
2677
2678         /* If the FB is too big, just don't use it since fbdev is not very
2679          * important and we should probably use that space with FBC or other
2680          * features. */
2681         if (size_aligned * 2 > ggtt->stolen_usable_size)
2682                 return false;
2683
2684         mutex_lock(&dev->struct_mutex);
2685
2686         obj = i915_gem_object_create_stolen_for_preallocated(dev_priv,
2687                                                              base_aligned,
2688                                                              base_aligned,
2689                                                              size_aligned);
2690         if (!obj) {
2691                 mutex_unlock(&dev->struct_mutex);
2692                 return false;
2693         }
2694
2695         if (plane_config->tiling == I915_TILING_X)
2696                 obj->tiling_and_stride = fb->pitches[0] | I915_TILING_X;
2697
2698         mode_cmd.pixel_format = fb->format->format;
2699         mode_cmd.width = fb->width;
2700         mode_cmd.height = fb->height;
2701         mode_cmd.pitches[0] = fb->pitches[0];
2702         mode_cmd.modifier[0] = fb->modifier;
2703         mode_cmd.flags = DRM_MODE_FB_MODIFIERS;
2704
2705         if (intel_framebuffer_init(dev, to_intel_framebuffer(fb),
2706                                    &mode_cmd, obj)) {
2707                 DRM_DEBUG_KMS("intel fb init failed\n");
2708                 goto out_unref_obj;
2709         }
2710
2711         mutex_unlock(&dev->struct_mutex);
2712
2713         DRM_DEBUG_KMS("initial plane fb obj %p\n", obj);
2714         return true;
2715
2716 out_unref_obj:
2717         i915_gem_object_put(obj);
2718         mutex_unlock(&dev->struct_mutex);
2719         return false;
2720 }
2721
2722 /* Update plane->state->fb to match plane->fb after driver-internal updates */
2723 static void
2724 update_state_fb(struct drm_plane *plane)
2725 {
2726         if (plane->fb == plane->state->fb)
2727                 return;
2728
2729         if (plane->state->fb)
2730                 drm_framebuffer_unreference(plane->state->fb);
2731         plane->state->fb = plane->fb;
2732         if (plane->state->fb)
2733                 drm_framebuffer_reference(plane->state->fb);
2734 }
2735
2736 static void
2737 intel_find_initial_plane_obj(struct intel_crtc *intel_crtc,
2738                              struct intel_initial_plane_config *plane_config)
2739 {
2740         struct drm_device *dev = intel_crtc->base.dev;
2741         struct drm_i915_private *dev_priv = to_i915(dev);
2742         struct drm_crtc *c;
2743         struct drm_i915_gem_object *obj;
2744         struct drm_plane *primary = intel_crtc->base.primary;
2745         struct drm_plane_state *plane_state = primary->state;
2746         struct drm_crtc_state *crtc_state = intel_crtc->base.state;
2747         struct intel_plane *intel_plane = to_intel_plane(primary);
2748         struct intel_plane_state *intel_state =
2749                 to_intel_plane_state(plane_state);
2750         struct drm_framebuffer *fb;
2751
2752         if (!plane_config->fb)
2753                 return;
2754
2755         if (intel_alloc_initial_plane_obj(intel_crtc, plane_config)) {
2756                 fb = &plane_config->fb->base;
2757                 goto valid_fb;
2758         }
2759
2760         kfree(plane_config->fb);
2761
2762         /*
2763          * Failed to alloc the obj, check to see if we should share
2764          * an fb with another CRTC instead
2765          */
2766         for_each_crtc(dev, c) {
2767                 struct intel_plane_state *state;
2768
2769                 if (c == &intel_crtc->base)
2770                         continue;
2771
2772                 if (!to_intel_crtc(c)->active)
2773                         continue;
2774
2775                 state = to_intel_plane_state(c->primary->state);
2776                 if (!state->vma)
2777                         continue;
2778
2779                 if (intel_plane_ggtt_offset(state) == plane_config->base) {
2780                         fb = c->primary->fb;
2781                         drm_framebuffer_reference(fb);
2782                         goto valid_fb;
2783                 }
2784         }
2785
2786         /*
2787          * We've failed to reconstruct the BIOS FB.  Current display state
2788          * indicates that the primary plane is visible, but has a NULL FB,
2789          * which will lead to problems later if we don't fix it up.  The
2790          * simplest solution is to just disable the primary plane now and
2791          * pretend the BIOS never had it enabled.
2792          */
2793         plane_state->visible = false;
2794         crtc_state->plane_mask &= ~(1 << drm_plane_index(primary));
2795         intel_pre_disable_primary_noatomic(&intel_crtc->base);
2796         intel_plane->disable_plane(primary, &intel_crtc->base);
2797
2798         return;
2799
2800 valid_fb:
2801         mutex_lock(&dev->struct_mutex);
2802         intel_state->vma =
2803                 intel_pin_and_fence_fb_obj(fb, primary->state->rotation);
2804         mutex_unlock(&dev->struct_mutex);
2805         if (IS_ERR(intel_state->vma)) {
2806                 DRM_ERROR("failed to pin boot fb on pipe %d: %li\n",
2807                           intel_crtc->pipe, PTR_ERR(intel_state->vma));
2808
2809                 intel_state->vma = NULL;
2810                 drm_framebuffer_unreference(fb);
2811                 return;
2812         }
2813
2814         plane_state->src_x = 0;
2815         plane_state->src_y = 0;
2816         plane_state->src_w = fb->width << 16;
2817         plane_state->src_h = fb->height << 16;
2818
2819         plane_state->crtc_x = 0;
2820         plane_state->crtc_y = 0;
2821         plane_state->crtc_w = fb->width;
2822         plane_state->crtc_h = fb->height;
2823
2824         intel_state->base.src = drm_plane_state_src(plane_state);
2825         intel_state->base.dst = drm_plane_state_dest(plane_state);
2826
2827         obj = intel_fb_obj(fb);
2828         if (i915_gem_object_is_tiled(obj))
2829                 dev_priv->preserve_bios_swizzle = true;
2830
2831         drm_framebuffer_reference(fb);
2832         primary->fb = primary->state->fb = fb;
2833         primary->crtc = primary->state->crtc = &intel_crtc->base;
2834         intel_crtc->base.state->plane_mask |= (1 << drm_plane_index(primary));
2835         atomic_or(to_intel_plane(primary)->frontbuffer_bit,
2836                   &obj->frontbuffer_bits);
2837 }
2838
2839 static int skl_max_plane_width(const struct drm_framebuffer *fb, int plane,
2840                                unsigned int rotation)
2841 {
2842         int cpp = fb->format->cpp[plane];
2843
2844         switch (fb->modifier) {
2845         case DRM_FORMAT_MOD_NONE:
2846         case I915_FORMAT_MOD_X_TILED:
2847                 switch (cpp) {
2848                 case 8:
2849                         return 4096;
2850                 case 4:
2851                 case 2:
2852                 case 1:
2853                         return 8192;
2854                 default:
2855                         MISSING_CASE(cpp);
2856                         break;
2857                 }
2858                 break;
2859         case I915_FORMAT_MOD_Y_TILED:
2860         case I915_FORMAT_MOD_Yf_TILED:
2861                 switch (cpp) {
2862                 case 8:
2863                         return 2048;
2864                 case 4:
2865                         return 4096;
2866                 case 2:
2867                 case 1:
2868                         return 8192;
2869                 default:
2870                         MISSING_CASE(cpp);
2871                         break;
2872                 }
2873                 break;
2874         default:
2875                 MISSING_CASE(fb->modifier);
2876         }
2877
2878         return 2048;
2879 }
2880
2881 static int skl_check_main_surface(struct intel_plane_state *plane_state)
2882 {
2883         const struct drm_i915_private *dev_priv = to_i915(plane_state->base.plane->dev);
2884         const struct drm_framebuffer *fb = plane_state->base.fb;
2885         unsigned int rotation = plane_state->base.rotation;
2886         int x = plane_state->base.src.x1 >> 16;
2887         int y = plane_state->base.src.y1 >> 16;
2888         int w = drm_rect_width(&plane_state->base.src) >> 16;
2889         int h = drm_rect_height(&plane_state->base.src) >> 16;
2890         int max_width = skl_max_plane_width(fb, 0, rotation);
2891         int max_height = 4096;
2892         u32 alignment, offset, aux_offset = plane_state->aux.offset;
2893
2894         if (w > max_width || h > max_height) {
2895                 DRM_DEBUG_KMS("requested Y/RGB source size %dx%d too big (limit %dx%d)\n",
2896                               w, h, max_width, max_height);
2897                 return -EINVAL;
2898         }
2899
2900         intel_add_fb_offsets(&x, &y, plane_state, 0);
2901         offset = intel_compute_tile_offset(&x, &y, plane_state, 0);
2902
2903         alignment = intel_surf_alignment(dev_priv, fb->modifier);
2904
2905         /*
2906          * AUX surface offset is specified as the distance from the
2907          * main surface offset, and it must be non-negative. Make
2908          * sure that is what we will get.
2909          */
2910         if (offset > aux_offset)
2911                 offset = intel_adjust_tile_offset(&x, &y, plane_state, 0,
2912                                                   offset, aux_offset & ~(alignment - 1));
2913
2914         /*
2915          * When using an X-tiled surface, the plane blows up
2916          * if the x offset + width exceed the stride.
2917          *
2918          * TODO: linear and Y-tiled seem fine, Yf untested,
2919          */
2920         if (fb->modifier == I915_FORMAT_MOD_X_TILED) {
2921                 int cpp = fb->format->cpp[0];
2922
2923                 while ((x + w) * cpp > fb->pitches[0]) {
2924                         if (offset == 0) {
2925                                 DRM_DEBUG_KMS("Unable to find suitable display surface offset\n");
2926                                 return -EINVAL;
2927                         }
2928
2929                         offset = intel_adjust_tile_offset(&x, &y, plane_state, 0,
2930                                                           offset, offset - alignment);
2931                 }
2932         }
2933
2934         plane_state->main.offset = offset;
2935         plane_state->main.x = x;
2936         plane_state->main.y = y;
2937
2938         return 0;
2939 }
2940
2941 static int skl_check_nv12_aux_surface(struct intel_plane_state *plane_state)
2942 {
2943         const struct drm_framebuffer *fb = plane_state->base.fb;
2944         unsigned int rotation = plane_state->base.rotation;
2945         int max_width = skl_max_plane_width(fb, 1, rotation);
2946         int max_height = 4096;
2947         int x = plane_state->base.src.x1 >> 17;
2948         int y = plane_state->base.src.y1 >> 17;
2949         int w = drm_rect_width(&plane_state->base.src) >> 17;
2950         int h = drm_rect_height(&plane_state->base.src) >> 17;
2951         u32 offset;
2952
2953         intel_add_fb_offsets(&x, &y, plane_state, 1);
2954         offset = intel_compute_tile_offset(&x, &y, plane_state, 1);
2955
2956         /* FIXME not quite sure how/if these apply to the chroma plane */
2957         if (w > max_width || h > max_height) {
2958                 DRM_DEBUG_KMS("CbCr source size %dx%d too big (limit %dx%d)\n",
2959                               w, h, max_width, max_height);
2960                 return -EINVAL;
2961         }
2962
2963         plane_state->aux.offset = offset;
2964         plane_state->aux.x = x;
2965         plane_state->aux.y = y;
2966
2967         return 0;
2968 }
2969
2970 int skl_check_plane_surface(struct intel_plane_state *plane_state)
2971 {
2972         const struct drm_framebuffer *fb = plane_state->base.fb;
2973         unsigned int rotation = plane_state->base.rotation;
2974         int ret;
2975
2976         if (!plane_state->base.visible)
2977                 return 0;
2978
2979         /* Rotate src coordinates to match rotated GTT view */
2980         if (drm_rotation_90_or_270(rotation))
2981                 drm_rect_rotate(&plane_state->base.src,
2982                                 fb->width << 16, fb->height << 16,
2983                                 DRM_ROTATE_270);
2984
2985         /*
2986          * Handle the AUX surface first since
2987          * the main surface setup depends on it.
2988          */
2989         if (fb->format->format == DRM_FORMAT_NV12) {
2990                 ret = skl_check_nv12_aux_surface(plane_state);
2991                 if (ret)
2992                         return ret;
2993         } else {
2994                 plane_state->aux.offset = ~0xfff;
2995                 plane_state->aux.x = 0;
2996                 plane_state->aux.y = 0;
2997         }
2998
2999         ret = skl_check_main_surface(plane_state);
3000         if (ret)
3001                 return ret;
3002
3003         return 0;
3004 }
3005
3006 static void i9xx_update_primary_plane(struct drm_plane *primary,
3007                                       const struct intel_crtc_state *crtc_state,
3008                                       const struct intel_plane_state *plane_state)
3009 {
3010         struct drm_i915_private *dev_priv = to_i915(primary->dev);
3011         struct intel_crtc *intel_crtc = to_intel_crtc(crtc_state->base.crtc);
3012         struct drm_framebuffer *fb = plane_state->base.fb;
3013         int plane = intel_crtc->plane;
3014         u32 linear_offset;
3015         u32 dspcntr;
3016         i915_reg_t reg = DSPCNTR(plane);
3017         unsigned int rotation = plane_state->base.rotation;
3018         int x = plane_state->base.src.x1 >> 16;
3019         int y = plane_state->base.src.y1 >> 16;
3020
3021         dspcntr = DISPPLANE_GAMMA_ENABLE;
3022
3023         dspcntr |= DISPLAY_PLANE_ENABLE;
3024
3025         if (INTEL_GEN(dev_priv) < 4) {
3026                 if (intel_crtc->pipe == PIPE_B)
3027                         dspcntr |= DISPPLANE_SEL_PIPE_B;
3028
3029                 /* pipesrc and dspsize control the size that is scaled from,
3030                  * which should always be the user's requested size.
3031                  */
3032                 I915_WRITE(DSPSIZE(plane),
3033                            ((crtc_state->pipe_src_h - 1) << 16) |
3034                            (crtc_state->pipe_src_w - 1));
3035                 I915_WRITE(DSPPOS(plane), 0);
3036         } else if (IS_CHERRYVIEW(dev_priv) && plane == PLANE_B) {
3037                 I915_WRITE(PRIMSIZE(plane),
3038                            ((crtc_state->pipe_src_h - 1) << 16) |
3039                            (crtc_state->pipe_src_w - 1));
3040                 I915_WRITE(PRIMPOS(plane), 0);
3041                 I915_WRITE(PRIMCNSTALPHA(plane), 0);
3042         }
3043
3044         switch (fb->format->format) {
3045         case DRM_FORMAT_C8:
3046                 dspcntr |= DISPPLANE_8BPP;
3047                 break;
3048         case DRM_FORMAT_XRGB1555:
3049                 dspcntr |= DISPPLANE_BGRX555;
3050                 break;
3051         case DRM_FORMAT_RGB565:
3052                 dspcntr |= DISPPLANE_BGRX565;
3053                 break;
3054         case DRM_FORMAT_XRGB8888:
3055                 dspcntr |= DISPPLANE_BGRX888;
3056                 break;
3057         case DRM_FORMAT_XBGR8888:
3058                 dspcntr |= DISPPLANE_RGBX888;
3059                 break;
3060         case DRM_FORMAT_XRGB2101010:
3061                 dspcntr |= DISPPLANE_BGRX101010;
3062                 break;
3063         case DRM_FORMAT_XBGR2101010:
3064                 dspcntr |= DISPPLANE_RGBX101010;
3065                 break;
3066         default:
3067                 BUG();
3068         }
3069
3070         if (INTEL_GEN(dev_priv) >= 4 &&
3071             fb->modifier == I915_FORMAT_MOD_X_TILED)
3072                 dspcntr |= DISPPLANE_TILED;
3073
3074         if (rotation & DRM_ROTATE_180)
3075                 dspcntr |= DISPPLANE_ROTATE_180;
3076
3077         if (rotation & DRM_REFLECT_X)
3078                 dspcntr |= DISPPLANE_MIRROR;
3079
3080         if (IS_G4X(dev_priv))
3081                 dspcntr |= DISPPLANE_TRICKLE_FEED_DISABLE;
3082
3083         intel_add_fb_offsets(&x, &y, plane_state, 0);
3084
3085         if (INTEL_GEN(dev_priv) >= 4)
3086                 intel_crtc->dspaddr_offset =
3087                         intel_compute_tile_offset(&x, &y, plane_state, 0);
3088
3089         if (rotation & DRM_ROTATE_180) {
3090                 x += crtc_state->pipe_src_w - 1;
3091                 y += crtc_state->pipe_src_h - 1;
3092         } else if (rotation & DRM_REFLECT_X) {
3093                 x += crtc_state->pipe_src_w - 1;
3094         }
3095
3096         linear_offset = intel_fb_xy_to_linear(x, y, plane_state, 0);
3097
3098         if (INTEL_GEN(dev_priv) < 4)
3099                 intel_crtc->dspaddr_offset = linear_offset;
3100
3101         intel_crtc->adjusted_x = x;
3102         intel_crtc->adjusted_y = y;
3103
3104         I915_WRITE(reg, dspcntr);
3105
3106         I915_WRITE(DSPSTRIDE(plane), fb->pitches[0]);
3107         if (INTEL_GEN(dev_priv) >= 4) {
3108                 I915_WRITE(DSPSURF(plane),
3109                            intel_plane_ggtt_offset(plane_state) +
3110                            intel_crtc->dspaddr_offset);
3111                 I915_WRITE(DSPTILEOFF(plane), (y << 16) | x);
3112                 I915_WRITE(DSPLINOFF(plane), linear_offset);
3113         } else {
3114                 I915_WRITE(DSPADDR(plane),
3115                            intel_plane_ggtt_offset(plane_state) +
3116                            intel_crtc->dspaddr_offset);
3117         }
3118         POSTING_READ(reg);
3119 }
3120
3121 static void i9xx_disable_primary_plane(struct drm_plane *primary,
3122                                        struct drm_crtc *crtc)
3123 {
3124         struct drm_device *dev = crtc->dev;
3125         struct drm_i915_private *dev_priv = to_i915(dev);
3126         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3127         int plane = intel_crtc->plane;
3128
3129         I915_WRITE(DSPCNTR(plane), 0);
3130         if (INTEL_INFO(dev_priv)->gen >= 4)
3131                 I915_WRITE(DSPSURF(plane), 0);
3132         else
3133                 I915_WRITE(DSPADDR(plane), 0);
3134         POSTING_READ(DSPCNTR(plane));
3135 }
3136
3137 static void ironlake_update_primary_plane(struct drm_plane *primary,
3138                                           const struct intel_crtc_state *crtc_state,
3139                                           const struct intel_plane_state *plane_state)
3140 {
3141         struct drm_device *dev = primary->dev;
3142         struct drm_i915_private *dev_priv = to_i915(dev);
3143         struct intel_crtc *intel_crtc = to_intel_crtc(crtc_state->base.crtc);
3144         struct drm_framebuffer *fb = plane_state->base.fb;
3145         int plane = intel_crtc->plane;
3146         u32 linear_offset;
3147         u32 dspcntr;
3148         i915_reg_t reg = DSPCNTR(plane);
3149         unsigned int rotation = plane_state->base.rotation;
3150         int x = plane_state->base.src.x1 >> 16;
3151         int y = plane_state->base.src.y1 >> 16;
3152
3153         dspcntr = DISPPLANE_GAMMA_ENABLE;
3154         dspcntr |= DISPLAY_PLANE_ENABLE;
3155
3156         if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv))
3157                 dspcntr |= DISPPLANE_PIPE_CSC_ENABLE;
3158
3159         switch (fb->format->format) {
3160         case DRM_FORMAT_C8:
3161                 dspcntr |= DISPPLANE_8BPP;
3162                 break;
3163         case DRM_FORMAT_RGB565:
3164                 dspcntr |= DISPPLANE_BGRX565;
3165                 break;
3166         case DRM_FORMAT_XRGB8888:
3167                 dspcntr |= DISPPLANE_BGRX888;
3168                 break;
3169         case DRM_FORMAT_XBGR8888:
3170                 dspcntr |= DISPPLANE_RGBX888;
3171                 break;
3172         case DRM_FORMAT_XRGB2101010:
3173                 dspcntr |= DISPPLANE_BGRX101010;
3174                 break;
3175         case DRM_FORMAT_XBGR2101010:
3176                 dspcntr |= DISPPLANE_RGBX101010;
3177                 break;
3178         default:
3179                 BUG();
3180         }
3181
3182         if (fb->modifier == I915_FORMAT_MOD_X_TILED)
3183                 dspcntr |= DISPPLANE_TILED;
3184
3185         if (rotation & DRM_ROTATE_180)
3186                 dspcntr |= DISPPLANE_ROTATE_180;
3187
3188         if (!IS_HASWELL(dev_priv) && !IS_BROADWELL(dev_priv))
3189                 dspcntr |= DISPPLANE_TRICKLE_FEED_DISABLE;
3190
3191         intel_add_fb_offsets(&x, &y, plane_state, 0);
3192
3193         intel_crtc->dspaddr_offset =
3194                 intel_compute_tile_offset(&x, &y, plane_state, 0);
3195
3196         /* HSW+ does this automagically in hardware */
3197         if (!IS_HASWELL(dev_priv) && !IS_BROADWELL(dev_priv) &&
3198             rotation & DRM_ROTATE_180) {
3199                 x += crtc_state->pipe_src_w - 1;
3200                 y += crtc_state->pipe_src_h - 1;
3201         }
3202
3203         linear_offset = intel_fb_xy_to_linear(x, y, plane_state, 0);
3204
3205         intel_crtc->adjusted_x = x;
3206         intel_crtc->adjusted_y = y;
3207
3208         I915_WRITE(reg, dspcntr);
3209
3210         I915_WRITE(DSPSTRIDE(plane), fb->pitches[0]);
3211         I915_WRITE(DSPSURF(plane),
3212                    intel_plane_ggtt_offset(plane_state) +
3213                    intel_crtc->dspaddr_offset);
3214         if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv)) {
3215                 I915_WRITE(DSPOFFSET(plane), (y << 16) | x);
3216         } else {
3217                 I915_WRITE(DSPTILEOFF(plane), (y << 16) | x);
3218                 I915_WRITE(DSPLINOFF(plane), linear_offset);
3219         }
3220         POSTING_READ(reg);
3221 }
3222
3223 u32 intel_fb_stride_alignment(const struct drm_i915_private *dev_priv,
3224                               uint64_t fb_modifier, uint32_t pixel_format)
3225 {
3226         if (fb_modifier == DRM_FORMAT_MOD_NONE) {
3227                 return 64;
3228         } else {
3229                 int cpp = drm_format_plane_cpp(pixel_format, 0);
3230
3231                 return intel_tile_width_bytes(dev_priv, fb_modifier, cpp);
3232         }
3233 }
3234
3235 static void skl_detach_scaler(struct intel_crtc *intel_crtc, int id)
3236 {
3237         struct drm_device *dev = intel_crtc->base.dev;
3238         struct drm_i915_private *dev_priv = to_i915(dev);
3239
3240         I915_WRITE(SKL_PS_CTRL(intel_crtc->pipe, id), 0);
3241         I915_WRITE(SKL_PS_WIN_POS(intel_crtc->pipe, id), 0);
3242         I915_WRITE(SKL_PS_WIN_SZ(intel_crtc->pipe, id), 0);
3243 }
3244
3245 /*
3246  * This function detaches (aka. unbinds) unused scalers in hardware
3247  */
3248 static void skl_detach_scalers(struct intel_crtc *intel_crtc)
3249 {
3250         struct intel_crtc_scaler_state *scaler_state;
3251         int i;
3252
3253         scaler_state = &intel_crtc->config->scaler_state;
3254
3255         /* loop through and disable scalers that aren't in use */
3256         for (i = 0; i < intel_crtc->num_scalers; i++) {
3257                 if (!scaler_state->scalers[i].in_use)
3258                         skl_detach_scaler(intel_crtc, i);
3259         }
3260 }
3261
3262 u32 skl_plane_stride(const struct drm_framebuffer *fb, int plane,
3263                      unsigned int rotation)
3264 {
3265         const struct drm_i915_private *dev_priv = to_i915(fb->dev);
3266         u32 stride = intel_fb_pitch(fb, plane, rotation);
3267
3268         /*
3269          * The stride is either expressed as a multiple of 64 bytes chunks for
3270          * linear buffers or in number of tiles for tiled buffers.
3271          */
3272         if (drm_rotation_90_or_270(rotation)) {
3273                 int cpp = fb->format->cpp[plane];
3274
3275                 stride /= intel_tile_height(dev_priv, fb->modifier, cpp);
3276         } else {
3277                 stride /= intel_fb_stride_alignment(dev_priv, fb->modifier,
3278                                                     fb->format->format);
3279         }
3280
3281         return stride;
3282 }
3283
3284 u32 skl_plane_ctl_format(uint32_t pixel_format)
3285 {
3286         switch (pixel_format) {
3287         case DRM_FORMAT_C8:
3288                 return PLANE_CTL_FORMAT_INDEXED;
3289         case DRM_FORMAT_RGB565:
3290                 return PLANE_CTL_FORMAT_RGB_565;
3291         case DRM_FORMAT_XBGR8888:
3292                 return PLANE_CTL_FORMAT_XRGB_8888 | PLANE_CTL_ORDER_RGBX;
3293         case DRM_FORMAT_XRGB8888:
3294                 return PLANE_CTL_FORMAT_XRGB_8888;
3295         /*
3296          * XXX: For ARBG/ABGR formats we default to expecting scanout buffers
3297          * to be already pre-multiplied. We need to add a knob (or a different
3298          * DRM_FORMAT) for user-space to configure that.
3299          */
3300         case DRM_FORMAT_ABGR8888:
3301                 return PLANE_CTL_FORMAT_XRGB_8888 | PLANE_CTL_ORDER_RGBX |
3302                         PLANE_CTL_ALPHA_SW_PREMULTIPLY;
3303         case DRM_FORMAT_ARGB8888:
3304                 return PLANE_CTL_FORMAT_XRGB_8888 |
3305                         PLANE_CTL_ALPHA_SW_PREMULTIPLY;
3306         case DRM_FORMAT_XRGB2101010:
3307                 return PLANE_CTL_FORMAT_XRGB_2101010;
3308         case DRM_FORMAT_XBGR2101010:
3309                 return PLANE_CTL_ORDER_RGBX | PLANE_CTL_FORMAT_XRGB_2101010;
3310         case DRM_FORMAT_YUYV:
3311                 return PLANE_CTL_FORMAT_YUV422 | PLANE_CTL_YUV422_YUYV;
3312         case DRM_FORMAT_YVYU:
3313                 return PLANE_CTL_FORMAT_YUV422 | PLANE_CTL_YUV422_YVYU;
3314         case DRM_FORMAT_UYVY:
3315                 return PLANE_CTL_FORMAT_YUV422 | PLANE_CTL_YUV422_UYVY;
3316         case DRM_FORMAT_VYUY:
3317                 return PLANE_CTL_FORMAT_YUV422 | PLANE_CTL_YUV422_VYUY;
3318         default:
3319                 MISSING_CASE(pixel_format);
3320         }
3321
3322         return 0;
3323 }
3324
3325 u32 skl_plane_ctl_tiling(uint64_t fb_modifier)
3326 {
3327         switch (fb_modifier) {
3328         case DRM_FORMAT_MOD_NONE:
3329                 break;
3330         case I915_FORMAT_MOD_X_TILED:
3331                 return PLANE_CTL_TILED_X;
3332         case I915_FORMAT_MOD_Y_TILED:
3333                 return PLANE_CTL_TILED_Y;
3334         case I915_FORMAT_MOD_Yf_TILED:
3335                 return PLANE_CTL_TILED_YF;
3336         default:
3337                 MISSING_CASE(fb_modifier);
3338         }
3339
3340         return 0;
3341 }
3342
3343 u32 skl_plane_ctl_rotation(unsigned int rotation)
3344 {
3345         switch (rotation) {
3346         case DRM_ROTATE_0:
3347                 break;
3348         /*
3349          * DRM_ROTATE_ is counter clockwise to stay compatible with Xrandr
3350          * while i915 HW rotation is clockwise, thats why this swapping.
3351          */
3352         case DRM_ROTATE_90:
3353                 return PLANE_CTL_ROTATE_270;
3354         case DRM_ROTATE_180:
3355                 return PLANE_CTL_ROTATE_180;
3356         case DRM_ROTATE_270:
3357                 return PLANE_CTL_ROTATE_90;
3358         default:
3359                 MISSING_CASE(rotation);
3360         }
3361
3362         return 0;
3363 }
3364
3365 static void skylake_update_primary_plane(struct drm_plane *plane,
3366                                          const struct intel_crtc_state *crtc_state,
3367                                          const struct intel_plane_state *plane_state)
3368 {
3369         struct drm_device *dev = plane->dev;
3370         struct drm_i915_private *dev_priv = to_i915(dev);
3371         struct intel_crtc *intel_crtc = to_intel_crtc(crtc_state->base.crtc);
3372         struct drm_framebuffer *fb = plane_state->base.fb;
3373         enum plane_id plane_id = to_intel_plane(plane)->id;
3374         enum pipe pipe = to_intel_plane(plane)->pipe;
3375         u32 plane_ctl;
3376         unsigned int rotation = plane_state->base.rotation;
3377         u32 stride = skl_plane_stride(fb, 0, rotation);
3378         u32 surf_addr = plane_state->main.offset;
3379         int scaler_id = plane_state->scaler_id;
3380         int src_x = plane_state->main.x;
3381         int src_y = plane_state->main.y;
3382         int src_w = drm_rect_width(&plane_state->base.src) >> 16;
3383         int src_h = drm_rect_height(&plane_state->base.src) >> 16;
3384         int dst_x = plane_state->base.dst.x1;
3385         int dst_y = plane_state->base.dst.y1;
3386         int dst_w = drm_rect_width(&plane_state->base.dst);
3387         int dst_h = drm_rect_height(&plane_state->base.dst);
3388
3389         plane_ctl = PLANE_CTL_ENABLE |
3390                     PLANE_CTL_PIPE_GAMMA_ENABLE |
3391                     PLANE_CTL_PIPE_CSC_ENABLE;
3392
3393         plane_ctl |= skl_plane_ctl_format(fb->format->format);
3394         plane_ctl |= skl_plane_ctl_tiling(fb->modifier);
3395         plane_ctl |= PLANE_CTL_PLANE_GAMMA_DISABLE;
3396         plane_ctl |= skl_plane_ctl_rotation(rotation);
3397
3398         /* Sizes are 0 based */
3399         src_w--;
3400         src_h--;
3401         dst_w--;
3402         dst_h--;
3403
3404         intel_crtc->dspaddr_offset = surf_addr;
3405
3406         intel_crtc->adjusted_x = src_x;
3407         intel_crtc->adjusted_y = src_y;
3408
3409         I915_WRITE(PLANE_CTL(pipe, plane_id), plane_ctl);
3410         I915_WRITE(PLANE_OFFSET(pipe, plane_id), (src_y << 16) | src_x);
3411         I915_WRITE(PLANE_STRIDE(pipe, plane_id), stride);
3412         I915_WRITE(PLANE_SIZE(pipe, plane_id), (src_h << 16) | src_w);
3413
3414         if (scaler_id >= 0) {
3415                 uint32_t ps_ctrl = 0;
3416
3417                 WARN_ON(!dst_w || !dst_h);
3418                 ps_ctrl = PS_SCALER_EN | PS_PLANE_SEL(plane_id) |
3419                         crtc_state->scaler_state.scalers[scaler_id].mode;
3420                 I915_WRITE(SKL_PS_CTRL(pipe, scaler_id), ps_ctrl);
3421                 I915_WRITE(SKL_PS_PWR_GATE(pipe, scaler_id), 0);
3422                 I915_WRITE(SKL_PS_WIN_POS(pipe, scaler_id), (dst_x << 16) | dst_y);
3423                 I915_WRITE(SKL_PS_WIN_SZ(pipe, scaler_id), (dst_w << 16) | dst_h);
3424                 I915_WRITE(PLANE_POS(pipe, plane_id), 0);
3425         } else {
3426                 I915_WRITE(PLANE_POS(pipe, plane_id), (dst_y << 16) | dst_x);
3427         }
3428
3429         I915_WRITE(PLANE_SURF(pipe, plane_id),
3430                    intel_plane_ggtt_offset(plane_state) + surf_addr);
3431
3432         POSTING_READ(PLANE_SURF(pipe, plane_id));
3433 }
3434
3435 static void skylake_disable_primary_plane(struct drm_plane *primary,
3436                                           struct drm_crtc *crtc)
3437 {
3438         struct drm_device *dev = crtc->dev;
3439         struct drm_i915_private *dev_priv = to_i915(dev);
3440         enum plane_id plane_id = to_intel_plane(primary)->id;
3441         enum pipe pipe = to_intel_plane(primary)->pipe;
3442
3443         I915_WRITE(PLANE_CTL(pipe, plane_id), 0);
3444         I915_WRITE(PLANE_SURF(pipe, plane_id), 0);
3445         POSTING_READ(PLANE_SURF(pipe, plane_id));
3446 }
3447
3448 /* Assume fb object is pinned & idle & fenced and just update base pointers */
3449 static int
3450 intel_pipe_set_base_atomic(struct drm_crtc *crtc, struct drm_framebuffer *fb,
3451                            int x, int y, enum mode_set_atomic state)
3452 {
3453         /* Support for kgdboc is disabled, this needs a major rework. */
3454         DRM_ERROR("legacy panic handler not supported any more.\n");
3455
3456         return -ENODEV;
3457 }
3458
3459 static void intel_complete_page_flips(struct drm_i915_private *dev_priv)
3460 {
3461         struct intel_crtc *crtc;
3462
3463         for_each_intel_crtc(&dev_priv->drm, crtc)
3464                 intel_finish_page_flip_cs(dev_priv, crtc->pipe);
3465 }
3466
3467 static void intel_update_primary_planes(struct drm_device *dev)
3468 {
3469         struct drm_crtc *crtc;
3470
3471         for_each_crtc(dev, crtc) {
3472                 struct intel_plane *plane = to_intel_plane(crtc->primary);
3473                 struct intel_plane_state *plane_state =
3474                         to_intel_plane_state(plane->base.state);
3475
3476                 if (plane_state->base.visible)
3477                         plane->update_plane(&plane->base,
3478                                             to_intel_crtc_state(crtc->state),
3479                                             plane_state);
3480         }
3481 }
3482
3483 static int
3484 __intel_display_resume(struct drm_device *dev,
3485                        struct drm_atomic_state *state)
3486 {
3487         struct drm_crtc_state *crtc_state;
3488         struct drm_crtc *crtc;
3489         int i, ret;
3490
3491         intel_modeset_setup_hw_state(dev);
3492         i915_redisable_vga(to_i915(dev));
3493
3494         if (!state)
3495                 return 0;
3496
3497         for_each_crtc_in_state(state, crtc, crtc_state, i) {
3498                 /*
3499                  * Force recalculation even if we restore
3500                  * current state. With fast modeset this may not result
3501                  * in a modeset when the state is compatible.
3502                  */
3503                 crtc_state->mode_changed = true;
3504         }
3505
3506         /* ignore any reset values/BIOS leftovers in the WM registers */
3507         to_intel_atomic_state(state)->skip_intermediate_wm = true;
3508
3509         ret = drm_atomic_commit(state);
3510
3511         WARN_ON(ret == -EDEADLK);
3512         return ret;
3513 }
3514
3515 static bool gpu_reset_clobbers_display(struct drm_i915_private *dev_priv)
3516 {
3517         return intel_has_gpu_reset(dev_priv) &&
3518                 INTEL_GEN(dev_priv) < 5 && !IS_G4X(dev_priv);
3519 }
3520
3521 void intel_prepare_reset(struct drm_i915_private *dev_priv)
3522 {
3523         struct drm_device *dev = &dev_priv->drm;
3524         struct drm_modeset_acquire_ctx *ctx = &dev_priv->reset_ctx;
3525         struct drm_atomic_state *state;
3526         int ret;
3527
3528         /*
3529          * Need mode_config.mutex so that we don't
3530          * trample ongoing ->detect() and whatnot.
3531          */
3532         mutex_lock(&dev->mode_config.mutex);
3533         drm_modeset_acquire_init(ctx, 0);
3534         while (1) {
3535                 ret = drm_modeset_lock_all_ctx(dev, ctx);
3536                 if (ret != -EDEADLK)
3537                         break;
3538
3539                 drm_modeset_backoff(ctx);
3540         }
3541
3542         /* reset doesn't touch the display, but flips might get nuked anyway, */
3543         if (!i915.force_reset_modeset_test &&
3544             !gpu_reset_clobbers_display(dev_priv))
3545                 return;
3546
3547         /*
3548          * Disabling the crtcs gracefully seems nicer. Also the
3549          * g33 docs say we should at least disable all the planes.
3550          */
3551         state = drm_atomic_helper_duplicate_state(dev, ctx);
3552         if (IS_ERR(state)) {
3553                 ret = PTR_ERR(state);
3554                 DRM_ERROR("Duplicating state failed with %i\n", ret);
3555                 return;
3556         }
3557
3558         ret = drm_atomic_helper_disable_all(dev, ctx);
3559         if (ret) {
3560                 DRM_ERROR("Suspending crtc's failed with %i\n", ret);
3561                 drm_atomic_state_put(state);
3562                 return;
3563         }
3564
3565         dev_priv->modeset_restore_state = state;
3566         state->acquire_ctx = ctx;
3567 }
3568
3569 void intel_finish_reset(struct drm_i915_private *dev_priv)
3570 {
3571         struct drm_device *dev = &dev_priv->drm;
3572         struct drm_modeset_acquire_ctx *ctx = &dev_priv->reset_ctx;
3573         struct drm_atomic_state *state = dev_priv->modeset_restore_state;
3574         int ret;
3575
3576         /*
3577          * Flips in the rings will be nuked by the reset,
3578          * so complete all pending flips so that user space
3579          * will get its events and not get stuck.
3580          */
3581         intel_complete_page_flips(dev_priv);
3582
3583         dev_priv->modeset_restore_state = NULL;
3584
3585         /* reset doesn't touch the display */
3586         if (!gpu_reset_clobbers_display(dev_priv)) {
3587                 if (!state) {
3588                         /*
3589                          * Flips in the rings have been nuked by the reset,
3590                          * so update the base address of all primary
3591                          * planes to the the last fb to make sure we're
3592                          * showing the correct fb after a reset.
3593                          *
3594                          * FIXME: Atomic will make this obsolete since we won't schedule
3595                          * CS-based flips (which might get lost in gpu resets) any more.
3596                          */
3597                         intel_update_primary_planes(dev);
3598                 } else {
3599                         ret = __intel_display_resume(dev, state);
3600                         if (ret)
3601                                 DRM_ERROR("Restoring old state failed with %i\n", ret);
3602                 }
3603         } else {
3604                 /*
3605                  * The display has been reset as well,
3606                  * so need a full re-initialization.
3607                  */
3608                 intel_runtime_pm_disable_interrupts(dev_priv);
3609                 intel_runtime_pm_enable_interrupts(dev_priv);
3610
3611                 intel_pps_unlock_regs_wa(dev_priv);
3612                 intel_modeset_init_hw(dev);
3613
3614                 spin_lock_irq(&dev_priv->irq_lock);
3615                 if (dev_priv->display.hpd_irq_setup)
3616                         dev_priv->display.hpd_irq_setup(dev_priv);
3617                 spin_unlock_irq(&dev_priv->irq_lock);
3618
3619                 ret = __intel_display_resume(dev, state);
3620                 if (ret)
3621                         DRM_ERROR("Restoring old state failed with %i\n", ret);
3622
3623                 intel_hpd_init(dev_priv);
3624         }
3625
3626         if (state)
3627                 drm_atomic_state_put(state);
3628         drm_modeset_drop_locks(ctx);
3629         drm_modeset_acquire_fini(ctx);
3630         mutex_unlock(&dev->mode_config.mutex);
3631 }
3632
3633 static bool abort_flip_on_reset(struct intel_crtc *crtc)
3634 {
3635         struct i915_gpu_error *error = &to_i915(crtc->base.dev)->gpu_error;
3636
3637         if (i915_reset_in_progress(error))
3638                 return true;
3639
3640         if (crtc->reset_count != i915_reset_count(error))
3641                 return true;
3642
3643         return false;
3644 }
3645
3646 static bool intel_crtc_has_pending_flip(struct drm_crtc *crtc)
3647 {
3648         struct drm_device *dev = crtc->dev;
3649         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3650         bool pending;
3651
3652         if (abort_flip_on_reset(intel_crtc))
3653                 return false;
3654
3655         spin_lock_irq(&dev->event_lock);
3656         pending = to_intel_crtc(crtc)->flip_work != NULL;
3657         spin_unlock_irq(&dev->event_lock);
3658
3659         return pending;
3660 }
3661
3662 static void intel_update_pipe_config(struct intel_crtc *crtc,
3663                                      struct intel_crtc_state *old_crtc_state)
3664 {
3665         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
3666         struct intel_crtc_state *pipe_config =
3667                 to_intel_crtc_state(crtc->base.state);
3668
3669         /* drm_atomic_helper_update_legacy_modeset_state might not be called. */
3670         crtc->base.mode = crtc->base.state->mode;
3671
3672         /*
3673          * Update pipe size and adjust fitter if needed: the reason for this is
3674          * that in compute_mode_changes we check the native mode (not the pfit
3675          * mode) to see if we can flip rather than do a full mode set. In the
3676          * fastboot case, we'll flip, but if we don't update the pipesrc and
3677          * pfit state, we'll end up with a big fb scanned out into the wrong
3678          * sized surface.
3679          */
3680
3681         I915_WRITE(PIPESRC(crtc->pipe),
3682                    ((pipe_config->pipe_src_w - 1) << 16) |
3683                    (pipe_config->pipe_src_h - 1));
3684
3685         /* on skylake this is done by detaching scalers */
3686         if (INTEL_GEN(dev_priv) >= 9) {
3687                 skl_detach_scalers(crtc);
3688
3689                 if (pipe_config->pch_pfit.enabled)
3690                         skylake_pfit_enable(crtc);
3691         } else if (HAS_PCH_SPLIT(dev_priv)) {
3692                 if (pipe_config->pch_pfit.enabled)
3693                         ironlake_pfit_enable(crtc);
3694                 else if (old_crtc_state->pch_pfit.enabled)
3695                         ironlake_pfit_disable(crtc, true);
3696         }
3697 }
3698
3699 static void intel_fdi_normal_train(struct drm_crtc *crtc)
3700 {
3701         struct drm_device *dev = crtc->dev;
3702         struct drm_i915_private *dev_priv = to_i915(dev);
3703         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3704         int pipe = intel_crtc->pipe;
3705         i915_reg_t reg;
3706         u32 temp;
3707
3708         /* enable normal train */
3709         reg = FDI_TX_CTL(pipe);
3710         temp = I915_READ(reg);
3711         if (IS_IVYBRIDGE(dev_priv)) {
3712                 temp &= ~FDI_LINK_TRAIN_NONE_IVB;
3713                 temp |= FDI_LINK_TRAIN_NONE_IVB | FDI_TX_ENHANCE_FRAME_ENABLE;
3714         } else {
3715                 temp &= ~FDI_LINK_TRAIN_NONE;
3716                 temp |= FDI_LINK_TRAIN_NONE | FDI_TX_ENHANCE_FRAME_ENABLE;
3717         }
3718         I915_WRITE(reg, temp);
3719
3720         reg = FDI_RX_CTL(pipe);
3721         temp = I915_READ(reg);
3722         if (HAS_PCH_CPT(dev_priv)) {
3723                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
3724                 temp |= FDI_LINK_TRAIN_NORMAL_CPT;
3725         } else {
3726                 temp &= ~FDI_LINK_TRAIN_NONE;
3727                 temp |= FDI_LINK_TRAIN_NONE;
3728         }
3729         I915_WRITE(reg, temp | FDI_RX_ENHANCE_FRAME_ENABLE);
3730
3731         /* wait one idle pattern time */
3732         POSTING_READ(reg);
3733         udelay(1000);
3734
3735         /* IVB wants error correction enabled */
3736         if (IS_IVYBRIDGE(dev_priv))
3737                 I915_WRITE(reg, I915_READ(reg) | FDI_FS_ERRC_ENABLE |
3738                            FDI_FE_ERRC_ENABLE);
3739 }
3740
3741 /* The FDI link training functions for ILK/Ibexpeak. */
3742 static void ironlake_fdi_link_train(struct drm_crtc *crtc)
3743 {
3744         struct drm_device *dev = crtc->dev;
3745         struct drm_i915_private *dev_priv = to_i915(dev);
3746         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3747         int pipe = intel_crtc->pipe;
3748         i915_reg_t reg;
3749         u32 temp, tries;
3750
3751         /* FDI needs bits from pipe first */
3752         assert_pipe_enabled(dev_priv, pipe);
3753
3754         /* Train 1: umask FDI RX Interrupt symbol_lock and bit_lock bit
3755            for train result */
3756         reg = FDI_RX_IMR(pipe);
3757         temp = I915_READ(reg);
3758         temp &= ~FDI_RX_SYMBOL_LOCK;
3759         temp &= ~FDI_RX_BIT_LOCK;
3760         I915_WRITE(reg, temp);
3761         I915_READ(reg);
3762         udelay(150);
3763
3764         /* enable CPU FDI TX and PCH FDI RX */
3765         reg = FDI_TX_CTL(pipe);
3766         temp = I915_READ(reg);
3767         temp &= ~FDI_DP_PORT_WIDTH_MASK;
3768         temp |= FDI_DP_PORT_WIDTH(intel_crtc->config->fdi_lanes);
3769         temp &= ~FDI_LINK_TRAIN_NONE;
3770         temp |= FDI_LINK_TRAIN_PATTERN_1;
3771         I915_WRITE(reg, temp | FDI_TX_ENABLE);
3772
3773         reg = FDI_RX_CTL(pipe);
3774         temp = I915_READ(reg);
3775         temp &= ~FDI_LINK_TRAIN_NONE;
3776         temp |= FDI_LINK_TRAIN_PATTERN_1;
3777         I915_WRITE(reg, temp | FDI_RX_ENABLE);
3778
3779         POSTING_READ(reg);
3780         udelay(150);
3781
3782         /* Ironlake workaround, enable clock pointer after FDI enable*/
3783         I915_WRITE(FDI_RX_CHICKEN(pipe), FDI_RX_PHASE_SYNC_POINTER_OVR);
3784         I915_WRITE(FDI_RX_CHICKEN(pipe), FDI_RX_PHASE_SYNC_POINTER_OVR |
3785                    FDI_RX_PHASE_SYNC_POINTER_EN);
3786
3787         reg = FDI_RX_IIR(pipe);
3788         for (tries = 0; tries < 5; tries++) {
3789                 temp = I915_READ(reg);
3790                 DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
3791
3792                 if ((temp & FDI_RX_BIT_LOCK)) {
3793                         DRM_DEBUG_KMS("FDI train 1 done.\n");
3794                         I915_WRITE(reg, temp | FDI_RX_BIT_LOCK);
3795                         break;
3796                 }
3797         }
3798         if (tries == 5)
3799                 DRM_ERROR("FDI train 1 fail!\n");
3800
3801         /* Train 2 */
3802         reg = FDI_TX_CTL(pipe);
3803         temp = I915_READ(reg);
3804         temp &= ~FDI_LINK_TRAIN_NONE;
3805         temp |= FDI_LINK_TRAIN_PATTERN_2;
3806         I915_WRITE(reg, temp);
3807
3808         reg = FDI_RX_CTL(pipe);
3809         temp = I915_READ(reg);
3810         temp &= ~FDI_LINK_TRAIN_NONE;
3811         temp |= FDI_LINK_TRAIN_PATTERN_2;
3812         I915_WRITE(reg, temp);
3813
3814         POSTING_READ(reg);
3815         udelay(150);
3816
3817         reg = FDI_RX_IIR(pipe);
3818         for (tries = 0; tries < 5; tries++) {
3819                 temp = I915_READ(reg);
3820                 DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
3821
3822                 if (temp & FDI_RX_SYMBOL_LOCK) {
3823                         I915_WRITE(reg, temp | FDI_RX_SYMBOL_LOCK);
3824                         DRM_DEBUG_KMS("FDI train 2 done.\n");
3825                         break;
3826                 }
3827         }
3828         if (tries == 5)
3829                 DRM_ERROR("FDI train 2 fail!\n");
3830
3831         DRM_DEBUG_KMS("FDI train done\n");
3832
3833 }
3834
3835 static const int snb_b_fdi_train_param[] = {
3836         FDI_LINK_TRAIN_400MV_0DB_SNB_B,
3837         FDI_LINK_TRAIN_400MV_6DB_SNB_B,
3838         FDI_LINK_TRAIN_600MV_3_5DB_SNB_B,
3839         FDI_LINK_TRAIN_800MV_0DB_SNB_B,
3840 };
3841
3842 /* The FDI link training functions for SNB/Cougarpoint. */
3843 static void gen6_fdi_link_train(struct drm_crtc *crtc)
3844 {
3845         struct drm_device *dev = crtc->dev;
3846         struct drm_i915_private *dev_priv = to_i915(dev);
3847         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3848         int pipe = intel_crtc->pipe;
3849         i915_reg_t reg;
3850         u32 temp, i, retry;
3851
3852         /* Train 1: umask FDI RX Interrupt symbol_lock and bit_lock bit
3853            for train result */
3854         reg = FDI_RX_IMR(pipe);
3855         temp = I915_READ(reg);
3856         temp &= ~FDI_RX_SYMBOL_LOCK;
3857         temp &= ~FDI_RX_BIT_LOCK;
3858         I915_WRITE(reg, temp);
3859
3860         POSTING_READ(reg);
3861         udelay(150);
3862
3863         /* enable CPU FDI TX and PCH FDI RX */
3864         reg = FDI_TX_CTL(pipe);
3865         temp = I915_READ(reg);
3866         temp &= ~FDI_DP_PORT_WIDTH_MASK;
3867         temp |= FDI_DP_PORT_WIDTH(intel_crtc->config->fdi_lanes);
3868         temp &= ~FDI_LINK_TRAIN_NONE;
3869         temp |= FDI_LINK_TRAIN_PATTERN_1;
3870         temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
3871         /* SNB-B */
3872         temp |= FDI_LINK_TRAIN_400MV_0DB_SNB_B;
3873         I915_WRITE(reg, temp | FDI_TX_ENABLE);
3874
3875         I915_WRITE(FDI_RX_MISC(pipe),
3876                    FDI_RX_TP1_TO_TP2_48 | FDI_RX_FDI_DELAY_90);
3877
3878         reg = FDI_RX_CTL(pipe);
3879         temp = I915_READ(reg);
3880         if (HAS_PCH_CPT(dev_priv)) {
3881                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
3882                 temp |= FDI_LINK_TRAIN_PATTERN_1_CPT;
3883         } else {
3884                 temp &= ~FDI_LINK_TRAIN_NONE;
3885                 temp |= FDI_LINK_TRAIN_PATTERN_1;
3886         }
3887         I915_WRITE(reg, temp | FDI_RX_ENABLE);
3888
3889         POSTING_READ(reg);
3890         udelay(150);
3891
3892         for (i = 0; i < 4; i++) {
3893                 reg = FDI_TX_CTL(pipe);
3894                 temp = I915_READ(reg);
3895                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
3896                 temp |= snb_b_fdi_train_param[i];
3897                 I915_WRITE(reg, temp);
3898
3899                 POSTING_READ(reg);
3900                 udelay(500);
3901
3902                 for (retry = 0; retry < 5; retry++) {
3903                         reg = FDI_RX_IIR(pipe);
3904                         temp = I915_READ(reg);
3905                         DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
3906                         if (temp & FDI_RX_BIT_LOCK) {
3907                                 I915_WRITE(reg, temp | FDI_RX_BIT_LOCK);
3908                                 DRM_DEBUG_KMS("FDI train 1 done.\n");
3909                                 break;
3910                         }
3911                         udelay(50);
3912                 }
3913                 if (retry < 5)
3914                         break;
3915         }
3916         if (i == 4)
3917                 DRM_ERROR("FDI train 1 fail!\n");
3918
3919         /* Train 2 */
3920         reg = FDI_TX_CTL(pipe);
3921         temp = I915_READ(reg);
3922         temp &= ~FDI_LINK_TRAIN_NONE;
3923         temp |= FDI_LINK_TRAIN_PATTERN_2;
3924         if (IS_GEN6(dev_priv)) {
3925                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
3926                 /* SNB-B */
3927                 temp |= FDI_LINK_TRAIN_400MV_0DB_SNB_B;
3928         }
3929         I915_WRITE(reg, temp);
3930
3931         reg = FDI_RX_CTL(pipe);
3932         temp = I915_READ(reg);
3933         if (HAS_PCH_CPT(dev_priv)) {
3934                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
3935                 temp |= FDI_LINK_TRAIN_PATTERN_2_CPT;
3936         } else {
3937                 temp &= ~FDI_LINK_TRAIN_NONE;
3938                 temp |= FDI_LINK_TRAIN_PATTERN_2;
3939         }
3940         I915_WRITE(reg, temp);
3941
3942         POSTING_READ(reg);
3943         udelay(150);
3944
3945         for (i = 0; i < 4; i++) {
3946                 reg = FDI_TX_CTL(pipe);
3947                 temp = I915_READ(reg);
3948                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
3949                 temp |= snb_b_fdi_train_param[i];
3950                 I915_WRITE(reg, temp);
3951
3952                 POSTING_READ(reg);
3953                 udelay(500);
3954
3955                 for (retry = 0; retry < 5; retry++) {
3956                         reg = FDI_RX_IIR(pipe);
3957                         temp = I915_READ(reg);
3958                         DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
3959                         if (temp & FDI_RX_SYMBOL_LOCK) {
3960                                 I915_WRITE(reg, temp | FDI_RX_SYMBOL_LOCK);
3961                                 DRM_DEBUG_KMS("FDI train 2 done.\n");
3962                                 break;
3963                         }
3964                         udelay(50);
3965                 }
3966                 if (retry < 5)
3967                         break;
3968         }
3969         if (i == 4)
3970                 DRM_ERROR("FDI train 2 fail!\n");
3971
3972         DRM_DEBUG_KMS("FDI train done.\n");
3973 }
3974
3975 /* Manual link training for Ivy Bridge A0 parts */
3976 static void ivb_manual_fdi_link_train(struct drm_crtc *crtc)
3977 {
3978         struct drm_device *dev = crtc->dev;
3979         struct drm_i915_private *dev_priv = to_i915(dev);
3980         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3981         int pipe = intel_crtc->pipe;
3982         i915_reg_t reg;
3983         u32 temp, i, j;
3984
3985         /* Train 1: umask FDI RX Interrupt symbol_lock and bit_lock bit
3986            for train result */
3987         reg = FDI_RX_IMR(pipe);
3988         temp = I915_READ(reg);
3989         temp &= ~FDI_RX_SYMBOL_LOCK;
3990         temp &= ~FDI_RX_BIT_LOCK;
3991         I915_WRITE(reg, temp);
3992
3993         POSTING_READ(reg);
3994         udelay(150);
3995
3996         DRM_DEBUG_KMS("FDI_RX_IIR before link train 0x%x\n",
3997                       I915_READ(FDI_RX_IIR(pipe)));
3998
3999         /* Try each vswing and preemphasis setting twice before moving on */
4000         for (j = 0; j < ARRAY_SIZE(snb_b_fdi_train_param) * 2; j++) {
4001                 /* disable first in case we need to retry */
4002                 reg = FDI_TX_CTL(pipe);
4003                 temp = I915_READ(reg);
4004                 temp &= ~(FDI_LINK_TRAIN_AUTO | FDI_LINK_TRAIN_NONE_IVB);
4005                 temp &= ~FDI_TX_ENABLE;
4006                 I915_WRITE(reg, temp);
4007
4008                 reg = FDI_RX_CTL(pipe);
4009                 temp = I915_READ(reg);
4010                 temp &= ~FDI_LINK_TRAIN_AUTO;
4011                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
4012                 temp &= ~FDI_RX_ENABLE;
4013                 I915_WRITE(reg, temp);
4014
4015                 /* enable CPU FDI TX and PCH FDI RX */
4016                 reg = FDI_TX_CTL(pipe);
4017                 temp = I915_READ(reg);
4018                 temp &= ~FDI_DP_PORT_WIDTH_MASK;
4019                 temp |= FDI_DP_PORT_WIDTH(intel_crtc->config->fdi_lanes);
4020                 temp |= FDI_LINK_TRAIN_PATTERN_1_IVB;
4021                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
4022                 temp |= snb_b_fdi_train_param[j/2];
4023                 temp |= FDI_COMPOSITE_SYNC;
4024                 I915_WRITE(reg, temp | FDI_TX_ENABLE);
4025
4026                 I915_WRITE(FDI_RX_MISC(pipe),
4027                            FDI_RX_TP1_TO_TP2_48 | FDI_RX_FDI_DELAY_90);
4028
4029                 reg = FDI_RX_CTL(pipe);
4030                 temp = I915_READ(reg);
4031                 temp |= FDI_LINK_TRAIN_PATTERN_1_CPT;
4032                 temp |= FDI_COMPOSITE_SYNC;
4033                 I915_WRITE(reg, temp | FDI_RX_ENABLE);
4034
4035                 POSTING_READ(reg);
4036                 udelay(1); /* should be 0.5us */
4037
4038                 for (i = 0; i < 4; i++) {
4039                         reg = FDI_RX_IIR(pipe);
4040                         temp = I915_READ(reg);
4041                         DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
4042
4043                         if (temp & FDI_RX_BIT_LOCK ||
4044                             (I915_READ(reg) & FDI_RX_BIT_LOCK)) {
4045                                 I915_WRITE(reg, temp | FDI_RX_BIT_LOCK);
4046                                 DRM_DEBUG_KMS("FDI train 1 done, level %i.\n",
4047                                               i);
4048                                 break;
4049                         }
4050                         udelay(1); /* should be 0.5us */
4051                 }
4052                 if (i == 4) {
4053                         DRM_DEBUG_KMS("FDI train 1 fail on vswing %d\n", j / 2);
4054                         continue;
4055                 }
4056
4057                 /* Train 2 */
4058                 reg = FDI_TX_CTL(pipe);
4059                 temp = I915_READ(reg);
4060                 temp &= ~FDI_LINK_TRAIN_NONE_IVB;
4061                 temp |= FDI_LINK_TRAIN_PATTERN_2_IVB;
4062                 I915_WRITE(reg, temp);
4063
4064                 reg = FDI_RX_CTL(pipe);
4065                 temp = I915_READ(reg);
4066                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
4067                 temp |= FDI_LINK_TRAIN_PATTERN_2_CPT;
4068                 I915_WRITE(reg, temp);
4069
4070                 POSTING_READ(reg);
4071                 udelay(2); /* should be 1.5us */
4072
4073                 for (i = 0; i < 4; i++) {
4074                         reg = FDI_RX_IIR(pipe);
4075                         temp = I915_READ(reg);
4076                         DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
4077
4078                         if (temp & FDI_RX_SYMBOL_LOCK ||
4079                             (I915_READ(reg) & FDI_RX_SYMBOL_LOCK)) {
4080                                 I915_WRITE(reg, temp | FDI_RX_SYMBOL_LOCK);
4081                                 DRM_DEBUG_KMS("FDI train 2 done, level %i.\n",
4082                                               i);
4083                                 goto train_done;
4084                         }
4085                         udelay(2); /* should be 1.5us */
4086                 }
4087                 if (i == 4)
4088                         DRM_DEBUG_KMS("FDI train 2 fail on vswing %d\n", j / 2);
4089         }
4090
4091 train_done:
4092         DRM_DEBUG_KMS("FDI train done.\n");
4093 }
4094
4095 static void ironlake_fdi_pll_enable(struct intel_crtc *intel_crtc)
4096 {
4097         struct drm_device *dev = intel_crtc->base.dev;
4098         struct drm_i915_private *dev_priv = to_i915(dev);
4099         int pipe = intel_crtc->pipe;
4100         i915_reg_t reg;
4101         u32 temp;
4102
4103         /* enable PCH FDI RX PLL, wait warmup plus DMI latency */
4104         reg = FDI_RX_CTL(pipe);
4105         temp = I915_READ(reg);
4106         temp &= ~(FDI_DP_PORT_WIDTH_MASK | (0x7 << 16));
4107         temp |= FDI_DP_PORT_WIDTH(intel_crtc->config->fdi_lanes);
4108         temp |= (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) << 11;
4109         I915_WRITE(reg, temp | FDI_RX_PLL_ENABLE);
4110
4111         POSTING_READ(reg);
4112         udelay(200);
4113
4114         /* Switch from Rawclk to PCDclk */
4115         temp = I915_READ(reg);
4116         I915_WRITE(reg, temp | FDI_PCDCLK);
4117
4118         POSTING_READ(reg);
4119         udelay(200);
4120
4121         /* Enable CPU FDI TX PLL, always on for Ironlake */
4122         reg = FDI_TX_CTL(pipe);
4123         temp = I915_READ(reg);
4124         if ((temp & FDI_TX_PLL_ENABLE) == 0) {
4125                 I915_WRITE(reg, temp | FDI_TX_PLL_ENABLE);
4126
4127                 POSTING_READ(reg);
4128                 udelay(100);
4129         }
4130 }
4131
4132 static void ironlake_fdi_pll_disable(struct intel_crtc *intel_crtc)
4133 {
4134         struct drm_device *dev = intel_crtc->base.dev;
4135         struct drm_i915_private *dev_priv = to_i915(dev);
4136         int pipe = intel_crtc->pipe;
4137         i915_reg_t reg;
4138         u32 temp;
4139
4140         /* Switch from PCDclk to Rawclk */
4141         reg = FDI_RX_CTL(pipe);
4142         temp = I915_READ(reg);
4143         I915_WRITE(reg, temp & ~FDI_PCDCLK);
4144
4145         /* Disable CPU FDI TX PLL */
4146         reg = FDI_TX_CTL(pipe);
4147         temp = I915_READ(reg);
4148         I915_WRITE(reg, temp & ~FDI_TX_PLL_ENABLE);
4149
4150         POSTING_READ(reg);
4151         udelay(100);
4152
4153         reg = FDI_RX_CTL(pipe);
4154         temp = I915_READ(reg);
4155         I915_WRITE(reg, temp & ~FDI_RX_PLL_ENABLE);
4156
4157         /* Wait for the clocks to turn off. */
4158         POSTING_READ(reg);
4159         udelay(100);
4160 }
4161
4162 static void ironlake_fdi_disable(struct drm_crtc *crtc)
4163 {
4164         struct drm_device *dev = crtc->dev;
4165         struct drm_i915_private *dev_priv = to_i915(dev);
4166         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4167         int pipe = intel_crtc->pipe;
4168         i915_reg_t reg;
4169         u32 temp;
4170
4171         /* disable CPU FDI tx and PCH FDI rx */
4172         reg = FDI_TX_CTL(pipe);
4173         temp = I915_READ(reg);
4174         I915_WRITE(reg, temp & ~FDI_TX_ENABLE);
4175         POSTING_READ(reg);
4176
4177         reg = FDI_RX_CTL(pipe);
4178         temp = I915_READ(reg);
4179         temp &= ~(0x7 << 16);
4180         temp |= (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) << 11;
4181         I915_WRITE(reg, temp & ~FDI_RX_ENABLE);
4182
4183         POSTING_READ(reg);
4184         udelay(100);
4185
4186         /* Ironlake workaround, disable clock pointer after downing FDI */
4187         if (HAS_PCH_IBX(dev_priv))
4188                 I915_WRITE(FDI_RX_CHICKEN(pipe), FDI_RX_PHASE_SYNC_POINTER_OVR);
4189
4190         /* still set train pattern 1 */
4191         reg = FDI_TX_CTL(pipe);
4192         temp = I915_READ(reg);
4193         temp &= ~FDI_LINK_TRAIN_NONE;
4194         temp |= FDI_LINK_TRAIN_PATTERN_1;
4195         I915_WRITE(reg, temp);
4196
4197         reg = FDI_RX_CTL(pipe);
4198         temp = I915_READ(reg);
4199         if (HAS_PCH_CPT(dev_priv)) {
4200                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
4201                 temp |= FDI_LINK_TRAIN_PATTERN_1_CPT;
4202         } else {
4203                 temp &= ~FDI_LINK_TRAIN_NONE;
4204                 temp |= FDI_LINK_TRAIN_PATTERN_1;
4205         }
4206         /* BPC in FDI rx is consistent with that in PIPECONF */
4207         temp &= ~(0x07 << 16);
4208         temp |= (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) << 11;
4209         I915_WRITE(reg, temp);
4210
4211         POSTING_READ(reg);
4212         udelay(100);
4213 }
4214
4215 bool intel_has_pending_fb_unpin(struct drm_i915_private *dev_priv)
4216 {
4217         struct intel_crtc *crtc;
4218
4219         /* Note that we don't need to be called with mode_config.lock here
4220          * as our list of CRTC objects is static for the lifetime of the
4221          * device and so cannot disappear as we iterate. Similarly, we can
4222          * happily treat the predicates as racy, atomic checks as userspace
4223          * cannot claim and pin a new fb without at least acquring the
4224          * struct_mutex and so serialising with us.
4225          */
4226         for_each_intel_crtc(&dev_priv->drm, crtc) {
4227                 if (atomic_read(&crtc->unpin_work_count) == 0)
4228                         continue;
4229
4230                 if (crtc->flip_work)
4231                         intel_wait_for_vblank(dev_priv, crtc->pipe);
4232
4233                 return true;
4234         }
4235
4236         return false;
4237 }
4238
4239 static void page_flip_completed(struct intel_crtc *intel_crtc)
4240 {
4241         struct drm_i915_private *dev_priv = to_i915(intel_crtc->base.dev);
4242         struct intel_flip_work *work = intel_crtc->flip_work;
4243
4244         intel_crtc->flip_work = NULL;
4245
4246         if (work->event)
4247                 drm_crtc_send_vblank_event(&intel_crtc->base, work->event);
4248
4249         drm_crtc_vblank_put(&intel_crtc->base);
4250
4251         wake_up_all(&dev_priv->pending_flip_queue);
4252         trace_i915_flip_complete(intel_crtc->plane,
4253                                  work->pending_flip_obj);
4254
4255         queue_work(dev_priv->wq, &work->unpin_work);
4256 }
4257
4258 static int intel_crtc_wait_for_pending_flips(struct drm_crtc *crtc)
4259 {
4260         struct drm_device *dev = crtc->dev;
4261         struct drm_i915_private *dev_priv = to_i915(dev);
4262         long ret;
4263
4264         WARN_ON(waitqueue_active(&dev_priv->pending_flip_queue));
4265
4266         ret = wait_event_interruptible_timeout(
4267                                         dev_priv->pending_flip_queue,
4268                                         !intel_crtc_has_pending_flip(crtc),
4269                                         60*HZ);
4270
4271         if (ret < 0)
4272                 return ret;
4273
4274         if (ret == 0) {
4275                 struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4276                 struct intel_flip_work *work;
4277
4278                 spin_lock_irq(&dev->event_lock);
4279                 work = intel_crtc->flip_work;
4280                 if (work && !is_mmio_work(work)) {
4281                         WARN_ONCE(1, "Removing stuck page flip\n");
4282                         page_flip_completed(intel_crtc);
4283                 }
4284                 spin_unlock_irq(&dev->event_lock);
4285         }
4286
4287         return 0;
4288 }
4289
4290 void lpt_disable_iclkip(struct drm_i915_private *dev_priv)
4291 {
4292         u32 temp;
4293
4294         I915_WRITE(PIXCLK_GATE, PIXCLK_GATE_GATE);
4295
4296         mutex_lock(&dev_priv->sb_lock);
4297
4298         temp = intel_sbi_read(dev_priv, SBI_SSCCTL6, SBI_ICLK);
4299         temp |= SBI_SSCCTL_DISABLE;
4300         intel_sbi_write(dev_priv, SBI_SSCCTL6, temp, SBI_ICLK);
4301
4302         mutex_unlock(&dev_priv->sb_lock);
4303 }
4304
4305 /* Program iCLKIP clock to the desired frequency */
4306 static void lpt_program_iclkip(struct drm_crtc *crtc)
4307 {
4308         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
4309         int clock = to_intel_crtc(crtc)->config->base.adjusted_mode.crtc_clock;
4310         u32 divsel, phaseinc, auxdiv, phasedir = 0;
4311         u32 temp;
4312
4313         lpt_disable_iclkip(dev_priv);
4314
4315         /* The iCLK virtual clock root frequency is in MHz,
4316          * but the adjusted_mode->crtc_clock in in KHz. To get the
4317          * divisors, it is necessary to divide one by another, so we
4318          * convert the virtual clock precision to KHz here for higher
4319          * precision.
4320          */
4321         for (auxdiv = 0; auxdiv < 2; auxdiv++) {
4322                 u32 iclk_virtual_root_freq = 172800 * 1000;
4323                 u32 iclk_pi_range = 64;
4324                 u32 desired_divisor;
4325
4326                 desired_divisor = DIV_ROUND_CLOSEST(iclk_virtual_root_freq,
4327                                                     clock << auxdiv);
4328                 divsel = (desired_divisor / iclk_pi_range) - 2;
4329                 phaseinc = desired_divisor % iclk_pi_range;
4330
4331                 /*
4332                  * Near 20MHz is a corner case which is
4333                  * out of range for the 7-bit divisor
4334                  */
4335                 if (divsel <= 0x7f)
4336                         break;
4337         }
4338
4339         /* This should not happen with any sane values */
4340         WARN_ON(SBI_SSCDIVINTPHASE_DIVSEL(divsel) &
4341                 ~SBI_SSCDIVINTPHASE_DIVSEL_MASK);
4342         WARN_ON(SBI_SSCDIVINTPHASE_DIR(phasedir) &
4343                 ~SBI_SSCDIVINTPHASE_INCVAL_MASK);
4344
4345         DRM_DEBUG_KMS("iCLKIP clock: found settings for %dKHz refresh rate: auxdiv=%x, divsel=%x, phasedir=%x, phaseinc=%x\n",
4346                         clock,
4347                         auxdiv,
4348                         divsel,
4349                         phasedir,
4350                         phaseinc);
4351
4352         mutex_lock(&dev_priv->sb_lock);
4353
4354         /* Program SSCDIVINTPHASE6 */
4355         temp = intel_sbi_read(dev_priv, SBI_SSCDIVINTPHASE6, SBI_ICLK);
4356         temp &= ~SBI_SSCDIVINTPHASE_DIVSEL_MASK;
4357         temp |= SBI_SSCDIVINTPHASE_DIVSEL(divsel);
4358         temp &= ~SBI_SSCDIVINTPHASE_INCVAL_MASK;
4359         temp |= SBI_SSCDIVINTPHASE_INCVAL(phaseinc);
4360         temp |= SBI_SSCDIVINTPHASE_DIR(phasedir);
4361         temp |= SBI_SSCDIVINTPHASE_PROPAGATE;
4362         intel_sbi_write(dev_priv, SBI_SSCDIVINTPHASE6, temp, SBI_ICLK);
4363
4364         /* Program SSCAUXDIV */
4365         temp = intel_sbi_read(dev_priv, SBI_SSCAUXDIV6, SBI_ICLK);
4366         temp &= ~SBI_SSCAUXDIV_FINALDIV2SEL(1);
4367         temp |= SBI_SSCAUXDIV_FINALDIV2SEL(auxdiv);
4368         intel_sbi_write(dev_priv, SBI_SSCAUXDIV6, temp, SBI_ICLK);
4369
4370         /* Enable modulator and associated divider */
4371         temp = intel_sbi_read(dev_priv, SBI_SSCCTL6, SBI_ICLK);
4372         temp &= ~SBI_SSCCTL_DISABLE;
4373         intel_sbi_write(dev_priv, SBI_SSCCTL6, temp, SBI_ICLK);
4374
4375         mutex_unlock(&dev_priv->sb_lock);
4376
4377         /* Wait for initialization time */
4378         udelay(24);
4379
4380         I915_WRITE(PIXCLK_GATE, PIXCLK_GATE_UNGATE);
4381 }
4382
4383 int lpt_get_iclkip(struct drm_i915_private *dev_priv)
4384 {
4385         u32 divsel, phaseinc, auxdiv;
4386         u32 iclk_virtual_root_freq = 172800 * 1000;
4387         u32 iclk_pi_range = 64;
4388         u32 desired_divisor;
4389         u32 temp;
4390
4391         if ((I915_READ(PIXCLK_GATE) & PIXCLK_GATE_UNGATE) == 0)
4392                 return 0;
4393
4394         mutex_lock(&dev_priv->sb_lock);
4395
4396         temp = intel_sbi_read(dev_priv, SBI_SSCCTL6, SBI_ICLK);
4397         if (temp & SBI_SSCCTL_DISABLE) {
4398                 mutex_unlock(&dev_priv->sb_lock);
4399                 return 0;
4400         }
4401
4402         temp = intel_sbi_read(dev_priv, SBI_SSCDIVINTPHASE6, SBI_ICLK);
4403         divsel = (temp & SBI_SSCDIVINTPHASE_DIVSEL_MASK) >>
4404                 SBI_SSCDIVINTPHASE_DIVSEL_SHIFT;
4405         phaseinc = (temp & SBI_SSCDIVINTPHASE_INCVAL_MASK) >>
4406                 SBI_SSCDIVINTPHASE_INCVAL_SHIFT;
4407
4408         temp = intel_sbi_read(dev_priv, SBI_SSCAUXDIV6, SBI_ICLK);
4409         auxdiv = (temp & SBI_SSCAUXDIV_FINALDIV2SEL_MASK) >>
4410                 SBI_SSCAUXDIV_FINALDIV2SEL_SHIFT;
4411
4412         mutex_unlock(&dev_priv->sb_lock);
4413
4414         desired_divisor = (divsel + 2) * iclk_pi_range + phaseinc;
4415
4416         return DIV_ROUND_CLOSEST(iclk_virtual_root_freq,
4417                                  desired_divisor << auxdiv);
4418 }
4419
4420 static void ironlake_pch_transcoder_set_timings(struct intel_crtc *crtc,
4421                                                 enum pipe pch_transcoder)
4422 {
4423         struct drm_device *dev = crtc->base.dev;
4424         struct drm_i915_private *dev_priv = to_i915(dev);
4425         enum transcoder cpu_transcoder = crtc->config->cpu_transcoder;
4426
4427         I915_WRITE(PCH_TRANS_HTOTAL(pch_transcoder),
4428                    I915_READ(HTOTAL(cpu_transcoder)));
4429         I915_WRITE(PCH_TRANS_HBLANK(pch_transcoder),
4430                    I915_READ(HBLANK(cpu_transcoder)));
4431         I915_WRITE(PCH_TRANS_HSYNC(pch_transcoder),
4432                    I915_READ(HSYNC(cpu_transcoder)));
4433
4434         I915_WRITE(PCH_TRANS_VTOTAL(pch_transcoder),
4435                    I915_READ(VTOTAL(cpu_transcoder)));
4436         I915_WRITE(PCH_TRANS_VBLANK(pch_transcoder),
4437                    I915_READ(VBLANK(cpu_transcoder)));
4438         I915_WRITE(PCH_TRANS_VSYNC(pch_transcoder),
4439                    I915_READ(VSYNC(cpu_transcoder)));
4440         I915_WRITE(PCH_TRANS_VSYNCSHIFT(pch_transcoder),
4441                    I915_READ(VSYNCSHIFT(cpu_transcoder)));
4442 }
4443
4444 static void cpt_set_fdi_bc_bifurcation(struct drm_device *dev, bool enable)
4445 {
4446         struct drm_i915_private *dev_priv = to_i915(dev);
4447         uint32_t temp;
4448
4449         temp = I915_READ(SOUTH_CHICKEN1);
4450         if (!!(temp & FDI_BC_BIFURCATION_SELECT) == enable)
4451                 return;
4452
4453         WARN_ON(I915_READ(FDI_RX_CTL(PIPE_B)) & FDI_RX_ENABLE);
4454         WARN_ON(I915_READ(FDI_RX_CTL(PIPE_C)) & FDI_RX_ENABLE);
4455
4456         temp &= ~FDI_BC_BIFURCATION_SELECT;
4457         if (enable)
4458                 temp |= FDI_BC_BIFURCATION_SELECT;
4459
4460         DRM_DEBUG_KMS("%sabling fdi C rx\n", enable ? "en" : "dis");
4461         I915_WRITE(SOUTH_CHICKEN1, temp);
4462         POSTING_READ(SOUTH_CHICKEN1);
4463 }
4464
4465 static void ivybridge_update_fdi_bc_bifurcation(struct intel_crtc *intel_crtc)
4466 {
4467         struct drm_device *dev = intel_crtc->base.dev;
4468
4469         switch (intel_crtc->pipe) {
4470         case PIPE_A:
4471                 break;
4472         case PIPE_B:
4473                 if (intel_crtc->config->fdi_lanes > 2)
4474                         cpt_set_fdi_bc_bifurcation(dev, false);
4475                 else
4476                         cpt_set_fdi_bc_bifurcation(dev, true);
4477
4478                 break;
4479         case PIPE_C:
4480                 cpt_set_fdi_bc_bifurcation(dev, true);
4481
4482                 break;
4483         default:
4484                 BUG();
4485         }
4486 }
4487
4488 /* Return which DP Port should be selected for Transcoder DP control */
4489 static enum port
4490 intel_trans_dp_port_sel(struct drm_crtc *crtc)
4491 {
4492         struct drm_device *dev = crtc->dev;
4493         struct intel_encoder *encoder;
4494
4495         for_each_encoder_on_crtc(dev, crtc, encoder) {
4496                 if (encoder->type == INTEL_OUTPUT_DP ||
4497                     encoder->type == INTEL_OUTPUT_EDP)
4498                         return enc_to_dig_port(&encoder->base)->port;
4499         }
4500
4501         return -1;
4502 }
4503
4504 /*
4505  * Enable PCH resources required for PCH ports:
4506  *   - PCH PLLs
4507  *   - FDI training & RX/TX
4508  *   - update transcoder timings
4509  *   - DP transcoding bits
4510  *   - transcoder
4511  */
4512 static void ironlake_pch_enable(struct drm_crtc *crtc)
4513 {
4514         struct drm_device *dev = crtc->dev;
4515         struct drm_i915_private *dev_priv = to_i915(dev);
4516         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4517         int pipe = intel_crtc->pipe;
4518         u32 temp;
4519
4520         assert_pch_transcoder_disabled(dev_priv, pipe);
4521
4522         if (IS_IVYBRIDGE(dev_priv))
4523                 ivybridge_update_fdi_bc_bifurcation(intel_crtc);
4524
4525         /* Write the TU size bits before fdi link training, so that error
4526          * detection works. */
4527         I915_WRITE(FDI_RX_TUSIZE1(pipe),
4528                    I915_READ(PIPE_DATA_M1(pipe)) & TU_SIZE_MASK);
4529
4530         /* For PCH output, training FDI link */
4531         dev_priv->display.fdi_link_train(crtc);
4532
4533         /* We need to program the right clock selection before writing the pixel
4534          * mutliplier into the DPLL. */
4535         if (HAS_PCH_CPT(dev_priv)) {
4536                 u32 sel;
4537
4538                 temp = I915_READ(PCH_DPLL_SEL);
4539                 temp |= TRANS_DPLL_ENABLE(pipe);
4540                 sel = TRANS_DPLLB_SEL(pipe);
4541                 if (intel_crtc->config->shared_dpll ==
4542                     intel_get_shared_dpll_by_id(dev_priv, DPLL_ID_PCH_PLL_B))
4543                         temp |= sel;
4544                 else
4545                         temp &= ~sel;
4546                 I915_WRITE(PCH_DPLL_SEL, temp);
4547         }
4548
4549         /* XXX: pch pll's can be enabled any time before we enable the PCH
4550          * transcoder, and we actually should do this to not upset any PCH
4551          * transcoder that already use the clock when we share it.
4552          *
4553          * Note that enable_shared_dpll tries to do the right thing, but
4554          * get_shared_dpll unconditionally resets the pll - we need that to have
4555          * the right LVDS enable sequence. */
4556         intel_enable_shared_dpll(intel_crtc);
4557
4558         /* set transcoder timing, panel must allow it */
4559         assert_panel_unlocked(dev_priv, pipe);
4560         ironlake_pch_transcoder_set_timings(intel_crtc, pipe);
4561
4562         intel_fdi_normal_train(crtc);
4563
4564         /* For PCH DP, enable TRANS_DP_CTL */
4565         if (HAS_PCH_CPT(dev_priv) &&
4566             intel_crtc_has_dp_encoder(intel_crtc->config)) {
4567                 const struct drm_display_mode *adjusted_mode =
4568                         &intel_crtc->config->base.adjusted_mode;
4569                 u32 bpc = (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) >> 5;
4570                 i915_reg_t reg = TRANS_DP_CTL(pipe);
4571                 temp = I915_READ(reg);
4572                 temp &= ~(TRANS_DP_PORT_SEL_MASK |
4573                           TRANS_DP_SYNC_MASK |
4574                           TRANS_DP_BPC_MASK);
4575                 temp |= TRANS_DP_OUTPUT_ENABLE;
4576                 temp |= bpc << 9; /* same format but at 11:9 */
4577
4578                 if (adjusted_mode->flags & DRM_MODE_FLAG_PHSYNC)
4579                         temp |= TRANS_DP_HSYNC_ACTIVE_HIGH;
4580                 if (adjusted_mode->flags & DRM_MODE_FLAG_PVSYNC)
4581                         temp |= TRANS_DP_VSYNC_ACTIVE_HIGH;
4582
4583                 switch (intel_trans_dp_port_sel(crtc)) {
4584                 case PORT_B:
4585                         temp |= TRANS_DP_PORT_SEL_B;
4586                         break;
4587                 case PORT_C:
4588                         temp |= TRANS_DP_PORT_SEL_C;
4589                         break;
4590                 case PORT_D:
4591                         temp |= TRANS_DP_PORT_SEL_D;
4592                         break;
4593                 default:
4594                         BUG();
4595                 }
4596
4597                 I915_WRITE(reg, temp);
4598         }
4599
4600         ironlake_enable_pch_transcoder(dev_priv, pipe);
4601 }
4602
4603 static void lpt_pch_enable(struct drm_crtc *crtc)
4604 {
4605         struct drm_device *dev = crtc->dev;
4606         struct drm_i915_private *dev_priv = to_i915(dev);
4607         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4608         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
4609
4610         assert_pch_transcoder_disabled(dev_priv, TRANSCODER_A);
4611
4612         lpt_program_iclkip(crtc);
4613
4614         /* Set transcoder timing. */
4615         ironlake_pch_transcoder_set_timings(intel_crtc, PIPE_A);
4616
4617         lpt_enable_pch_transcoder(dev_priv, cpu_transcoder);
4618 }
4619
4620 static void cpt_verify_modeset(struct drm_device *dev, int pipe)
4621 {
4622         struct drm_i915_private *dev_priv = to_i915(dev);
4623         i915_reg_t dslreg = PIPEDSL(pipe);
4624         u32 temp;
4625
4626         temp = I915_READ(dslreg);
4627         udelay(500);
4628         if (wait_for(I915_READ(dslreg) != temp, 5)) {
4629                 if (wait_for(I915_READ(dslreg) != temp, 5))
4630                         DRM_ERROR("mode set failed: pipe %c stuck\n", pipe_name(pipe));
4631         }
4632 }
4633
4634 static int
4635 skl_update_scaler(struct intel_crtc_state *crtc_state, bool force_detach,
4636                   unsigned scaler_user, int *scaler_id, unsigned int rotation,
4637                   int src_w, int src_h, int dst_w, int dst_h)
4638 {
4639         struct intel_crtc_scaler_state *scaler_state =
4640                 &crtc_state->scaler_state;
4641         struct intel_crtc *intel_crtc =
4642                 to_intel_crtc(crtc_state->base.crtc);
4643         int need_scaling;
4644
4645         need_scaling = drm_rotation_90_or_270(rotation) ?
4646                 (src_h != dst_w || src_w != dst_h):
4647                 (src_w != dst_w || src_h != dst_h);
4648
4649         /*
4650          * if plane is being disabled or scaler is no more required or force detach
4651          *  - free scaler binded to this plane/crtc
4652          *  - in order to do this, update crtc->scaler_usage
4653          *
4654          * Here scaler state in crtc_state is set free so that
4655          * scaler can be assigned to other user. Actual register
4656          * update to free the scaler is done in plane/panel-fit programming.
4657          * For this purpose crtc/plane_state->scaler_id isn't reset here.
4658          */
4659         if (force_detach || !need_scaling) {
4660                 if (*scaler_id >= 0) {
4661                         scaler_state->scaler_users &= ~(1 << scaler_user);
4662                         scaler_state->scalers[*scaler_id].in_use = 0;
4663
4664                         DRM_DEBUG_KMS("scaler_user index %u.%u: "
4665                                 "Staged freeing scaler id %d scaler_users = 0x%x\n",
4666                                 intel_crtc->pipe, scaler_user, *scaler_id,
4667                                 scaler_state->scaler_users);
4668                         *scaler_id = -1;
4669                 }
4670                 return 0;
4671         }
4672
4673         /* range checks */
4674         if (src_w < SKL_MIN_SRC_W || src_h < SKL_MIN_SRC_H ||
4675                 dst_w < SKL_MIN_DST_W || dst_h < SKL_MIN_DST_H ||
4676
4677                 src_w > SKL_MAX_SRC_W || src_h > SKL_MAX_SRC_H ||
4678                 dst_w > SKL_MAX_DST_W || dst_h > SKL_MAX_DST_H) {
4679                 DRM_DEBUG_KMS("scaler_user index %u.%u: src %ux%u dst %ux%u "
4680                         "size is out of scaler range\n",
4681                         intel_crtc->pipe, scaler_user, src_w, src_h, dst_w, dst_h);
4682                 return -EINVAL;
4683         }
4684
4685         /* mark this plane as a scaler user in crtc_state */
4686         scaler_state->scaler_users |= (1 << scaler_user);
4687         DRM_DEBUG_KMS("scaler_user index %u.%u: "
4688                 "staged scaling request for %ux%u->%ux%u scaler_users = 0x%x\n",
4689                 intel_crtc->pipe, scaler_user, src_w, src_h, dst_w, dst_h,
4690                 scaler_state->scaler_users);
4691
4692         return 0;
4693 }
4694
4695 /**
4696  * skl_update_scaler_crtc - Stages update to scaler state for a given crtc.
4697  *
4698  * @state: crtc's scaler state
4699  *
4700  * Return
4701  *     0 - scaler_usage updated successfully
4702  *    error - requested scaling cannot be supported or other error condition
4703  */
4704 int skl_update_scaler_crtc(struct intel_crtc_state *state)
4705 {
4706         const struct drm_display_mode *adjusted_mode = &state->base.adjusted_mode;
4707
4708         return skl_update_scaler(state, !state->base.active, SKL_CRTC_INDEX,
4709                 &state->scaler_state.scaler_id, DRM_ROTATE_0,
4710                 state->pipe_src_w, state->pipe_src_h,
4711                 adjusted_mode->crtc_hdisplay, adjusted_mode->crtc_vdisplay);
4712 }
4713
4714 /**
4715  * skl_update_scaler_plane - Stages update to scaler state for a given plane.
4716  *
4717  * @state: crtc's scaler state
4718  * @plane_state: atomic plane state to update
4719  *
4720  * Return
4721  *     0 - scaler_usage updated successfully
4722  *    error - requested scaling cannot be supported or other error condition
4723  */
4724 static int skl_update_scaler_plane(struct intel_crtc_state *crtc_state,
4725                                    struct intel_plane_state *plane_state)
4726 {
4727
4728         struct intel_plane *intel_plane =
4729                 to_intel_plane(plane_state->base.plane);
4730         struct drm_framebuffer *fb = plane_state->base.fb;
4731         int ret;
4732
4733         bool force_detach = !fb || !plane_state->base.visible;
4734
4735         ret = skl_update_scaler(crtc_state, force_detach,
4736                                 drm_plane_index(&intel_plane->base),
4737                                 &plane_state->scaler_id,
4738                                 plane_state->base.rotation,
4739                                 drm_rect_width(&plane_state->base.src) >> 16,
4740                                 drm_rect_height(&plane_state->base.src) >> 16,
4741                                 drm_rect_width(&plane_state->base.dst),
4742                                 drm_rect_height(&plane_state->base.dst));
4743
4744         if (ret || plane_state->scaler_id < 0)
4745                 return ret;
4746
4747         /* check colorkey */
4748         if (plane_state->ckey.flags != I915_SET_COLORKEY_NONE) {
4749                 DRM_DEBUG_KMS("[PLANE:%d:%s] scaling with color key not allowed",
4750                               intel_plane->base.base.id,
4751                               intel_plane->base.name);
4752                 return -EINVAL;
4753         }
4754
4755         /* Check src format */
4756         switch (fb->format->format) {
4757         case DRM_FORMAT_RGB565:
4758         case DRM_FORMAT_XBGR8888:
4759         case DRM_FORMAT_XRGB8888:
4760         case DRM_FORMAT_ABGR8888:
4761         case DRM_FORMAT_ARGB8888:
4762         case DRM_FORMAT_XRGB2101010:
4763         case DRM_FORMAT_XBGR2101010:
4764         case DRM_FORMAT_YUYV:
4765         case DRM_FORMAT_YVYU:
4766         case DRM_FORMAT_UYVY:
4767         case DRM_FORMAT_VYUY:
4768                 break;
4769         default:
4770                 DRM_DEBUG_KMS("[PLANE:%d:%s] FB:%d unsupported scaling format 0x%x\n",
4771                               intel_plane->base.base.id, intel_plane->base.name,
4772                               fb->base.id, fb->format->format);
4773                 return -EINVAL;
4774         }
4775
4776         return 0;
4777 }
4778
4779 static void skylake_scaler_disable(struct intel_crtc *crtc)
4780 {
4781         int i;
4782
4783         for (i = 0; i < crtc->num_scalers; i++)
4784                 skl_detach_scaler(crtc, i);
4785 }
4786
4787 static void skylake_pfit_enable(struct intel_crtc *crtc)
4788 {
4789         struct drm_device *dev = crtc->base.dev;
4790         struct drm_i915_private *dev_priv = to_i915(dev);
4791         int pipe = crtc->pipe;
4792         struct intel_crtc_scaler_state *scaler_state =
4793                 &crtc->config->scaler_state;
4794
4795         if (crtc->config->pch_pfit.enabled) {
4796                 int id;
4797
4798                 if (WARN_ON(crtc->config->scaler_state.scaler_id < 0))
4799                         return;
4800
4801                 id = scaler_state->scaler_id;
4802                 I915_WRITE(SKL_PS_CTRL(pipe, id), PS_SCALER_EN |
4803                         PS_FILTER_MEDIUM | scaler_state->scalers[id].mode);
4804                 I915_WRITE(SKL_PS_WIN_POS(pipe, id), crtc->config->pch_pfit.pos);
4805                 I915_WRITE(SKL_PS_WIN_SZ(pipe, id), crtc->config->pch_pfit.size);
4806         }
4807 }
4808
4809 static void ironlake_pfit_enable(struct intel_crtc *crtc)
4810 {
4811         struct drm_device *dev = crtc->base.dev;
4812         struct drm_i915_private *dev_priv = to_i915(dev);
4813         int pipe = crtc->pipe;
4814
4815         if (crtc->config->pch_pfit.enabled) {
4816                 /* Force use of hard-coded filter coefficients
4817                  * as some pre-programmed values are broken,
4818                  * e.g. x201.
4819                  */
4820                 if (IS_IVYBRIDGE(dev_priv) || IS_HASWELL(dev_priv))
4821                         I915_WRITE(PF_CTL(pipe), PF_ENABLE | PF_FILTER_MED_3x3 |
4822                                                  PF_PIPE_SEL_IVB(pipe));
4823                 else
4824                         I915_WRITE(PF_CTL(pipe), PF_ENABLE | PF_FILTER_MED_3x3);
4825                 I915_WRITE(PF_WIN_POS(pipe), crtc->config->pch_pfit.pos);
4826                 I915_WRITE(PF_WIN_SZ(pipe), crtc->config->pch_pfit.size);
4827         }
4828 }
4829
4830 void hsw_enable_ips(struct intel_crtc *crtc)
4831 {
4832         struct drm_device *dev = crtc->base.dev;
4833         struct drm_i915_private *dev_priv = to_i915(dev);
4834
4835         if (!crtc->config->ips_enabled)
4836                 return;
4837
4838         /*
4839          * We can only enable IPS after we enable a plane and wait for a vblank
4840          * This function is called from post_plane_update, which is run after
4841          * a vblank wait.
4842          */
4843
4844         assert_plane_enabled(dev_priv, crtc->plane);
4845         if (IS_BROADWELL(dev_priv)) {
4846                 mutex_lock(&dev_priv->rps.hw_lock);
4847                 WARN_ON(sandybridge_pcode_write(dev_priv, DISPLAY_IPS_CONTROL, 0xc0000000));
4848                 mutex_unlock(&dev_priv->rps.hw_lock);
4849                 /* Quoting Art Runyan: "its not safe to expect any particular
4850                  * value in IPS_CTL bit 31 after enabling IPS through the
4851                  * mailbox." Moreover, the mailbox may return a bogus state,
4852                  * so we need to just enable it and continue on.
4853                  */
4854         } else {
4855                 I915_WRITE(IPS_CTL, IPS_ENABLE);
4856                 /* The bit only becomes 1 in the next vblank, so this wait here
4857                  * is essentially intel_wait_for_vblank. If we don't have this
4858                  * and don't wait for vblanks until the end of crtc_enable, then
4859                  * the HW state readout code will complain that the expected
4860                  * IPS_CTL value is not the one we read. */
4861                 if (intel_wait_for_register(dev_priv,
4862                                             IPS_CTL, IPS_ENABLE, IPS_ENABLE,
4863                                             50))
4864                         DRM_ERROR("Timed out waiting for IPS enable\n");
4865         }
4866 }
4867
4868 void hsw_disable_ips(struct intel_crtc *crtc)
4869 {
4870         struct drm_device *dev = crtc->base.dev;
4871         struct drm_i915_private *dev_priv = to_i915(dev);
4872
4873         if (!crtc->config->ips_enabled)
4874                 return;
4875
4876         assert_plane_enabled(dev_priv, crtc->plane);
4877         if (IS_BROADWELL(dev_priv)) {
4878                 mutex_lock(&dev_priv->rps.hw_lock);
4879                 WARN_ON(sandybridge_pcode_write(dev_priv, DISPLAY_IPS_CONTROL, 0));
4880                 mutex_unlock(&dev_priv->rps.hw_lock);
4881                 /* wait for pcode to finish disabling IPS, which may take up to 42ms */
4882                 if (intel_wait_for_register(dev_priv,
4883                                             IPS_CTL, IPS_ENABLE, 0,
4884                                             42))
4885                         DRM_ERROR("Timed out waiting for IPS disable\n");
4886         } else {
4887                 I915_WRITE(IPS_CTL, 0);
4888                 POSTING_READ(IPS_CTL);
4889         }
4890
4891         /* We need to wait for a vblank before we can disable the plane. */
4892         intel_wait_for_vblank(dev_priv, crtc->pipe);
4893 }
4894
4895 static void intel_crtc_dpms_overlay_disable(struct intel_crtc *intel_crtc)
4896 {
4897         if (intel_crtc->overlay) {
4898                 struct drm_device *dev = intel_crtc->base.dev;
4899                 struct drm_i915_private *dev_priv = to_i915(dev);
4900
4901                 mutex_lock(&dev->struct_mutex);
4902                 dev_priv->mm.interruptible = false;
4903                 (void) intel_overlay_switch_off(intel_crtc->overlay);
4904                 dev_priv->mm.interruptible = true;
4905                 mutex_unlock(&dev->struct_mutex);
4906         }
4907
4908         /* Let userspace switch the overlay on again. In most cases userspace
4909          * has to recompute where to put it anyway.
4910          */
4911 }
4912
4913 /**
4914  * intel_post_enable_primary - Perform operations after enabling primary plane
4915  * @crtc: the CRTC whose primary plane was just enabled
4916  *
4917  * Performs potentially sleeping operations that must be done after the primary
4918  * plane is enabled, such as updating FBC and IPS.  Note that this may be
4919  * called due to an explicit primary plane update, or due to an implicit
4920  * re-enable that is caused when a sprite plane is updated to no longer
4921  * completely hide the primary plane.
4922  */
4923 static void
4924 intel_post_enable_primary(struct drm_crtc *crtc)
4925 {
4926         struct drm_device *dev = crtc->dev;
4927         struct drm_i915_private *dev_priv = to_i915(dev);
4928         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4929         int pipe = intel_crtc->pipe;
4930
4931         /*
4932          * FIXME IPS should be fine as long as one plane is
4933          * enabled, but in practice it seems to have problems
4934          * when going from primary only to sprite only and vice
4935          * versa.
4936          */
4937         hsw_enable_ips(intel_crtc);
4938
4939         /*
4940          * Gen2 reports pipe underruns whenever all planes are disabled.
4941          * So don't enable underrun reporting before at least some planes
4942          * are enabled.
4943          * FIXME: Need to fix the logic to work when we turn off all planes
4944          * but leave the pipe running.
4945          */
4946         if (IS_GEN2(dev_priv))
4947                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
4948
4949         /* Underruns don't always raise interrupts, so check manually. */
4950         intel_check_cpu_fifo_underruns(dev_priv);
4951         intel_check_pch_fifo_underruns(dev_priv);
4952 }
4953
4954 /* FIXME move all this to pre_plane_update() with proper state tracking */
4955 static void
4956 intel_pre_disable_primary(struct drm_crtc *crtc)
4957 {
4958         struct drm_device *dev = crtc->dev;
4959         struct drm_i915_private *dev_priv = to_i915(dev);
4960         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4961         int pipe = intel_crtc->pipe;
4962
4963         /*
4964          * Gen2 reports pipe underruns whenever all planes are disabled.
4965          * So diasble underrun reporting before all the planes get disabled.
4966          * FIXME: Need to fix the logic to work when we turn off all planes
4967          * but leave the pipe running.
4968          */
4969         if (IS_GEN2(dev_priv))
4970                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
4971
4972         /*
4973          * FIXME IPS should be fine as long as one plane is
4974          * enabled, but in practice it seems to have problems
4975          * when going from primary only to sprite only and vice
4976          * versa.
4977          */
4978         hsw_disable_ips(intel_crtc);
4979 }
4980
4981 /* FIXME get rid of this and use pre_plane_update */
4982 static void
4983 intel_pre_disable_primary_noatomic(struct drm_crtc *crtc)
4984 {
4985         struct drm_device *dev = crtc->dev;
4986         struct drm_i915_private *dev_priv = to_i915(dev);
4987         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4988         int pipe = intel_crtc->pipe;
4989
4990         intel_pre_disable_primary(crtc);
4991
4992         /*
4993          * Vblank time updates from the shadow to live plane control register
4994          * are blocked if the memory self-refresh mode is active at that
4995          * moment. So to make sure the plane gets truly disabled, disable
4996          * first the self-refresh mode. The self-refresh enable bit in turn
4997          * will be checked/applied by the HW only at the next frame start
4998          * event which is after the vblank start event, so we need to have a
4999          * wait-for-vblank between disabling the plane and the pipe.
5000          */
5001         if (HAS_GMCH_DISPLAY(dev_priv) &&
5002             intel_set_memory_cxsr(dev_priv, false))
5003                 intel_wait_for_vblank(dev_priv, pipe);
5004 }
5005
5006 static void intel_post_plane_update(struct intel_crtc_state *old_crtc_state)
5007 {
5008         struct intel_crtc *crtc = to_intel_crtc(old_crtc_state->base.crtc);
5009         struct drm_atomic_state *old_state = old_crtc_state->base.state;
5010         struct intel_crtc_state *pipe_config =
5011                 to_intel_crtc_state(crtc->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
5016         intel_frontbuffer_flip(to_i915(crtc->base.dev), pipe_config->fb_bits);
5017
5018         crtc->wm.cxsr_allowed = true;
5019
5020         if (pipe_config->update_wm_post && pipe_config->base.active)
5021                 intel_update_watermarks(crtc);
5022
5023         if (old_pri_state) {
5024                 struct intel_plane_state *primary_state =
5025                         to_intel_plane_state(primary->state);
5026                 struct intel_plane_state *old_primary_state =
5027                         to_intel_plane_state(old_pri_state);
5028
5029                 intel_fbc_post_update(crtc);
5030
5031                 if (primary_state->base.visible &&
5032                     (needs_modeset(&pipe_config->base) ||
5033                      !old_primary_state->base.visible))
5034                         intel_post_enable_primary(&crtc->base);
5035         }
5036 }
5037
5038 static void intel_pre_plane_update(struct intel_crtc_state *old_crtc_state)
5039 {
5040         struct intel_crtc *crtc = to_intel_crtc(old_crtc_state->base.crtc);
5041         struct drm_device *dev = crtc->base.dev;
5042         struct drm_i915_private *dev_priv = to_i915(dev);
5043         struct intel_crtc_state *pipe_config =
5044                 to_intel_crtc_state(crtc->base.state);
5045         struct drm_atomic_state *old_state = old_crtc_state->base.state;
5046         struct drm_plane *primary = crtc->base.primary;
5047         struct drm_plane_state *old_pri_state =
5048                 drm_atomic_get_existing_plane_state(old_state, primary);
5049         bool modeset = needs_modeset(&pipe_config->base);
5050         struct intel_atomic_state *old_intel_state =
5051                 to_intel_atomic_state(old_state);
5052
5053         if (old_pri_state) {
5054                 struct intel_plane_state *primary_state =
5055                         to_intel_plane_state(primary->state);
5056                 struct intel_plane_state *old_primary_state =
5057                         to_intel_plane_state(old_pri_state);
5058
5059                 intel_fbc_pre_update(crtc, pipe_config, primary_state);
5060
5061                 if (old_primary_state->base.visible &&
5062                     (modeset || !primary_state->base.visible))
5063                         intel_pre_disable_primary(&crtc->base);
5064         }
5065
5066         if (pipe_config->disable_cxsr && HAS_GMCH_DISPLAY(dev_priv)) {
5067                 crtc->wm.cxsr_allowed = false;
5068
5069                 /*
5070                  * Vblank time updates from the shadow to live plane control register
5071                  * are blocked if the memory self-refresh mode is active at that
5072                  * moment. So to make sure the plane gets truly disabled, disable
5073                  * first the self-refresh mode. The self-refresh enable bit in turn
5074                  * will be checked/applied by the HW only at the next frame start
5075                  * event which is after the vblank start event, so we need to have a
5076                  * wait-for-vblank between disabling the plane and the pipe.
5077                  */
5078                 if (old_crtc_state->base.active &&
5079                     intel_set_memory_cxsr(dev_priv, false))
5080                         intel_wait_for_vblank(dev_priv, crtc->pipe);
5081         }
5082
5083         /*
5084          * IVB workaround: must disable low power watermarks for at least
5085          * one frame before enabling scaling.  LP watermarks can be re-enabled
5086          * when scaling is disabled.
5087          *
5088          * WaCxSRDisabledForSpriteScaling:ivb
5089          */
5090         if (pipe_config->disable_lp_wm && ilk_disable_lp_wm(dev))
5091                 intel_wait_for_vblank(dev_priv, crtc->pipe);
5092
5093         /*
5094          * If we're doing a modeset, we're done.  No need to do any pre-vblank
5095          * watermark programming here.
5096          */
5097         if (needs_modeset(&pipe_config->base))
5098                 return;
5099
5100         /*
5101          * For platforms that support atomic watermarks, program the
5102          * 'intermediate' watermarks immediately.  On pre-gen9 platforms, these
5103          * will be the intermediate values that are safe for both pre- and
5104          * post- vblank; when vblank happens, the 'active' values will be set
5105          * to the final 'target' values and we'll do this again to get the
5106          * optimal watermarks.  For gen9+ platforms, the values we program here
5107          * will be the final target values which will get automatically latched
5108          * at vblank time; no further programming will be necessary.
5109          *
5110          * If a platform hasn't been transitioned to atomic watermarks yet,
5111          * we'll continue to update watermarks the old way, if flags tell
5112          * us to.
5113          */
5114         if (dev_priv->display.initial_watermarks != NULL)
5115                 dev_priv->display.initial_watermarks(old_intel_state,
5116                                                      pipe_config);
5117         else if (pipe_config->update_wm_pre)
5118                 intel_update_watermarks(crtc);
5119 }
5120
5121 static void intel_crtc_disable_planes(struct drm_crtc *crtc, unsigned plane_mask)
5122 {
5123         struct drm_device *dev = crtc->dev;
5124         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5125         struct drm_plane *p;
5126         int pipe = intel_crtc->pipe;
5127
5128         intel_crtc_dpms_overlay_disable(intel_crtc);
5129
5130         drm_for_each_plane_mask(p, dev, plane_mask)
5131                 to_intel_plane(p)->disable_plane(p, crtc);
5132
5133         /*
5134          * FIXME: Once we grow proper nuclear flip support out of this we need
5135          * to compute the mask of flip planes precisely. For the time being
5136          * consider this a flip to a NULL plane.
5137          */
5138         intel_frontbuffer_flip(to_i915(dev), INTEL_FRONTBUFFER_ALL_MASK(pipe));
5139 }
5140
5141 static void intel_encoders_pre_pll_enable(struct drm_crtc *crtc,
5142                                           struct intel_crtc_state *crtc_state,
5143                                           struct drm_atomic_state *old_state)
5144 {
5145         struct drm_connector_state *old_conn_state;
5146         struct drm_connector *conn;
5147         int i;
5148
5149         for_each_connector_in_state(old_state, conn, old_conn_state, i) {
5150                 struct drm_connector_state *conn_state = conn->state;
5151                 struct intel_encoder *encoder =
5152                         to_intel_encoder(conn_state->best_encoder);
5153
5154                 if (conn_state->crtc != crtc)
5155                         continue;
5156
5157                 if (encoder->pre_pll_enable)
5158                         encoder->pre_pll_enable(encoder, crtc_state, conn_state);
5159         }
5160 }
5161
5162 static void intel_encoders_pre_enable(struct drm_crtc *crtc,
5163                                       struct intel_crtc_state *crtc_state,
5164                                       struct drm_atomic_state *old_state)
5165 {
5166         struct drm_connector_state *old_conn_state;
5167         struct drm_connector *conn;
5168         int i;
5169
5170         for_each_connector_in_state(old_state, conn, old_conn_state, i) {
5171                 struct drm_connector_state *conn_state = conn->state;
5172                 struct intel_encoder *encoder =
5173                         to_intel_encoder(conn_state->best_encoder);
5174
5175                 if (conn_state->crtc != crtc)
5176                         continue;
5177
5178                 if (encoder->pre_enable)
5179                         encoder->pre_enable(encoder, crtc_state, conn_state);
5180         }
5181 }
5182
5183 static void intel_encoders_enable(struct drm_crtc *crtc,
5184                                   struct intel_crtc_state *crtc_state,
5185                                   struct drm_atomic_state *old_state)
5186 {
5187         struct drm_connector_state *old_conn_state;
5188         struct drm_connector *conn;
5189         int i;
5190
5191         for_each_connector_in_state(old_state, conn, old_conn_state, i) {
5192                 struct drm_connector_state *conn_state = conn->state;
5193                 struct intel_encoder *encoder =
5194                         to_intel_encoder(conn_state->best_encoder);
5195
5196                 if (conn_state->crtc != crtc)
5197                         continue;
5198
5199                 encoder->enable(encoder, crtc_state, conn_state);
5200                 intel_opregion_notify_encoder(encoder, true);
5201         }
5202 }
5203
5204 static void intel_encoders_disable(struct drm_crtc *crtc,
5205                                    struct intel_crtc_state *old_crtc_state,
5206                                    struct drm_atomic_state *old_state)
5207 {
5208         struct drm_connector_state *old_conn_state;
5209         struct drm_connector *conn;
5210         int i;
5211
5212         for_each_connector_in_state(old_state, conn, old_conn_state, i) {
5213                 struct intel_encoder *encoder =
5214                         to_intel_encoder(old_conn_state->best_encoder);
5215
5216                 if (old_conn_state->crtc != crtc)
5217                         continue;
5218
5219                 intel_opregion_notify_encoder(encoder, false);
5220                 encoder->disable(encoder, old_crtc_state, old_conn_state);
5221         }
5222 }
5223
5224 static void intel_encoders_post_disable(struct drm_crtc *crtc,
5225                                         struct intel_crtc_state *old_crtc_state,
5226                                         struct drm_atomic_state *old_state)
5227 {
5228         struct drm_connector_state *old_conn_state;
5229         struct drm_connector *conn;
5230         int i;
5231
5232         for_each_connector_in_state(old_state, conn, old_conn_state, i) {
5233                 struct intel_encoder *encoder =
5234                         to_intel_encoder(old_conn_state->best_encoder);
5235
5236                 if (old_conn_state->crtc != crtc)
5237                         continue;
5238
5239                 if (encoder->post_disable)
5240                         encoder->post_disable(encoder, old_crtc_state, old_conn_state);
5241         }
5242 }
5243
5244 static void intel_encoders_post_pll_disable(struct drm_crtc *crtc,
5245                                             struct intel_crtc_state *old_crtc_state,
5246                                             struct drm_atomic_state *old_state)
5247 {
5248         struct drm_connector_state *old_conn_state;
5249         struct drm_connector *conn;
5250         int i;
5251
5252         for_each_connector_in_state(old_state, conn, old_conn_state, i) {
5253                 struct intel_encoder *encoder =
5254                         to_intel_encoder(old_conn_state->best_encoder);
5255
5256                 if (old_conn_state->crtc != crtc)
5257                         continue;
5258
5259                 if (encoder->post_pll_disable)
5260                         encoder->post_pll_disable(encoder, old_crtc_state, old_conn_state);
5261         }
5262 }
5263
5264 static void ironlake_crtc_enable(struct intel_crtc_state *pipe_config,
5265                                  struct drm_atomic_state *old_state)
5266 {
5267         struct drm_crtc *crtc = pipe_config->base.crtc;
5268         struct drm_device *dev = crtc->dev;
5269         struct drm_i915_private *dev_priv = to_i915(dev);
5270         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5271         int pipe = intel_crtc->pipe;
5272         struct intel_atomic_state *old_intel_state =
5273                 to_intel_atomic_state(old_state);
5274
5275         if (WARN_ON(intel_crtc->active))
5276                 return;
5277
5278         /*
5279          * Sometimes spurious CPU pipe underruns happen during FDI
5280          * training, at least with VGA+HDMI cloning. Suppress them.
5281          *
5282          * On ILK we get an occasional spurious CPU pipe underruns
5283          * between eDP port A enable and vdd enable. Also PCH port
5284          * enable seems to result in the occasional CPU pipe underrun.
5285          *
5286          * Spurious PCH underruns also occur during PCH enabling.
5287          */
5288         if (intel_crtc->config->has_pch_encoder || IS_GEN5(dev_priv))
5289                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
5290         if (intel_crtc->config->has_pch_encoder)
5291                 intel_set_pch_fifo_underrun_reporting(dev_priv, pipe, false);
5292
5293         if (intel_crtc->config->has_pch_encoder)
5294                 intel_prepare_shared_dpll(intel_crtc);
5295
5296         if (intel_crtc_has_dp_encoder(intel_crtc->config))
5297                 intel_dp_set_m_n(intel_crtc, M1_N1);
5298
5299         intel_set_pipe_timings(intel_crtc);
5300         intel_set_pipe_src_size(intel_crtc);
5301
5302         if (intel_crtc->config->has_pch_encoder) {
5303                 intel_cpu_transcoder_set_m_n(intel_crtc,
5304                                      &intel_crtc->config->fdi_m_n, NULL);
5305         }
5306
5307         ironlake_set_pipeconf(crtc);
5308
5309         intel_crtc->active = true;
5310
5311         intel_encoders_pre_enable(crtc, pipe_config, old_state);
5312
5313         if (intel_crtc->config->has_pch_encoder) {
5314                 /* Note: FDI PLL enabling _must_ be done before we enable the
5315                  * cpu pipes, hence this is separate from all the other fdi/pch
5316                  * enabling. */
5317                 ironlake_fdi_pll_enable(intel_crtc);
5318         } else {
5319                 assert_fdi_tx_disabled(dev_priv, pipe);
5320                 assert_fdi_rx_disabled(dev_priv, pipe);
5321         }
5322
5323         ironlake_pfit_enable(intel_crtc);
5324
5325         /*
5326          * On ILK+ LUT must be loaded before the pipe is running but with
5327          * clocks enabled
5328          */
5329         intel_color_load_luts(&pipe_config->base);
5330
5331         if (dev_priv->display.initial_watermarks != NULL)
5332                 dev_priv->display.initial_watermarks(old_intel_state, intel_crtc->config);
5333         intel_enable_pipe(intel_crtc);
5334
5335         if (intel_crtc->config->has_pch_encoder)
5336                 ironlake_pch_enable(crtc);
5337
5338         assert_vblank_disabled(crtc);
5339         drm_crtc_vblank_on(crtc);
5340
5341         intel_encoders_enable(crtc, pipe_config, old_state);
5342
5343         if (HAS_PCH_CPT(dev_priv))
5344                 cpt_verify_modeset(dev, intel_crtc->pipe);
5345
5346         /* Must wait for vblank to avoid spurious PCH FIFO underruns */
5347         if (intel_crtc->config->has_pch_encoder)
5348                 intel_wait_for_vblank(dev_priv, pipe);
5349         intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
5350         intel_set_pch_fifo_underrun_reporting(dev_priv, pipe, true);
5351 }
5352
5353 /* IPS only exists on ULT machines and is tied to pipe A. */
5354 static bool hsw_crtc_supports_ips(struct intel_crtc *crtc)
5355 {
5356         return HAS_IPS(to_i915(crtc->base.dev)) && crtc->pipe == PIPE_A;
5357 }
5358
5359 static void haswell_crtc_enable(struct intel_crtc_state *pipe_config,
5360                                 struct drm_atomic_state *old_state)
5361 {
5362         struct drm_crtc *crtc = pipe_config->base.crtc;
5363         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
5364         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5365         int pipe = intel_crtc->pipe, hsw_workaround_pipe;
5366         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
5367         struct intel_atomic_state *old_intel_state =
5368                 to_intel_atomic_state(old_state);
5369
5370         if (WARN_ON(intel_crtc->active))
5371                 return;
5372
5373         if (intel_crtc->config->has_pch_encoder)
5374                 intel_set_pch_fifo_underrun_reporting(dev_priv, TRANSCODER_A,
5375                                                       false);
5376
5377         intel_encoders_pre_pll_enable(crtc, pipe_config, old_state);
5378
5379         if (intel_crtc->config->shared_dpll)
5380                 intel_enable_shared_dpll(intel_crtc);
5381
5382         if (intel_crtc_has_dp_encoder(intel_crtc->config))
5383                 intel_dp_set_m_n(intel_crtc, M1_N1);
5384
5385         if (!transcoder_is_dsi(cpu_transcoder))
5386                 intel_set_pipe_timings(intel_crtc);
5387
5388         intel_set_pipe_src_size(intel_crtc);
5389
5390         if (cpu_transcoder != TRANSCODER_EDP &&
5391             !transcoder_is_dsi(cpu_transcoder)) {
5392                 I915_WRITE(PIPE_MULT(cpu_transcoder),
5393                            intel_crtc->config->pixel_multiplier - 1);
5394         }
5395
5396         if (intel_crtc->config->has_pch_encoder) {
5397                 intel_cpu_transcoder_set_m_n(intel_crtc,
5398                                      &intel_crtc->config->fdi_m_n, NULL);
5399         }
5400
5401         if (!transcoder_is_dsi(cpu_transcoder))
5402                 haswell_set_pipeconf(crtc);
5403
5404         haswell_set_pipemisc(crtc);
5405
5406         intel_color_set_csc(&pipe_config->base);
5407
5408         intel_crtc->active = true;
5409
5410         if (intel_crtc->config->has_pch_encoder)
5411                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
5412         else
5413                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
5414
5415         intel_encoders_pre_enable(crtc, pipe_config, old_state);
5416
5417         if (intel_crtc->config->has_pch_encoder)
5418                 dev_priv->display.fdi_link_train(crtc);
5419
5420         if (!transcoder_is_dsi(cpu_transcoder))
5421                 intel_ddi_enable_pipe_clock(intel_crtc);
5422
5423         if (INTEL_GEN(dev_priv) >= 9)
5424                 skylake_pfit_enable(intel_crtc);
5425         else
5426                 ironlake_pfit_enable(intel_crtc);
5427
5428         /*
5429          * On ILK+ LUT must be loaded before the pipe is running but with
5430          * clocks enabled
5431          */
5432         intel_color_load_luts(&pipe_config->base);
5433
5434         intel_ddi_set_pipe_settings(crtc);
5435         if (!transcoder_is_dsi(cpu_transcoder))
5436                 intel_ddi_enable_transcoder_func(crtc);
5437
5438         if (dev_priv->display.initial_watermarks != NULL)
5439                 dev_priv->display.initial_watermarks(old_intel_state, pipe_config);
5440
5441         /* XXX: Do the pipe assertions at the right place for BXT DSI. */
5442         if (!transcoder_is_dsi(cpu_transcoder))
5443                 intel_enable_pipe(intel_crtc);
5444
5445         if (intel_crtc->config->has_pch_encoder)
5446                 lpt_pch_enable(crtc);
5447
5448         if (intel_crtc_has_type(intel_crtc->config, INTEL_OUTPUT_DP_MST))
5449                 intel_ddi_set_vc_payload_alloc(crtc, true);
5450
5451         assert_vblank_disabled(crtc);
5452         drm_crtc_vblank_on(crtc);
5453
5454         intel_encoders_enable(crtc, pipe_config, old_state);
5455
5456         if (intel_crtc->config->has_pch_encoder) {
5457                 intel_wait_for_vblank(dev_priv, pipe);
5458                 intel_wait_for_vblank(dev_priv, pipe);
5459                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
5460                 intel_set_pch_fifo_underrun_reporting(dev_priv, TRANSCODER_A,
5461                                                       true);
5462         }
5463
5464         /* If we change the relative order between pipe/planes enabling, we need
5465          * to change the workaround. */
5466         hsw_workaround_pipe = pipe_config->hsw_workaround_pipe;
5467         if (IS_HASWELL(dev_priv) && hsw_workaround_pipe != INVALID_PIPE) {
5468                 intel_wait_for_vblank(dev_priv, hsw_workaround_pipe);
5469                 intel_wait_for_vblank(dev_priv, hsw_workaround_pipe);
5470         }
5471 }
5472
5473 static void ironlake_pfit_disable(struct intel_crtc *crtc, bool force)
5474 {
5475         struct drm_device *dev = crtc->base.dev;
5476         struct drm_i915_private *dev_priv = to_i915(dev);
5477         int pipe = crtc->pipe;
5478
5479         /* To avoid upsetting the power well on haswell only disable the pfit if
5480          * it's in use. The hw state code will make sure we get this right. */
5481         if (force || crtc->config->pch_pfit.enabled) {
5482                 I915_WRITE(PF_CTL(pipe), 0);
5483                 I915_WRITE(PF_WIN_POS(pipe), 0);
5484                 I915_WRITE(PF_WIN_SZ(pipe), 0);
5485         }
5486 }
5487
5488 static void ironlake_crtc_disable(struct intel_crtc_state *old_crtc_state,
5489                                   struct drm_atomic_state *old_state)
5490 {
5491         struct drm_crtc *crtc = old_crtc_state->base.crtc;
5492         struct drm_device *dev = crtc->dev;
5493         struct drm_i915_private *dev_priv = to_i915(dev);
5494         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5495         int pipe = intel_crtc->pipe;
5496
5497         /*
5498          * Sometimes spurious CPU pipe underruns happen when the
5499          * pipe is already disabled, but FDI RX/TX is still enabled.
5500          * Happens at least with VGA+HDMI cloning. Suppress them.
5501          */
5502         if (intel_crtc->config->has_pch_encoder) {
5503                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
5504                 intel_set_pch_fifo_underrun_reporting(dev_priv, pipe, false);
5505         }
5506
5507         intel_encoders_disable(crtc, old_crtc_state, old_state);
5508
5509         drm_crtc_vblank_off(crtc);
5510         assert_vblank_disabled(crtc);
5511
5512         intel_disable_pipe(intel_crtc);
5513
5514         ironlake_pfit_disable(intel_crtc, false);
5515
5516         if (intel_crtc->config->has_pch_encoder)
5517                 ironlake_fdi_disable(crtc);
5518
5519         intel_encoders_post_disable(crtc, old_crtc_state, old_state);
5520
5521         if (intel_crtc->config->has_pch_encoder) {
5522                 ironlake_disable_pch_transcoder(dev_priv, pipe);
5523
5524                 if (HAS_PCH_CPT(dev_priv)) {
5525                         i915_reg_t reg;
5526                         u32 temp;
5527
5528                         /* disable TRANS_DP_CTL */
5529                         reg = TRANS_DP_CTL(pipe);
5530                         temp = I915_READ(reg);
5531                         temp &= ~(TRANS_DP_OUTPUT_ENABLE |
5532                                   TRANS_DP_PORT_SEL_MASK);
5533                         temp |= TRANS_DP_PORT_SEL_NONE;
5534                         I915_WRITE(reg, temp);
5535
5536                         /* disable DPLL_SEL */
5537                         temp = I915_READ(PCH_DPLL_SEL);
5538                         temp &= ~(TRANS_DPLL_ENABLE(pipe) | TRANS_DPLLB_SEL(pipe));
5539                         I915_WRITE(PCH_DPLL_SEL, temp);
5540                 }
5541
5542                 ironlake_fdi_pll_disable(intel_crtc);
5543         }
5544
5545         intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
5546         intel_set_pch_fifo_underrun_reporting(dev_priv, pipe, true);
5547 }
5548
5549 static void haswell_crtc_disable(struct intel_crtc_state *old_crtc_state,
5550                                  struct drm_atomic_state *old_state)
5551 {
5552         struct drm_crtc *crtc = old_crtc_state->base.crtc;
5553         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
5554         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5555         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
5556
5557         if (intel_crtc->config->has_pch_encoder)
5558                 intel_set_pch_fifo_underrun_reporting(dev_priv, TRANSCODER_A,
5559                                                       false);
5560
5561         intel_encoders_disable(crtc, old_crtc_state, old_state);
5562
5563         drm_crtc_vblank_off(crtc);
5564         assert_vblank_disabled(crtc);
5565
5566         /* XXX: Do the pipe assertions at the right place for BXT DSI. */
5567         if (!transcoder_is_dsi(cpu_transcoder))
5568                 intel_disable_pipe(intel_crtc);
5569
5570         if (intel_crtc_has_type(intel_crtc->config, INTEL_OUTPUT_DP_MST))
5571                 intel_ddi_set_vc_payload_alloc(crtc, false);
5572
5573         if (!transcoder_is_dsi(cpu_transcoder))
5574                 intel_ddi_disable_transcoder_func(dev_priv, cpu_transcoder);
5575
5576         if (INTEL_GEN(dev_priv) >= 9)
5577                 skylake_scaler_disable(intel_crtc);
5578         else
5579                 ironlake_pfit_disable(intel_crtc, false);
5580
5581         if (!transcoder_is_dsi(cpu_transcoder))
5582                 intel_ddi_disable_pipe_clock(intel_crtc);
5583
5584         intel_encoders_post_disable(crtc, old_crtc_state, old_state);
5585
5586         if (old_crtc_state->has_pch_encoder)
5587                 intel_set_pch_fifo_underrun_reporting(dev_priv, TRANSCODER_A,
5588                                                       true);
5589 }
5590
5591 static void i9xx_pfit_enable(struct intel_crtc *crtc)
5592 {
5593         struct drm_device *dev = crtc->base.dev;
5594         struct drm_i915_private *dev_priv = to_i915(dev);
5595         struct intel_crtc_state *pipe_config = crtc->config;
5596
5597         if (!pipe_config->gmch_pfit.control)
5598                 return;
5599
5600         /*
5601          * The panel fitter should only be adjusted whilst the pipe is disabled,
5602          * according to register description and PRM.
5603          */
5604         WARN_ON(I915_READ(PFIT_CONTROL) & PFIT_ENABLE);
5605         assert_pipe_disabled(dev_priv, crtc->pipe);
5606
5607         I915_WRITE(PFIT_PGM_RATIOS, pipe_config->gmch_pfit.pgm_ratios);
5608         I915_WRITE(PFIT_CONTROL, pipe_config->gmch_pfit.control);
5609
5610         /* Border color in case we don't scale up to the full screen. Black by
5611          * default, change to something else for debugging. */
5612         I915_WRITE(BCLRPAT(crtc->pipe), 0);
5613 }
5614
5615 static enum intel_display_power_domain port_to_power_domain(enum port port)
5616 {
5617         switch (port) {
5618         case PORT_A:
5619                 return POWER_DOMAIN_PORT_DDI_A_LANES;
5620         case PORT_B:
5621                 return POWER_DOMAIN_PORT_DDI_B_LANES;
5622         case PORT_C:
5623                 return POWER_DOMAIN_PORT_DDI_C_LANES;
5624         case PORT_D:
5625                 return POWER_DOMAIN_PORT_DDI_D_LANES;
5626         case PORT_E:
5627                 return POWER_DOMAIN_PORT_DDI_E_LANES;
5628         default:
5629                 MISSING_CASE(port);
5630                 return POWER_DOMAIN_PORT_OTHER;
5631         }
5632 }
5633
5634 static enum intel_display_power_domain port_to_aux_power_domain(enum port port)
5635 {
5636         switch (port) {
5637         case PORT_A:
5638                 return POWER_DOMAIN_AUX_A;
5639         case PORT_B:
5640                 return POWER_DOMAIN_AUX_B;
5641         case PORT_C:
5642                 return POWER_DOMAIN_AUX_C;
5643         case PORT_D:
5644                 return POWER_DOMAIN_AUX_D;
5645         case PORT_E:
5646                 /* FIXME: Check VBT for actual wiring of PORT E */
5647                 return POWER_DOMAIN_AUX_D;
5648         default:
5649                 MISSING_CASE(port);
5650                 return POWER_DOMAIN_AUX_A;
5651         }
5652 }
5653
5654 enum intel_display_power_domain
5655 intel_display_port_power_domain(struct intel_encoder *intel_encoder)
5656 {
5657         struct drm_i915_private *dev_priv = to_i915(intel_encoder->base.dev);
5658         struct intel_digital_port *intel_dig_port;
5659
5660         switch (intel_encoder->type) {
5661         case INTEL_OUTPUT_UNKNOWN:
5662                 /* Only DDI platforms should ever use this output type */
5663                 WARN_ON_ONCE(!HAS_DDI(dev_priv));
5664         case INTEL_OUTPUT_DP:
5665         case INTEL_OUTPUT_HDMI:
5666         case INTEL_OUTPUT_EDP:
5667                 intel_dig_port = enc_to_dig_port(&intel_encoder->base);
5668                 return port_to_power_domain(intel_dig_port->port);
5669         case INTEL_OUTPUT_DP_MST:
5670                 intel_dig_port = enc_to_mst(&intel_encoder->base)->primary;
5671                 return port_to_power_domain(intel_dig_port->port);
5672         case INTEL_OUTPUT_ANALOG:
5673                 return POWER_DOMAIN_PORT_CRT;
5674         case INTEL_OUTPUT_DSI:
5675                 return POWER_DOMAIN_PORT_DSI;
5676         default:
5677                 return POWER_DOMAIN_PORT_OTHER;
5678         }
5679 }
5680
5681 enum intel_display_power_domain
5682 intel_display_port_aux_power_domain(struct intel_encoder *intel_encoder)
5683 {
5684         struct drm_i915_private *dev_priv = to_i915(intel_encoder->base.dev);
5685         struct intel_digital_port *intel_dig_port;
5686
5687         switch (intel_encoder->type) {
5688         case INTEL_OUTPUT_UNKNOWN:
5689         case INTEL_OUTPUT_HDMI:
5690                 /*
5691                  * Only DDI platforms should ever use these output types.
5692                  * We can get here after the HDMI detect code has already set
5693                  * the type of the shared encoder. Since we can't be sure
5694                  * what's the status of the given connectors, play safe and
5695                  * run the DP detection too.
5696                  */
5697                 WARN_ON_ONCE(!HAS_DDI(dev_priv));
5698         case INTEL_OUTPUT_DP:
5699         case INTEL_OUTPUT_EDP:
5700                 intel_dig_port = enc_to_dig_port(&intel_encoder->base);
5701                 return port_to_aux_power_domain(intel_dig_port->port);
5702         case INTEL_OUTPUT_DP_MST:
5703                 intel_dig_port = enc_to_mst(&intel_encoder->base)->primary;
5704                 return port_to_aux_power_domain(intel_dig_port->port);
5705         default:
5706                 MISSING_CASE(intel_encoder->type);
5707                 return POWER_DOMAIN_AUX_A;
5708         }
5709 }
5710
5711 static unsigned long get_crtc_power_domains(struct drm_crtc *crtc,
5712                                             struct intel_crtc_state *crtc_state)
5713 {
5714         struct drm_device *dev = crtc->dev;
5715         struct drm_encoder *encoder;
5716         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5717         enum pipe pipe = intel_crtc->pipe;
5718         unsigned long mask;
5719         enum transcoder transcoder = crtc_state->cpu_transcoder;
5720
5721         if (!crtc_state->base.active)
5722                 return 0;
5723
5724         mask = BIT(POWER_DOMAIN_PIPE(pipe));
5725         mask |= BIT(POWER_DOMAIN_TRANSCODER(transcoder));
5726         if (crtc_state->pch_pfit.enabled ||
5727             crtc_state->pch_pfit.force_thru)
5728                 mask |= BIT(POWER_DOMAIN_PIPE_PANEL_FITTER(pipe));
5729
5730         drm_for_each_encoder_mask(encoder, dev, crtc_state->base.encoder_mask) {
5731                 struct intel_encoder *intel_encoder = to_intel_encoder(encoder);
5732
5733                 mask |= BIT(intel_display_port_power_domain(intel_encoder));
5734         }
5735
5736         if (crtc_state->shared_dpll)
5737                 mask |= BIT(POWER_DOMAIN_PLLS);
5738
5739         return mask;
5740 }
5741
5742 static unsigned long
5743 modeset_get_crtc_power_domains(struct drm_crtc *crtc,
5744                                struct intel_crtc_state *crtc_state)
5745 {
5746         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
5747         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5748         enum intel_display_power_domain domain;
5749         unsigned long domains, new_domains, old_domains;
5750
5751         old_domains = intel_crtc->enabled_power_domains;
5752         intel_crtc->enabled_power_domains = new_domains =
5753                 get_crtc_power_domains(crtc, crtc_state);
5754
5755         domains = new_domains & ~old_domains;
5756
5757         for_each_power_domain(domain, domains)
5758                 intel_display_power_get(dev_priv, domain);
5759
5760         return old_domains & ~new_domains;
5761 }
5762
5763 static void modeset_put_power_domains(struct drm_i915_private *dev_priv,
5764                                       unsigned long domains)
5765 {
5766         enum intel_display_power_domain domain;
5767
5768         for_each_power_domain(domain, domains)
5769                 intel_display_power_put(dev_priv, domain);
5770 }
5771
5772 static int intel_compute_max_dotclk(struct drm_i915_private *dev_priv)
5773 {
5774         int max_cdclk_freq = dev_priv->max_cdclk_freq;
5775
5776         if (IS_GEMINILAKE(dev_priv))
5777                 return 2 * max_cdclk_freq;
5778         else if (INTEL_INFO(dev_priv)->gen >= 9 ||
5779                  IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv))
5780                 return max_cdclk_freq;
5781         else if (IS_CHERRYVIEW(dev_priv))
5782                 return max_cdclk_freq*95/100;
5783         else if (INTEL_INFO(dev_priv)->gen < 4)
5784                 return 2*max_cdclk_freq*90/100;
5785         else
5786                 return max_cdclk_freq*90/100;
5787 }
5788
5789 static int skl_calc_cdclk(int max_pixclk, int vco);
5790
5791 static void intel_update_max_cdclk(struct drm_i915_private *dev_priv)
5792 {
5793         if (IS_SKYLAKE(dev_priv) || IS_KABYLAKE(dev_priv)) {
5794                 u32 limit = I915_READ(SKL_DFSM) & SKL_DFSM_CDCLK_LIMIT_MASK;
5795                 int max_cdclk, vco;
5796
5797                 vco = dev_priv->skl_preferred_vco_freq;
5798                 WARN_ON(vco != 8100000 && vco != 8640000);
5799
5800                 /*
5801                  * Use the lower (vco 8640) cdclk values as a
5802                  * first guess. skl_calc_cdclk() will correct it
5803                  * if the preferred vco is 8100 instead.
5804                  */
5805                 if (limit == SKL_DFSM_CDCLK_LIMIT_675)
5806                         max_cdclk = 617143;
5807                 else if (limit == SKL_DFSM_CDCLK_LIMIT_540)
5808                         max_cdclk = 540000;
5809                 else if (limit == SKL_DFSM_CDCLK_LIMIT_450)
5810                         max_cdclk = 432000;
5811                 else
5812                         max_cdclk = 308571;
5813
5814                 dev_priv->max_cdclk_freq = skl_calc_cdclk(max_cdclk, vco);
5815         } else if (IS_GEMINILAKE(dev_priv)) {
5816                 dev_priv->max_cdclk_freq = 316800;
5817         } else if (IS_BROXTON(dev_priv)) {
5818                 dev_priv->max_cdclk_freq = 624000;
5819         } else if (IS_BROADWELL(dev_priv))  {
5820                 /*
5821                  * FIXME with extra cooling we can allow
5822                  * 540 MHz for ULX and 675 Mhz for ULT.
5823                  * How can we know if extra cooling is
5824                  * available? PCI ID, VTB, something else?
5825                  */
5826                 if (I915_READ(FUSE_STRAP) & HSW_CDCLK_LIMIT)
5827                         dev_priv->max_cdclk_freq = 450000;
5828                 else if (IS_BDW_ULX(dev_priv))
5829                         dev_priv->max_cdclk_freq = 450000;
5830                 else if (IS_BDW_ULT(dev_priv))
5831                         dev_priv->max_cdclk_freq = 540000;
5832                 else
5833                         dev_priv->max_cdclk_freq = 675000;
5834         } else if (IS_CHERRYVIEW(dev_priv)) {
5835                 dev_priv->max_cdclk_freq = 320000;
5836         } else if (IS_VALLEYVIEW(dev_priv)) {
5837                 dev_priv->max_cdclk_freq = 400000;
5838         } else {
5839                 /* otherwise assume cdclk is fixed */
5840                 dev_priv->max_cdclk_freq = dev_priv->cdclk_freq;
5841         }
5842
5843         dev_priv->max_dotclk_freq = intel_compute_max_dotclk(dev_priv);
5844
5845         DRM_DEBUG_DRIVER("Max CD clock rate: %d kHz\n",
5846                          dev_priv->max_cdclk_freq);
5847
5848         DRM_DEBUG_DRIVER("Max dotclock rate: %d kHz\n",
5849                          dev_priv->max_dotclk_freq);
5850 }
5851
5852 static void intel_update_cdclk(struct drm_i915_private *dev_priv)
5853 {
5854         dev_priv->cdclk_freq = dev_priv->display.get_display_clock_speed(dev_priv);
5855
5856         if (INTEL_GEN(dev_priv) >= 9)
5857                 DRM_DEBUG_DRIVER("Current CD clock rate: %d kHz, VCO: %d kHz, ref: %d kHz\n",
5858                                  dev_priv->cdclk_freq, dev_priv->cdclk_pll.vco,
5859                                  dev_priv->cdclk_pll.ref);
5860         else
5861                 DRM_DEBUG_DRIVER("Current CD clock rate: %d kHz\n",
5862                                  dev_priv->cdclk_freq);
5863
5864         /*
5865          * 9:0 CMBUS [sic] CDCLK frequency (cdfreq):
5866          * Programmng [sic] note: bit[9:2] should be programmed to the number
5867          * of cdclk that generates 4MHz reference clock freq which is used to
5868          * generate GMBus clock. This will vary with the cdclk freq.
5869          */
5870         if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
5871                 I915_WRITE(GMBUSFREQ_VLV, DIV_ROUND_UP(dev_priv->cdclk_freq, 1000));
5872 }
5873
5874 /* convert from kHz to .1 fixpoint MHz with -1MHz offset */
5875 static int skl_cdclk_decimal(int cdclk)
5876 {
5877         return DIV_ROUND_CLOSEST(cdclk - 1000, 500);
5878 }
5879
5880 static int bxt_de_pll_vco(struct drm_i915_private *dev_priv, int cdclk)
5881 {
5882         int ratio;
5883
5884         if (cdclk == dev_priv->cdclk_pll.ref)
5885                 return 0;
5886
5887         switch (cdclk) {
5888         default:
5889                 MISSING_CASE(cdclk);
5890         case 144000:
5891         case 288000:
5892         case 384000:
5893         case 576000:
5894                 ratio = 60;
5895                 break;
5896         case 624000:
5897                 ratio = 65;
5898                 break;
5899         }
5900
5901         return dev_priv->cdclk_pll.ref * ratio;
5902 }
5903
5904 static int glk_de_pll_vco(struct drm_i915_private *dev_priv, int cdclk)
5905 {
5906         int ratio;
5907
5908         if (cdclk == dev_priv->cdclk_pll.ref)
5909                 return 0;
5910
5911         switch (cdclk) {
5912         default:
5913                 MISSING_CASE(cdclk);
5914         case  79200:
5915         case 158400:
5916         case 316800:
5917                 ratio = 33;
5918                 break;
5919         }
5920
5921         return dev_priv->cdclk_pll.ref * ratio;
5922 }
5923
5924 static void bxt_de_pll_disable(struct drm_i915_private *dev_priv)
5925 {
5926         I915_WRITE(BXT_DE_PLL_ENABLE, 0);
5927
5928         /* Timeout 200us */
5929         if (intel_wait_for_register(dev_priv,
5930                                     BXT_DE_PLL_ENABLE, BXT_DE_PLL_LOCK, 0,
5931                                     1))
5932                 DRM_ERROR("timeout waiting for DE PLL unlock\n");
5933
5934         dev_priv->cdclk_pll.vco = 0;
5935 }
5936
5937 static void bxt_de_pll_enable(struct drm_i915_private *dev_priv, int vco)
5938 {
5939         int ratio = DIV_ROUND_CLOSEST(vco, dev_priv->cdclk_pll.ref);
5940         u32 val;
5941
5942         val = I915_READ(BXT_DE_PLL_CTL);
5943         val &= ~BXT_DE_PLL_RATIO_MASK;
5944         val |= BXT_DE_PLL_RATIO(ratio);
5945         I915_WRITE(BXT_DE_PLL_CTL, val);
5946
5947         I915_WRITE(BXT_DE_PLL_ENABLE, BXT_DE_PLL_PLL_ENABLE);
5948
5949         /* Timeout 200us */
5950         if (intel_wait_for_register(dev_priv,
5951                                     BXT_DE_PLL_ENABLE,
5952                                     BXT_DE_PLL_LOCK,
5953                                     BXT_DE_PLL_LOCK,
5954                                     1))
5955                 DRM_ERROR("timeout waiting for DE PLL lock\n");
5956
5957         dev_priv->cdclk_pll.vco = vco;
5958 }
5959
5960 static void bxt_set_cdclk(struct drm_i915_private *dev_priv, int cdclk)
5961 {
5962         u32 val, divider;
5963         int vco, ret;
5964
5965         if (IS_GEMINILAKE(dev_priv))
5966                 vco = glk_de_pll_vco(dev_priv, cdclk);
5967         else
5968                 vco = bxt_de_pll_vco(dev_priv, cdclk);
5969
5970         DRM_DEBUG_DRIVER("Changing CDCLK to %d kHz (VCO %d kHz)\n", cdclk, vco);
5971
5972         /* cdclk = vco / 2 / div{1,1.5,2,4} */
5973         switch (DIV_ROUND_CLOSEST(vco, cdclk)) {
5974         case 8:
5975                 divider = BXT_CDCLK_CD2X_DIV_SEL_4;
5976                 break;
5977         case 4:
5978                 divider = BXT_CDCLK_CD2X_DIV_SEL_2;
5979                 break;
5980         case 3:
5981                 WARN(IS_GEMINILAKE(dev_priv), "Unsupported divider\n");
5982                 divider = BXT_CDCLK_CD2X_DIV_SEL_1_5;
5983                 break;
5984         case 2:
5985                 divider = BXT_CDCLK_CD2X_DIV_SEL_1;
5986                 break;
5987         default:
5988                 WARN_ON(cdclk != dev_priv->cdclk_pll.ref);
5989                 WARN_ON(vco != 0);
5990
5991                 divider = BXT_CDCLK_CD2X_DIV_SEL_1;
5992                 break;
5993         }
5994
5995         /* Inform power controller of upcoming frequency change */
5996         mutex_lock(&dev_priv->rps.hw_lock);
5997         ret = sandybridge_pcode_write(dev_priv, HSW_PCODE_DE_WRITE_FREQ_REQ,
5998                                       0x80000000);
5999         mutex_unlock(&dev_priv->rps.hw_lock);
6000
6001         if (ret) {
6002                 DRM_ERROR("PCode CDCLK freq change notify failed (err %d, freq %d)\n",
6003                           ret, cdclk);
6004                 return;
6005         }
6006
6007         if (dev_priv->cdclk_pll.vco != 0 &&
6008             dev_priv->cdclk_pll.vco != vco)
6009                 bxt_de_pll_disable(dev_priv);
6010
6011         if (dev_priv->cdclk_pll.vco != vco)
6012                 bxt_de_pll_enable(dev_priv, vco);
6013
6014         val = divider | skl_cdclk_decimal(cdclk);
6015         /*
6016          * FIXME if only the cd2x divider needs changing, it could be done
6017          * without shutting off the pipe (if only one pipe is active).
6018          */
6019         val |= BXT_CDCLK_CD2X_PIPE_NONE;
6020         /*
6021          * Disable SSA Precharge when CD clock frequency < 500 MHz,
6022          * enable otherwise.
6023          */
6024         if (cdclk >= 500000)
6025                 val |= BXT_CDCLK_SSA_PRECHARGE_ENABLE;
6026         I915_WRITE(CDCLK_CTL, val);
6027
6028         mutex_lock(&dev_priv->rps.hw_lock);
6029         ret = sandybridge_pcode_write(dev_priv, HSW_PCODE_DE_WRITE_FREQ_REQ,
6030                                       DIV_ROUND_UP(cdclk, 25000));
6031         mutex_unlock(&dev_priv->rps.hw_lock);
6032
6033         if (ret) {
6034                 DRM_ERROR("PCode CDCLK freq set failed, (err %d, freq %d)\n",
6035                           ret, cdclk);
6036                 return;
6037         }
6038
6039         intel_update_cdclk(dev_priv);
6040 }
6041
6042 static void bxt_sanitize_cdclk(struct drm_i915_private *dev_priv)
6043 {
6044         u32 cdctl, expected;
6045
6046         intel_update_cdclk(dev_priv);
6047
6048         if (dev_priv->cdclk_pll.vco == 0 ||
6049             dev_priv->cdclk_freq == dev_priv->cdclk_pll.ref)
6050                 goto sanitize;
6051
6052         /* DPLL okay; verify the cdclock
6053          *
6054          * Some BIOS versions leave an incorrect decimal frequency value and
6055          * set reserved MBZ bits in CDCLK_CTL at least during exiting from S4,
6056          * so sanitize this register.
6057          */
6058         cdctl = I915_READ(CDCLK_CTL);
6059         /*
6060          * Let's ignore the pipe field, since BIOS could have configured the
6061          * dividers both synching to an active pipe, or asynchronously
6062          * (PIPE_NONE).
6063          */
6064         cdctl &= ~BXT_CDCLK_CD2X_PIPE_NONE;
6065
6066         expected = (cdctl & BXT_CDCLK_CD2X_DIV_SEL_MASK) |
6067                    skl_cdclk_decimal(dev_priv->cdclk_freq);
6068         /*
6069          * Disable SSA Precharge when CD clock frequency < 500 MHz,
6070          * enable otherwise.
6071          */
6072         if (dev_priv->cdclk_freq >= 500000)
6073                 expected |= BXT_CDCLK_SSA_PRECHARGE_ENABLE;
6074
6075         if (cdctl == expected)
6076                 /* All well; nothing to sanitize */
6077                 return;
6078
6079 sanitize:
6080         DRM_DEBUG_KMS("Sanitizing cdclk programmed by pre-os\n");
6081
6082         /* force cdclk programming */
6083         dev_priv->cdclk_freq = 0;
6084
6085         /* force full PLL disable + enable */
6086         dev_priv->cdclk_pll.vco = -1;
6087 }
6088
6089 void bxt_init_cdclk(struct drm_i915_private *dev_priv)
6090 {
6091         int cdclk;
6092
6093         bxt_sanitize_cdclk(dev_priv);
6094
6095         if (dev_priv->cdclk_freq != 0 && dev_priv->cdclk_pll.vco != 0)
6096                 return;
6097
6098         /*
6099          * FIXME:
6100          * - The initial CDCLK needs to be read from VBT.
6101          *   Need to make this change after VBT has changes for BXT.
6102          */
6103         if (IS_GEMINILAKE(dev_priv))
6104                 cdclk = glk_calc_cdclk(0);
6105         else
6106                 cdclk = bxt_calc_cdclk(0);
6107
6108         bxt_set_cdclk(dev_priv, cdclk);
6109 }
6110
6111 void bxt_uninit_cdclk(struct drm_i915_private *dev_priv)
6112 {
6113         bxt_set_cdclk(dev_priv, dev_priv->cdclk_pll.ref);
6114 }
6115
6116 static int skl_calc_cdclk(int max_pixclk, int vco)
6117 {
6118         if (vco == 8640000) {
6119                 if (max_pixclk > 540000)
6120                         return 617143;
6121                 else if (max_pixclk > 432000)
6122                         return 540000;
6123                 else if (max_pixclk > 308571)
6124                         return 432000;
6125                 else
6126                         return 308571;
6127         } else {
6128                 if (max_pixclk > 540000)
6129                         return 675000;
6130                 else if (max_pixclk > 450000)
6131                         return 540000;
6132                 else if (max_pixclk > 337500)
6133                         return 450000;
6134                 else
6135                         return 337500;
6136         }
6137 }
6138
6139 static void
6140 skl_dpll0_update(struct drm_i915_private *dev_priv)
6141 {
6142         u32 val;
6143
6144         dev_priv->cdclk_pll.ref = 24000;
6145         dev_priv->cdclk_pll.vco = 0;
6146
6147         val = I915_READ(LCPLL1_CTL);
6148         if ((val & LCPLL_PLL_ENABLE) == 0)
6149                 return;
6150
6151         if (WARN_ON((val & LCPLL_PLL_LOCK) == 0))
6152                 return;
6153
6154         val = I915_READ(DPLL_CTRL1);
6155
6156         if (WARN_ON((val & (DPLL_CTRL1_HDMI_MODE(SKL_DPLL0) |
6157                             DPLL_CTRL1_SSC(SKL_DPLL0) |
6158                             DPLL_CTRL1_OVERRIDE(SKL_DPLL0))) !=
6159                     DPLL_CTRL1_OVERRIDE(SKL_DPLL0)))
6160                 return;
6161
6162         switch (val & DPLL_CTRL1_LINK_RATE_MASK(SKL_DPLL0)) {
6163         case DPLL_CTRL1_LINK_RATE(DPLL_CTRL1_LINK_RATE_810, SKL_DPLL0):
6164         case DPLL_CTRL1_LINK_RATE(DPLL_CTRL1_LINK_RATE_1350, SKL_DPLL0):
6165         case DPLL_CTRL1_LINK_RATE(DPLL_CTRL1_LINK_RATE_1620, SKL_DPLL0):
6166         case DPLL_CTRL1_LINK_RATE(DPLL_CTRL1_LINK_RATE_2700, SKL_DPLL0):
6167                 dev_priv->cdclk_pll.vco = 8100000;
6168                 break;
6169         case DPLL_CTRL1_LINK_RATE(DPLL_CTRL1_LINK_RATE_1080, SKL_DPLL0):
6170         case DPLL_CTRL1_LINK_RATE(DPLL_CTRL1_LINK_RATE_2160, SKL_DPLL0):
6171                 dev_priv->cdclk_pll.vco = 8640000;
6172                 break;
6173         default:
6174                 MISSING_CASE(val & DPLL_CTRL1_LINK_RATE_MASK(SKL_DPLL0));
6175                 break;
6176         }
6177 }
6178
6179 void skl_set_preferred_cdclk_vco(struct drm_i915_private *dev_priv, int vco)
6180 {
6181         bool changed = dev_priv->skl_preferred_vco_freq != vco;
6182
6183         dev_priv->skl_preferred_vco_freq = vco;
6184
6185         if (changed)
6186                 intel_update_max_cdclk(dev_priv);
6187 }
6188
6189 static void
6190 skl_dpll0_enable(struct drm_i915_private *dev_priv, int vco)
6191 {
6192         int min_cdclk = skl_calc_cdclk(0, vco);
6193         u32 val;
6194
6195         WARN_ON(vco != 8100000 && vco != 8640000);
6196
6197         /* select the minimum CDCLK before enabling DPLL 0 */
6198         val = CDCLK_FREQ_337_308 | skl_cdclk_decimal(min_cdclk);
6199         I915_WRITE(CDCLK_CTL, val);
6200         POSTING_READ(CDCLK_CTL);
6201
6202         /*
6203          * We always enable DPLL0 with the lowest link rate possible, but still
6204          * taking into account the VCO required to operate the eDP panel at the
6205          * desired frequency. The usual DP link rates operate with a VCO of
6206          * 8100 while the eDP 1.4 alternate link rates need a VCO of 8640.
6207          * The modeset code is responsible for the selection of the exact link
6208          * rate later on, with the constraint of choosing a frequency that
6209          * works with vco.
6210          */
6211         val = I915_READ(DPLL_CTRL1);
6212
6213         val &= ~(DPLL_CTRL1_HDMI_MODE(SKL_DPLL0) | DPLL_CTRL1_SSC(SKL_DPLL0) |
6214                  DPLL_CTRL1_LINK_RATE_MASK(SKL_DPLL0));
6215         val |= DPLL_CTRL1_OVERRIDE(SKL_DPLL0);
6216         if (vco == 8640000)
6217                 val |= DPLL_CTRL1_LINK_RATE(DPLL_CTRL1_LINK_RATE_1080,
6218                                             SKL_DPLL0);
6219         else
6220                 val |= DPLL_CTRL1_LINK_RATE(DPLL_CTRL1_LINK_RATE_810,
6221                                             SKL_DPLL0);
6222
6223         I915_WRITE(DPLL_CTRL1, val);
6224         POSTING_READ(DPLL_CTRL1);
6225
6226         I915_WRITE(LCPLL1_CTL, I915_READ(LCPLL1_CTL) | LCPLL_PLL_ENABLE);
6227
6228         if (intel_wait_for_register(dev_priv,
6229                                     LCPLL1_CTL, LCPLL_PLL_LOCK, LCPLL_PLL_LOCK,
6230                                     5))
6231                 DRM_ERROR("DPLL0 not locked\n");
6232
6233         dev_priv->cdclk_pll.vco = vco;
6234
6235         /* We'll want to keep using the current vco from now on. */
6236         skl_set_preferred_cdclk_vco(dev_priv, vco);
6237 }
6238
6239 static void
6240 skl_dpll0_disable(struct drm_i915_private *dev_priv)
6241 {
6242         I915_WRITE(LCPLL1_CTL, I915_READ(LCPLL1_CTL) & ~LCPLL_PLL_ENABLE);
6243         if (intel_wait_for_register(dev_priv,
6244                                    LCPLL1_CTL, LCPLL_PLL_LOCK, 0,
6245                                    1))
6246                 DRM_ERROR("Couldn't disable DPLL0\n");
6247
6248         dev_priv->cdclk_pll.vco = 0;
6249 }
6250
6251 static void skl_set_cdclk(struct drm_i915_private *dev_priv, int cdclk, int vco)
6252 {
6253         u32 freq_select, pcu_ack;
6254         int ret;
6255
6256         WARN_ON((cdclk == 24000) != (vco == 0));
6257
6258         DRM_DEBUG_DRIVER("Changing CDCLK to %d kHz (VCO %d kHz)\n", cdclk, vco);
6259
6260         mutex_lock(&dev_priv->rps.hw_lock);
6261         ret = skl_pcode_request(dev_priv, SKL_PCODE_CDCLK_CONTROL,
6262                                 SKL_CDCLK_PREPARE_FOR_CHANGE,
6263                                 SKL_CDCLK_READY_FOR_CHANGE,
6264                                 SKL_CDCLK_READY_FOR_CHANGE, 3);
6265         mutex_unlock(&dev_priv->rps.hw_lock);
6266         if (ret) {
6267                 DRM_ERROR("Failed to inform PCU about cdclk change (%d)\n",
6268                           ret);
6269                 return;
6270         }
6271
6272         /* set CDCLK_CTL */
6273         switch (cdclk) {
6274         case 450000:
6275         case 432000:
6276                 freq_select = CDCLK_FREQ_450_432;
6277                 pcu_ack = 1;
6278                 break;
6279         case 540000:
6280                 freq_select = CDCLK_FREQ_540;
6281                 pcu_ack = 2;
6282                 break;
6283         case 308571:
6284         case 337500:
6285         default:
6286                 freq_select = CDCLK_FREQ_337_308;
6287                 pcu_ack = 0;
6288                 break;
6289         case 617143:
6290         case 675000:
6291                 freq_select = CDCLK_FREQ_675_617;
6292                 pcu_ack = 3;
6293                 break;
6294         }
6295
6296         if (dev_priv->cdclk_pll.vco != 0 &&
6297             dev_priv->cdclk_pll.vco != vco)
6298                 skl_dpll0_disable(dev_priv);
6299
6300         if (dev_priv->cdclk_pll.vco != vco)
6301                 skl_dpll0_enable(dev_priv, vco);
6302
6303         I915_WRITE(CDCLK_CTL, freq_select | skl_cdclk_decimal(cdclk));
6304         POSTING_READ(CDCLK_CTL);
6305
6306         /* inform PCU of the change */
6307         mutex_lock(&dev_priv->rps.hw_lock);
6308         sandybridge_pcode_write(dev_priv, SKL_PCODE_CDCLK_CONTROL, pcu_ack);
6309         mutex_unlock(&dev_priv->rps.hw_lock);
6310
6311         intel_update_cdclk(dev_priv);
6312 }
6313
6314 static void skl_sanitize_cdclk(struct drm_i915_private *dev_priv);
6315
6316 void skl_uninit_cdclk(struct drm_i915_private *dev_priv)
6317 {
6318         skl_set_cdclk(dev_priv, dev_priv->cdclk_pll.ref, 0);
6319 }
6320
6321 void skl_init_cdclk(struct drm_i915_private *dev_priv)
6322 {
6323         int cdclk, vco;
6324
6325         skl_sanitize_cdclk(dev_priv);
6326
6327         if (dev_priv->cdclk_freq != 0 && dev_priv->cdclk_pll.vco != 0) {
6328                 /*
6329                  * Use the current vco as our initial
6330                  * guess as to what the preferred vco is.
6331                  */
6332                 if (dev_priv->skl_preferred_vco_freq == 0)
6333                         skl_set_preferred_cdclk_vco(dev_priv,
6334                                                     dev_priv->cdclk_pll.vco);
6335                 return;
6336         }
6337
6338         vco = dev_priv->skl_preferred_vco_freq;
6339         if (vco == 0)
6340                 vco = 8100000;
6341         cdclk = skl_calc_cdclk(0, vco);
6342
6343         skl_set_cdclk(dev_priv, cdclk, vco);
6344 }
6345
6346 static void skl_sanitize_cdclk(struct drm_i915_private *dev_priv)
6347 {
6348         uint32_t cdctl, expected;
6349
6350         /*
6351          * check if the pre-os intialized the display
6352          * There is SWF18 scratchpad register defined which is set by the
6353          * pre-os which can be used by the OS drivers to check the status
6354          */
6355         if ((I915_READ(SWF_ILK(0x18)) & 0x00FFFFFF) == 0)
6356                 goto sanitize;
6357
6358         intel_update_cdclk(dev_priv);
6359         /* Is PLL enabled and locked ? */
6360         if (dev_priv->cdclk_pll.vco == 0 ||
6361             dev_priv->cdclk_freq == dev_priv->cdclk_pll.ref)
6362                 goto sanitize;
6363
6364         /* DPLL okay; verify the cdclock
6365          *
6366          * Noticed in some instances that the freq selection is correct but
6367          * decimal part is programmed wrong from BIOS where pre-os does not
6368          * enable display. Verify the same as well.
6369          */
6370         cdctl = I915_READ(CDCLK_CTL);
6371         expected = (cdctl & CDCLK_FREQ_SEL_MASK) |
6372                 skl_cdclk_decimal(dev_priv->cdclk_freq);
6373         if (cdctl == expected)
6374                 /* All well; nothing to sanitize */
6375                 return;
6376
6377 sanitize:
6378         DRM_DEBUG_KMS("Sanitizing cdclk programmed by pre-os\n");
6379
6380         /* force cdclk programming */
6381         dev_priv->cdclk_freq = 0;
6382         /* force full PLL disable + enable */
6383         dev_priv->cdclk_pll.vco = -1;
6384 }
6385
6386 /* Adjust CDclk dividers to allow high res or save power if possible */
6387 static void valleyview_set_cdclk(struct drm_device *dev, int cdclk)
6388 {
6389         struct drm_i915_private *dev_priv = to_i915(dev);
6390         u32 val, cmd;
6391
6392         WARN_ON(dev_priv->display.get_display_clock_speed(dev_priv)
6393                                         != dev_priv->cdclk_freq);
6394
6395         if (cdclk >= 320000) /* jump to highest voltage for 400MHz too */
6396                 cmd = 2;
6397         else if (cdclk == 266667)
6398                 cmd = 1;
6399         else
6400                 cmd = 0;
6401
6402         mutex_lock(&dev_priv->rps.hw_lock);
6403         val = vlv_punit_read(dev_priv, PUNIT_REG_DSPFREQ);
6404         val &= ~DSPFREQGUAR_MASK;
6405         val |= (cmd << DSPFREQGUAR_SHIFT);
6406         vlv_punit_write(dev_priv, PUNIT_REG_DSPFREQ, val);
6407         if (wait_for((vlv_punit_read(dev_priv, PUNIT_REG_DSPFREQ) &
6408                       DSPFREQSTAT_MASK) == (cmd << DSPFREQSTAT_SHIFT),
6409                      50)) {
6410                 DRM_ERROR("timed out waiting for CDclk change\n");
6411         }
6412         mutex_unlock(&dev_priv->rps.hw_lock);
6413
6414         mutex_lock(&dev_priv->sb_lock);
6415
6416         if (cdclk == 400000) {
6417                 u32 divider;
6418
6419                 divider = DIV_ROUND_CLOSEST(dev_priv->hpll_freq << 1, cdclk) - 1;
6420
6421                 /* adjust cdclk divider */
6422                 val = vlv_cck_read(dev_priv, CCK_DISPLAY_CLOCK_CONTROL);
6423                 val &= ~CCK_FREQUENCY_VALUES;
6424                 val |= divider;
6425                 vlv_cck_write(dev_priv, CCK_DISPLAY_CLOCK_CONTROL, val);
6426
6427                 if (wait_for((vlv_cck_read(dev_priv, CCK_DISPLAY_CLOCK_CONTROL) &
6428                               CCK_FREQUENCY_STATUS) == (divider << CCK_FREQUENCY_STATUS_SHIFT),
6429                              50))
6430                         DRM_ERROR("timed out waiting for CDclk change\n");
6431         }
6432
6433         /* adjust self-refresh exit latency value */
6434         val = vlv_bunit_read(dev_priv, BUNIT_REG_BISOC);
6435         val &= ~0x7f;
6436
6437         /*
6438          * For high bandwidth configs, we set a higher latency in the bunit
6439          * so that the core display fetch happens in time to avoid underruns.
6440          */
6441         if (cdclk == 400000)
6442                 val |= 4500 / 250; /* 4.5 usec */
6443         else
6444                 val |= 3000 / 250; /* 3.0 usec */
6445         vlv_bunit_write(dev_priv, BUNIT_REG_BISOC, val);
6446
6447         mutex_unlock(&dev_priv->sb_lock);
6448
6449         intel_update_cdclk(dev_priv);
6450 }
6451
6452 static void cherryview_set_cdclk(struct drm_device *dev, int cdclk)
6453 {
6454         struct drm_i915_private *dev_priv = to_i915(dev);
6455         u32 val, cmd;
6456
6457         WARN_ON(dev_priv->display.get_display_clock_speed(dev_priv)
6458                                                 != dev_priv->cdclk_freq);
6459
6460         switch (cdclk) {
6461         case 333333:
6462         case 320000:
6463         case 266667:
6464         case 200000:
6465                 break;
6466         default:
6467                 MISSING_CASE(cdclk);
6468                 return;
6469         }
6470
6471         /*
6472          * Specs are full of misinformation, but testing on actual
6473          * hardware has shown that we just need to write the desired
6474          * CCK divider into the Punit register.
6475          */
6476         cmd = DIV_ROUND_CLOSEST(dev_priv->hpll_freq << 1, cdclk) - 1;
6477
6478         mutex_lock(&dev_priv->rps.hw_lock);
6479         val = vlv_punit_read(dev_priv, PUNIT_REG_DSPFREQ);
6480         val &= ~DSPFREQGUAR_MASK_CHV;
6481         val |= (cmd << DSPFREQGUAR_SHIFT_CHV);
6482         vlv_punit_write(dev_priv, PUNIT_REG_DSPFREQ, val);
6483         if (wait_for((vlv_punit_read(dev_priv, PUNIT_REG_DSPFREQ) &
6484                       DSPFREQSTAT_MASK_CHV) == (cmd << DSPFREQSTAT_SHIFT_CHV),
6485                      50)) {
6486                 DRM_ERROR("timed out waiting for CDclk change\n");
6487         }
6488         mutex_unlock(&dev_priv->rps.hw_lock);
6489
6490         intel_update_cdclk(dev_priv);
6491 }
6492
6493 static int valleyview_calc_cdclk(struct drm_i915_private *dev_priv,
6494                                  int max_pixclk)
6495 {
6496         int freq_320 = (dev_priv->hpll_freq <<  1) % 320000 != 0 ? 333333 : 320000;
6497         int limit = IS_CHERRYVIEW(dev_priv) ? 95 : 90;
6498
6499         /*
6500          * Really only a few cases to deal with, as only 4 CDclks are supported:
6501          *   200MHz
6502          *   267MHz
6503          *   320/333MHz (depends on HPLL freq)
6504          *   400MHz (VLV only)
6505          * So we check to see whether we're above 90% (VLV) or 95% (CHV)
6506          * of the lower bin and adjust if needed.
6507          *
6508          * We seem to get an unstable or solid color picture at 200MHz.
6509          * Not sure what's wrong. For now use 200MHz only when all pipes
6510          * are off.
6511          */
6512         if (!IS_CHERRYVIEW(dev_priv) &&
6513             max_pixclk > freq_320*limit/100)
6514                 return 400000;
6515         else if (max_pixclk > 266667*limit/100)
6516                 return freq_320;
6517         else if (max_pixclk > 0)
6518                 return 266667;
6519         else
6520                 return 200000;
6521 }
6522
6523 static int glk_calc_cdclk(int max_pixclk)
6524 {
6525         if (max_pixclk > 2 * 158400)
6526                 return 316800;
6527         else if (max_pixclk > 2 * 79200)
6528                 return 158400;
6529         else
6530                 return 79200;
6531 }
6532
6533 static int bxt_calc_cdclk(int max_pixclk)
6534 {
6535         if (max_pixclk > 576000)
6536                 return 624000;
6537         else if (max_pixclk > 384000)
6538                 return 576000;
6539         else if (max_pixclk > 288000)
6540                 return 384000;
6541         else if (max_pixclk > 144000)
6542                 return 288000;
6543         else
6544                 return 144000;
6545 }
6546
6547 /* Compute the max pixel clock for new configuration. */
6548 static int intel_mode_max_pixclk(struct drm_device *dev,
6549                                  struct drm_atomic_state *state)
6550 {
6551         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
6552         struct drm_i915_private *dev_priv = to_i915(dev);
6553         struct drm_crtc *crtc;
6554         struct drm_crtc_state *crtc_state;
6555         unsigned max_pixclk = 0, i;
6556         enum pipe pipe;
6557
6558         memcpy(intel_state->min_pixclk, dev_priv->min_pixclk,
6559                sizeof(intel_state->min_pixclk));
6560
6561         for_each_crtc_in_state(state, crtc, crtc_state, i) {
6562                 int pixclk = 0;
6563
6564                 if (crtc_state->enable)
6565                         pixclk = crtc_state->adjusted_mode.crtc_clock;
6566
6567                 intel_state->min_pixclk[i] = pixclk;
6568         }
6569
6570         for_each_pipe(dev_priv, pipe)
6571                 max_pixclk = max(intel_state->min_pixclk[pipe], max_pixclk);
6572
6573         return max_pixclk;
6574 }
6575
6576 static int valleyview_modeset_calc_cdclk(struct drm_atomic_state *state)
6577 {
6578         struct drm_device *dev = state->dev;
6579         struct drm_i915_private *dev_priv = to_i915(dev);
6580         int max_pixclk = intel_mode_max_pixclk(dev, state);
6581         struct intel_atomic_state *intel_state =
6582                 to_intel_atomic_state(state);
6583
6584         intel_state->cdclk = intel_state->dev_cdclk =
6585                 valleyview_calc_cdclk(dev_priv, max_pixclk);
6586
6587         if (!intel_state->active_crtcs)
6588                 intel_state->dev_cdclk = valleyview_calc_cdclk(dev_priv, 0);
6589
6590         return 0;
6591 }
6592
6593 static int bxt_modeset_calc_cdclk(struct drm_atomic_state *state)
6594 {
6595         struct drm_i915_private *dev_priv = to_i915(state->dev);
6596         int max_pixclk = ilk_max_pixel_rate(state);
6597         struct intel_atomic_state *intel_state =
6598                 to_intel_atomic_state(state);
6599         int cdclk;
6600
6601         if (IS_GEMINILAKE(dev_priv))
6602                 cdclk = glk_calc_cdclk(max_pixclk);
6603         else
6604                 cdclk = bxt_calc_cdclk(max_pixclk);
6605
6606         intel_state->cdclk = intel_state->dev_cdclk = cdclk;
6607
6608         if (!intel_state->active_crtcs) {
6609                 if (IS_GEMINILAKE(dev_priv))
6610                         cdclk = glk_calc_cdclk(0);
6611                 else
6612                         cdclk = bxt_calc_cdclk(0);
6613
6614                 intel_state->dev_cdclk = cdclk;
6615         }
6616
6617         return 0;
6618 }
6619
6620 static void vlv_program_pfi_credits(struct drm_i915_private *dev_priv)
6621 {
6622         unsigned int credits, default_credits;
6623
6624         if (IS_CHERRYVIEW(dev_priv))
6625                 default_credits = PFI_CREDIT(12);
6626         else
6627                 default_credits = PFI_CREDIT(8);
6628
6629         if (dev_priv->cdclk_freq >= dev_priv->czclk_freq) {
6630                 /* CHV suggested value is 31 or 63 */
6631                 if (IS_CHERRYVIEW(dev_priv))
6632                         credits = PFI_CREDIT_63;
6633                 else
6634                         credits = PFI_CREDIT(15);
6635         } else {
6636                 credits = default_credits;
6637         }
6638
6639         /*
6640          * WA - write default credits before re-programming
6641          * FIXME: should we also set the resend bit here?
6642          */
6643         I915_WRITE(GCI_CONTROL, VGA_FAST_MODE_DISABLE |
6644                    default_credits);
6645
6646         I915_WRITE(GCI_CONTROL, VGA_FAST_MODE_DISABLE |
6647                    credits | PFI_CREDIT_RESEND);
6648
6649         /*
6650          * FIXME is this guaranteed to clear
6651          * immediately or should we poll for it?
6652          */
6653         WARN_ON(I915_READ(GCI_CONTROL) & PFI_CREDIT_RESEND);
6654 }
6655
6656 static void valleyview_modeset_commit_cdclk(struct drm_atomic_state *old_state)
6657 {
6658         struct drm_device *dev = old_state->dev;
6659         struct drm_i915_private *dev_priv = to_i915(dev);
6660         struct intel_atomic_state *old_intel_state =
6661                 to_intel_atomic_state(old_state);
6662         unsigned req_cdclk = old_intel_state->dev_cdclk;
6663
6664         /*
6665          * FIXME: We can end up here with all power domains off, yet
6666          * with a CDCLK frequency other than the minimum. To account
6667          * for this take the PIPE-A power domain, which covers the HW
6668          * blocks needed for the following programming. This can be
6669          * removed once it's guaranteed that we get here either with
6670          * the minimum CDCLK set, or the required power domains
6671          * enabled.
6672          */
6673         intel_display_power_get(dev_priv, POWER_DOMAIN_PIPE_A);
6674
6675         if (IS_CHERRYVIEW(dev_priv))
6676                 cherryview_set_cdclk(dev, req_cdclk);
6677         else
6678                 valleyview_set_cdclk(dev, req_cdclk);
6679
6680         vlv_program_pfi_credits(dev_priv);
6681
6682         intel_display_power_put(dev_priv, POWER_DOMAIN_PIPE_A);
6683 }
6684
6685 static void valleyview_crtc_enable(struct intel_crtc_state *pipe_config,
6686                                    struct drm_atomic_state *old_state)
6687 {
6688         struct drm_crtc *crtc = pipe_config->base.crtc;
6689         struct drm_device *dev = crtc->dev;
6690         struct drm_i915_private *dev_priv = to_i915(dev);
6691         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
6692         int pipe = intel_crtc->pipe;
6693
6694         if (WARN_ON(intel_crtc->active))
6695                 return;
6696
6697         if (intel_crtc_has_dp_encoder(intel_crtc->config))
6698                 intel_dp_set_m_n(intel_crtc, M1_N1);
6699
6700         intel_set_pipe_timings(intel_crtc);
6701         intel_set_pipe_src_size(intel_crtc);
6702
6703         if (IS_CHERRYVIEW(dev_priv) && pipe == PIPE_B) {
6704                 struct drm_i915_private *dev_priv = to_i915(dev);
6705
6706                 I915_WRITE(CHV_BLEND(pipe), CHV_BLEND_LEGACY);
6707                 I915_WRITE(CHV_CANVAS(pipe), 0);
6708         }
6709
6710         i9xx_set_pipeconf(intel_crtc);
6711
6712         intel_crtc->active = true;
6713
6714         intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
6715
6716         intel_encoders_pre_pll_enable(crtc, pipe_config, old_state);
6717
6718         if (IS_CHERRYVIEW(dev_priv)) {
6719                 chv_prepare_pll(intel_crtc, intel_crtc->config);
6720                 chv_enable_pll(intel_crtc, intel_crtc->config);
6721         } else {
6722                 vlv_prepare_pll(intel_crtc, intel_crtc->config);
6723                 vlv_enable_pll(intel_crtc, intel_crtc->config);
6724         }
6725
6726         intel_encoders_pre_enable(crtc, pipe_config, old_state);
6727
6728         i9xx_pfit_enable(intel_crtc);
6729
6730         intel_color_load_luts(&pipe_config->base);
6731
6732         intel_update_watermarks(intel_crtc);
6733         intel_enable_pipe(intel_crtc);
6734
6735         assert_vblank_disabled(crtc);
6736         drm_crtc_vblank_on(crtc);
6737
6738         intel_encoders_enable(crtc, pipe_config, old_state);
6739 }
6740
6741 static void i9xx_set_pll_dividers(struct intel_crtc *crtc)
6742 {
6743         struct drm_device *dev = crtc->base.dev;
6744         struct drm_i915_private *dev_priv = to_i915(dev);
6745
6746         I915_WRITE(FP0(crtc->pipe), crtc->config->dpll_hw_state.fp0);
6747         I915_WRITE(FP1(crtc->pipe), crtc->config->dpll_hw_state.fp1);
6748 }
6749
6750 static void i9xx_crtc_enable(struct intel_crtc_state *pipe_config,
6751                              struct drm_atomic_state *old_state)
6752 {
6753         struct drm_crtc *crtc = pipe_config->base.crtc;
6754         struct drm_device *dev = crtc->dev;
6755         struct drm_i915_private *dev_priv = to_i915(dev);
6756         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
6757         enum pipe pipe = intel_crtc->pipe;
6758
6759         if (WARN_ON(intel_crtc->active))
6760                 return;
6761
6762         i9xx_set_pll_dividers(intel_crtc);
6763
6764         if (intel_crtc_has_dp_encoder(intel_crtc->config))
6765                 intel_dp_set_m_n(intel_crtc, M1_N1);
6766
6767         intel_set_pipe_timings(intel_crtc);
6768         intel_set_pipe_src_size(intel_crtc);
6769
6770         i9xx_set_pipeconf(intel_crtc);
6771
6772         intel_crtc->active = true;
6773
6774         if (!IS_GEN2(dev_priv))
6775                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
6776
6777         intel_encoders_pre_enable(crtc, pipe_config, old_state);
6778
6779         i9xx_enable_pll(intel_crtc);
6780
6781         i9xx_pfit_enable(intel_crtc);
6782
6783         intel_color_load_luts(&pipe_config->base);
6784
6785         intel_update_watermarks(intel_crtc);
6786         intel_enable_pipe(intel_crtc);
6787
6788         assert_vblank_disabled(crtc);
6789         drm_crtc_vblank_on(crtc);
6790
6791         intel_encoders_enable(crtc, pipe_config, old_state);
6792 }
6793
6794 static void i9xx_pfit_disable(struct intel_crtc *crtc)
6795 {
6796         struct drm_device *dev = crtc->base.dev;
6797         struct drm_i915_private *dev_priv = to_i915(dev);
6798
6799         if (!crtc->config->gmch_pfit.control)
6800                 return;
6801
6802         assert_pipe_disabled(dev_priv, crtc->pipe);
6803
6804         DRM_DEBUG_DRIVER("disabling pfit, current: 0x%08x\n",
6805                          I915_READ(PFIT_CONTROL));
6806         I915_WRITE(PFIT_CONTROL, 0);
6807 }
6808
6809 static void i9xx_crtc_disable(struct intel_crtc_state *old_crtc_state,
6810                               struct drm_atomic_state *old_state)
6811 {
6812         struct drm_crtc *crtc = old_crtc_state->base.crtc;
6813         struct drm_device *dev = crtc->dev;
6814         struct drm_i915_private *dev_priv = to_i915(dev);
6815         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
6816         int pipe = intel_crtc->pipe;
6817
6818         /*
6819          * On gen2 planes are double buffered but the pipe isn't, so we must
6820          * wait for planes to fully turn off before disabling the pipe.
6821          */
6822         if (IS_GEN2(dev_priv))
6823                 intel_wait_for_vblank(dev_priv, pipe);
6824
6825         intel_encoders_disable(crtc, old_crtc_state, old_state);
6826
6827         drm_crtc_vblank_off(crtc);
6828         assert_vblank_disabled(crtc);
6829
6830         intel_disable_pipe(intel_crtc);
6831
6832         i9xx_pfit_disable(intel_crtc);
6833
6834         intel_encoders_post_disable(crtc, old_crtc_state, old_state);
6835
6836         if (!intel_crtc_has_type(intel_crtc->config, INTEL_OUTPUT_DSI)) {
6837                 if (IS_CHERRYVIEW(dev_priv))
6838                         chv_disable_pll(dev_priv, pipe);
6839                 else if (IS_VALLEYVIEW(dev_priv))
6840                         vlv_disable_pll(dev_priv, pipe);
6841                 else
6842                         i9xx_disable_pll(intel_crtc);
6843         }
6844
6845         intel_encoders_post_pll_disable(crtc, old_crtc_state, old_state);
6846
6847         if (!IS_GEN2(dev_priv))
6848                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
6849 }
6850
6851 static void intel_crtc_disable_noatomic(struct drm_crtc *crtc)
6852 {
6853         struct intel_encoder *encoder;
6854         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
6855         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
6856         enum intel_display_power_domain domain;
6857         unsigned long domains;
6858         struct drm_atomic_state *state;
6859         struct intel_crtc_state *crtc_state;
6860         int ret;
6861
6862         if (!intel_crtc->active)
6863                 return;
6864
6865         if (crtc->primary->state->visible) {
6866                 WARN_ON(intel_crtc->flip_work);
6867
6868                 intel_pre_disable_primary_noatomic(crtc);
6869
6870                 intel_crtc_disable_planes(crtc, 1 << drm_plane_index(crtc->primary));
6871                 crtc->primary->state->visible = false;
6872         }
6873
6874         state = drm_atomic_state_alloc(crtc->dev);
6875         if (!state) {
6876                 DRM_DEBUG_KMS("failed to disable [CRTC:%d:%s], out of memory",
6877                               crtc->base.id, crtc->name);
6878                 return;
6879         }
6880
6881         state->acquire_ctx = crtc->dev->mode_config.acquire_ctx;
6882
6883         /* Everything's already locked, -EDEADLK can't happen. */
6884         crtc_state = intel_atomic_get_crtc_state(state, intel_crtc);
6885         ret = drm_atomic_add_affected_connectors(state, crtc);
6886
6887         WARN_ON(IS_ERR(crtc_state) || ret);
6888
6889         dev_priv->display.crtc_disable(crtc_state, state);
6890
6891         drm_atomic_state_put(state);
6892
6893         DRM_DEBUG_KMS("[CRTC:%d:%s] hw state adjusted, was enabled, now disabled\n",
6894                       crtc->base.id, crtc->name);
6895
6896         WARN_ON(drm_atomic_set_mode_for_crtc(crtc->state, NULL) < 0);
6897         crtc->state->active = false;
6898         intel_crtc->active = false;
6899         crtc->enabled = false;
6900         crtc->state->connector_mask = 0;
6901         crtc->state->encoder_mask = 0;
6902
6903         for_each_encoder_on_crtc(crtc->dev, crtc, encoder)
6904                 encoder->base.crtc = NULL;
6905
6906         intel_fbc_disable(intel_crtc);
6907         intel_update_watermarks(intel_crtc);
6908         intel_disable_shared_dpll(intel_crtc);
6909
6910         domains = intel_crtc->enabled_power_domains;
6911         for_each_power_domain(domain, domains)
6912                 intel_display_power_put(dev_priv, domain);
6913         intel_crtc->enabled_power_domains = 0;
6914
6915         dev_priv->active_crtcs &= ~(1 << intel_crtc->pipe);
6916         dev_priv->min_pixclk[intel_crtc->pipe] = 0;
6917 }
6918
6919 /*
6920  * turn all crtc's off, but do not adjust state
6921  * This has to be paired with a call to intel_modeset_setup_hw_state.
6922  */
6923 int intel_display_suspend(struct drm_device *dev)
6924 {
6925         struct drm_i915_private *dev_priv = to_i915(dev);
6926         struct drm_atomic_state *state;
6927         int ret;
6928
6929         state = drm_atomic_helper_suspend(dev);
6930         ret = PTR_ERR_OR_ZERO(state);
6931         if (ret)
6932                 DRM_ERROR("Suspending crtc's failed with %i\n", ret);
6933         else
6934                 dev_priv->modeset_restore_state = state;
6935         return ret;
6936 }
6937
6938 void intel_encoder_destroy(struct drm_encoder *encoder)
6939 {
6940         struct intel_encoder *intel_encoder = to_intel_encoder(encoder);
6941
6942         drm_encoder_cleanup(encoder);
6943         kfree(intel_encoder);
6944 }
6945
6946 /* Cross check the actual hw state with our own modeset state tracking (and it's
6947  * internal consistency). */
6948 static void intel_connector_verify_state(struct intel_connector *connector)
6949 {
6950         struct drm_crtc *crtc = connector->base.state->crtc;
6951
6952         DRM_DEBUG_KMS("[CONNECTOR:%d:%s]\n",
6953                       connector->base.base.id,
6954                       connector->base.name);
6955
6956         if (connector->get_hw_state(connector)) {
6957                 struct intel_encoder *encoder = connector->encoder;
6958                 struct drm_connector_state *conn_state = connector->base.state;
6959
6960                 I915_STATE_WARN(!crtc,
6961                          "connector enabled without attached crtc\n");
6962
6963                 if (!crtc)
6964                         return;
6965
6966                 I915_STATE_WARN(!crtc->state->active,
6967                       "connector is active, but attached crtc isn't\n");
6968
6969                 if (!encoder || encoder->type == INTEL_OUTPUT_DP_MST)
6970                         return;
6971
6972                 I915_STATE_WARN(conn_state->best_encoder != &encoder->base,
6973                         "atomic encoder doesn't match attached encoder\n");
6974
6975                 I915_STATE_WARN(conn_state->crtc != encoder->base.crtc,
6976                         "attached encoder crtc differs from connector crtc\n");
6977         } else {
6978                 I915_STATE_WARN(crtc && crtc->state->active,
6979                         "attached crtc is active, but connector isn't\n");
6980                 I915_STATE_WARN(!crtc && connector->base.state->best_encoder,
6981                         "best encoder set without crtc!\n");
6982         }
6983 }
6984
6985 int intel_connector_init(struct intel_connector *connector)
6986 {
6987         drm_atomic_helper_connector_reset(&connector->base);
6988
6989         if (!connector->base.state)
6990                 return -ENOMEM;
6991
6992         return 0;
6993 }
6994
6995 struct intel_connector *intel_connector_alloc(void)
6996 {
6997         struct intel_connector *connector;
6998
6999         connector = kzalloc(sizeof *connector, GFP_KERNEL);
7000         if (!connector)
7001                 return NULL;
7002
7003         if (intel_connector_init(connector) < 0) {
7004                 kfree(connector);
7005                 return NULL;
7006         }
7007
7008         return connector;
7009 }
7010
7011 /* Simple connector->get_hw_state implementation for encoders that support only
7012  * one connector and no cloning and hence the encoder state determines the state
7013  * of the connector. */
7014 bool intel_connector_get_hw_state(struct intel_connector *connector)
7015 {
7016         enum pipe pipe = 0;
7017         struct intel_encoder *encoder = connector->encoder;
7018
7019         return encoder->get_hw_state(encoder, &pipe);
7020 }
7021
7022 static int pipe_required_fdi_lanes(struct intel_crtc_state *crtc_state)
7023 {
7024         if (crtc_state->base.enable && crtc_state->has_pch_encoder)
7025                 return crtc_state->fdi_lanes;
7026
7027         return 0;
7028 }
7029
7030 static int ironlake_check_fdi_lanes(struct drm_device *dev, enum pipe pipe,
7031                                      struct intel_crtc_state *pipe_config)
7032 {
7033         struct drm_i915_private *dev_priv = to_i915(dev);
7034         struct drm_atomic_state *state = pipe_config->base.state;
7035         struct intel_crtc *other_crtc;
7036         struct intel_crtc_state *other_crtc_state;
7037
7038         DRM_DEBUG_KMS("checking fdi config on pipe %c, lanes %i\n",
7039                       pipe_name(pipe), pipe_config->fdi_lanes);
7040         if (pipe_config->fdi_lanes > 4) {
7041                 DRM_DEBUG_KMS("invalid fdi lane config on pipe %c: %i lanes\n",
7042                               pipe_name(pipe), pipe_config->fdi_lanes);
7043                 return -EINVAL;
7044         }
7045
7046         if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv)) {
7047                 if (pipe_config->fdi_lanes > 2) {
7048                         DRM_DEBUG_KMS("only 2 lanes on haswell, required: %i lanes\n",
7049                                       pipe_config->fdi_lanes);
7050                         return -EINVAL;
7051                 } else {
7052                         return 0;
7053                 }
7054         }
7055
7056         if (INTEL_INFO(dev_priv)->num_pipes == 2)
7057                 return 0;
7058
7059         /* Ivybridge 3 pipe is really complicated */
7060         switch (pipe) {
7061         case PIPE_A:
7062                 return 0;
7063         case PIPE_B:
7064                 if (pipe_config->fdi_lanes <= 2)
7065                         return 0;
7066
7067                 other_crtc = intel_get_crtc_for_pipe(dev_priv, PIPE_C);
7068                 other_crtc_state =
7069                         intel_atomic_get_crtc_state(state, other_crtc);
7070                 if (IS_ERR(other_crtc_state))
7071                         return PTR_ERR(other_crtc_state);
7072
7073                 if (pipe_required_fdi_lanes(other_crtc_state) > 0) {
7074                         DRM_DEBUG_KMS("invalid shared fdi lane config on pipe %c: %i lanes\n",
7075                                       pipe_name(pipe), pipe_config->fdi_lanes);
7076                         return -EINVAL;
7077                 }
7078                 return 0;
7079         case PIPE_C:
7080                 if (pipe_config->fdi_lanes > 2) {
7081                         DRM_DEBUG_KMS("only 2 lanes on pipe %c: required %i lanes\n",
7082                                       pipe_name(pipe), pipe_config->fdi_lanes);
7083                         return -EINVAL;
7084                 }
7085
7086                 other_crtc = intel_get_crtc_for_pipe(dev_priv, PIPE_B);
7087                 other_crtc_state =
7088                         intel_atomic_get_crtc_state(state, other_crtc);
7089                 if (IS_ERR(other_crtc_state))
7090                         return PTR_ERR(other_crtc_state);
7091
7092                 if (pipe_required_fdi_lanes(other_crtc_state) > 2) {
7093                         DRM_DEBUG_KMS("fdi link B uses too many lanes to enable link C\n");
7094                         return -EINVAL;
7095                 }
7096                 return 0;
7097         default:
7098                 BUG();
7099         }
7100 }
7101
7102 #define RETRY 1
7103 static int ironlake_fdi_compute_config(struct intel_crtc *intel_crtc,
7104                                        struct intel_crtc_state *pipe_config)
7105 {
7106         struct drm_device *dev = intel_crtc->base.dev;
7107         const struct drm_display_mode *adjusted_mode = &pipe_config->base.adjusted_mode;
7108         int lane, link_bw, fdi_dotclock, ret;
7109         bool needs_recompute = false;
7110
7111 retry:
7112         /* FDI is a binary signal running at ~2.7GHz, encoding
7113          * each output octet as 10 bits. The actual frequency
7114          * is stored as a divider into a 100MHz clock, and the
7115          * mode pixel clock is stored in units of 1KHz.
7116          * Hence the bw of each lane in terms of the mode signal
7117          * is:
7118          */
7119         link_bw = intel_fdi_link_freq(to_i915(dev), pipe_config);
7120
7121         fdi_dotclock = adjusted_mode->crtc_clock;
7122
7123         lane = ironlake_get_lanes_required(fdi_dotclock, link_bw,
7124                                            pipe_config->pipe_bpp);
7125
7126         pipe_config->fdi_lanes = lane;
7127
7128         intel_link_compute_m_n(pipe_config->pipe_bpp, lane, fdi_dotclock,
7129                                link_bw, &pipe_config->fdi_m_n);
7130
7131         ret = ironlake_check_fdi_lanes(dev, intel_crtc->pipe, pipe_config);
7132         if (ret == -EINVAL && pipe_config->pipe_bpp > 6*3) {
7133                 pipe_config->pipe_bpp -= 2*3;
7134                 DRM_DEBUG_KMS("fdi link bw constraint, reducing pipe bpp to %i\n",
7135                               pipe_config->pipe_bpp);
7136                 needs_recompute = true;
7137                 pipe_config->bw_constrained = true;
7138
7139                 goto retry;
7140         }
7141
7142         if (needs_recompute)
7143                 return RETRY;
7144
7145         return ret;
7146 }
7147
7148 static bool pipe_config_supports_ips(struct drm_i915_private *dev_priv,
7149                                      struct intel_crtc_state *pipe_config)
7150 {
7151         if (pipe_config->pipe_bpp > 24)
7152                 return false;
7153
7154         /* HSW can handle pixel rate up to cdclk? */
7155         if (IS_HASWELL(dev_priv))
7156                 return true;
7157
7158         /*
7159          * We compare against max which means we must take
7160          * the increased cdclk requirement into account when
7161          * calculating the new cdclk.
7162          *
7163          * Should measure whether using a lower cdclk w/o IPS
7164          */
7165         return ilk_pipe_pixel_rate(pipe_config) <=
7166                 dev_priv->max_cdclk_freq * 95 / 100;
7167 }
7168
7169 static void hsw_compute_ips_config(struct intel_crtc *crtc,
7170                                    struct intel_crtc_state *pipe_config)
7171 {
7172         struct drm_device *dev = crtc->base.dev;
7173         struct drm_i915_private *dev_priv = to_i915(dev);
7174
7175         pipe_config->ips_enabled = i915.enable_ips &&
7176                 hsw_crtc_supports_ips(crtc) &&
7177                 pipe_config_supports_ips(dev_priv, pipe_config);
7178 }
7179
7180 static bool intel_crtc_supports_double_wide(const struct intel_crtc *crtc)
7181 {
7182         const struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
7183
7184         /* GDG double wide on either pipe, otherwise pipe A only */
7185         return INTEL_INFO(dev_priv)->gen < 4 &&
7186                 (crtc->pipe == PIPE_A || IS_I915G(dev_priv));
7187 }
7188
7189 static int intel_crtc_compute_config(struct intel_crtc *crtc,
7190                                      struct intel_crtc_state *pipe_config)
7191 {
7192         struct drm_device *dev = crtc->base.dev;
7193         struct drm_i915_private *dev_priv = to_i915(dev);
7194         const struct drm_display_mode *adjusted_mode = &pipe_config->base.adjusted_mode;
7195         int clock_limit = dev_priv->max_dotclk_freq;
7196
7197         if (INTEL_GEN(dev_priv) < 4) {
7198                 clock_limit = dev_priv->max_cdclk_freq * 9 / 10;
7199
7200                 /*
7201                  * Enable double wide mode when the dot clock
7202                  * is > 90% of the (display) core speed.
7203                  */
7204                 if (intel_crtc_supports_double_wide(crtc) &&
7205                     adjusted_mode->crtc_clock > clock_limit) {
7206                         clock_limit = dev_priv->max_dotclk_freq;
7207                         pipe_config->double_wide = true;
7208                 }
7209         }
7210
7211         if (adjusted_mode->crtc_clock > clock_limit) {
7212                 DRM_DEBUG_KMS("requested pixel clock (%d kHz) too high (max: %d kHz, double wide: %s)\n",
7213                               adjusted_mode->crtc_clock, clock_limit,
7214                               yesno(pipe_config->double_wide));
7215                 return -EINVAL;
7216         }
7217
7218         /*
7219          * Pipe horizontal size must be even in:
7220          * - DVO ganged mode
7221          * - LVDS dual channel mode
7222          * - Double wide pipe
7223          */
7224         if ((intel_crtc_has_type(pipe_config, INTEL_OUTPUT_LVDS) &&
7225              intel_is_dual_link_lvds(dev)) || pipe_config->double_wide)
7226                 pipe_config->pipe_src_w &= ~1;
7227
7228         /* Cantiga+ cannot handle modes with a hsync front porch of 0.
7229          * WaPruneModeWithIncorrectHsyncOffset:ctg,elk,ilk,snb,ivb,vlv,hsw.
7230          */
7231         if ((INTEL_GEN(dev_priv) > 4 || IS_G4X(dev_priv)) &&
7232                 adjusted_mode->crtc_hsync_start == adjusted_mode->crtc_hdisplay)
7233                 return -EINVAL;
7234
7235         if (HAS_IPS(dev_priv))
7236                 hsw_compute_ips_config(crtc, pipe_config);
7237
7238         if (pipe_config->has_pch_encoder)
7239                 return ironlake_fdi_compute_config(crtc, pipe_config);
7240
7241         return 0;
7242 }
7243
7244 static int skylake_get_display_clock_speed(struct drm_i915_private *dev_priv)
7245 {
7246         u32 cdctl;
7247
7248         skl_dpll0_update(dev_priv);
7249
7250         if (dev_priv->cdclk_pll.vco == 0)
7251                 return dev_priv->cdclk_pll.ref;
7252
7253         cdctl = I915_READ(CDCLK_CTL);
7254
7255         if (dev_priv->cdclk_pll.vco == 8640000) {
7256                 switch (cdctl & CDCLK_FREQ_SEL_MASK) {
7257                 case CDCLK_FREQ_450_432:
7258                         return 432000;
7259                 case CDCLK_FREQ_337_308:
7260                         return 308571;
7261                 case CDCLK_FREQ_540:
7262                         return 540000;
7263                 case CDCLK_FREQ_675_617:
7264                         return 617143;
7265                 default:
7266                         MISSING_CASE(cdctl & CDCLK_FREQ_SEL_MASK);
7267                 }
7268         } else {
7269                 switch (cdctl & CDCLK_FREQ_SEL_MASK) {
7270                 case CDCLK_FREQ_450_432:
7271                         return 450000;
7272                 case CDCLK_FREQ_337_308:
7273                         return 337500;
7274                 case CDCLK_FREQ_540:
7275                         return 540000;
7276                 case CDCLK_FREQ_675_617:
7277                         return 675000;
7278                 default:
7279                         MISSING_CASE(cdctl & CDCLK_FREQ_SEL_MASK);
7280                 }
7281         }
7282
7283         return dev_priv->cdclk_pll.ref;
7284 }
7285
7286 static void bxt_de_pll_update(struct drm_i915_private *dev_priv)
7287 {
7288         u32 val;
7289
7290         dev_priv->cdclk_pll.ref = 19200;
7291         dev_priv->cdclk_pll.vco = 0;
7292
7293         val = I915_READ(BXT_DE_PLL_ENABLE);
7294         if ((val & BXT_DE_PLL_PLL_ENABLE) == 0)
7295                 return;
7296
7297         if (WARN_ON((val & BXT_DE_PLL_LOCK) == 0))
7298                 return;
7299
7300         val = I915_READ(BXT_DE_PLL_CTL);
7301         dev_priv->cdclk_pll.vco = (val & BXT_DE_PLL_RATIO_MASK) *
7302                 dev_priv->cdclk_pll.ref;
7303 }
7304
7305 static int broxton_get_display_clock_speed(struct drm_i915_private *dev_priv)
7306 {
7307         u32 divider;
7308         int div, vco;
7309
7310         bxt_de_pll_update(dev_priv);
7311
7312         vco = dev_priv->cdclk_pll.vco;
7313         if (vco == 0)
7314                 return dev_priv->cdclk_pll.ref;
7315
7316         divider = I915_READ(CDCLK_CTL) & BXT_CDCLK_CD2X_DIV_SEL_MASK;
7317
7318         switch (divider) {
7319         case BXT_CDCLK_CD2X_DIV_SEL_1:
7320                 div = 2;
7321                 break;
7322         case BXT_CDCLK_CD2X_DIV_SEL_1_5:
7323                 WARN(IS_GEMINILAKE(dev_priv), "Unsupported divider\n");
7324                 div = 3;
7325                 break;
7326         case BXT_CDCLK_CD2X_DIV_SEL_2:
7327                 div = 4;
7328                 break;
7329         case BXT_CDCLK_CD2X_DIV_SEL_4:
7330                 div = 8;
7331                 break;
7332         default:
7333                 MISSING_CASE(divider);
7334                 return dev_priv->cdclk_pll.ref;
7335         }
7336
7337         return DIV_ROUND_CLOSEST(vco, div);
7338 }
7339
7340 static int broadwell_get_display_clock_speed(struct drm_i915_private *dev_priv)
7341 {
7342         uint32_t lcpll = I915_READ(LCPLL_CTL);
7343         uint32_t freq = lcpll & LCPLL_CLK_FREQ_MASK;
7344
7345         if (lcpll & LCPLL_CD_SOURCE_FCLK)
7346                 return 800000;
7347         else if (I915_READ(FUSE_STRAP) & HSW_CDCLK_LIMIT)
7348                 return 450000;
7349         else if (freq == LCPLL_CLK_FREQ_450)
7350                 return 450000;
7351         else if (freq == LCPLL_CLK_FREQ_54O_BDW)
7352                 return 540000;
7353         else if (freq == LCPLL_CLK_FREQ_337_5_BDW)
7354                 return 337500;
7355         else
7356                 return 675000;
7357 }
7358
7359 static int haswell_get_display_clock_speed(struct drm_i915_private *dev_priv)
7360 {
7361         uint32_t lcpll = I915_READ(LCPLL_CTL);
7362         uint32_t freq = lcpll & LCPLL_CLK_FREQ_MASK;
7363
7364         if (lcpll & LCPLL_CD_SOURCE_FCLK)
7365                 return 800000;
7366         else if (I915_READ(FUSE_STRAP) & HSW_CDCLK_LIMIT)
7367                 return 450000;
7368         else if (freq == LCPLL_CLK_FREQ_450)
7369                 return 450000;
7370         else if (IS_HSW_ULT(dev_priv))
7371                 return 337500;
7372         else
7373                 return 540000;
7374 }
7375
7376 static int valleyview_get_display_clock_speed(struct drm_i915_private *dev_priv)
7377 {
7378         return vlv_get_cck_clock_hpll(dev_priv, "cdclk",
7379                                       CCK_DISPLAY_CLOCK_CONTROL);
7380 }
7381
7382 static int ilk_get_display_clock_speed(struct drm_i915_private *dev_priv)
7383 {
7384         return 450000;
7385 }
7386
7387 static int i945_get_display_clock_speed(struct drm_i915_private *dev_priv)
7388 {
7389         return 400000;
7390 }
7391
7392 static int i915_get_display_clock_speed(struct drm_i915_private *dev_priv)
7393 {
7394         return 333333;
7395 }
7396
7397 static int i9xx_misc_get_display_clock_speed(struct drm_i915_private *dev_priv)
7398 {
7399         return 200000;
7400 }
7401
7402 static int pnv_get_display_clock_speed(struct drm_i915_private *dev_priv)
7403 {
7404         struct pci_dev *pdev = dev_priv->drm.pdev;
7405         u16 gcfgc = 0;
7406
7407         pci_read_config_word(pdev, GCFGC, &gcfgc);
7408
7409         switch (gcfgc & GC_DISPLAY_CLOCK_MASK) {
7410         case GC_DISPLAY_CLOCK_267_MHZ_PNV:
7411                 return 266667;
7412         case GC_DISPLAY_CLOCK_333_MHZ_PNV:
7413                 return 333333;
7414         case GC_DISPLAY_CLOCK_444_MHZ_PNV:
7415                 return 444444;
7416         case GC_DISPLAY_CLOCK_200_MHZ_PNV:
7417                 return 200000;
7418         default:
7419                 DRM_ERROR("Unknown pnv display core clock 0x%04x\n", gcfgc);
7420         case GC_DISPLAY_CLOCK_133_MHZ_PNV:
7421                 return 133333;
7422         case GC_DISPLAY_CLOCK_167_MHZ_PNV:
7423                 return 166667;
7424         }
7425 }
7426
7427 static int i915gm_get_display_clock_speed(struct drm_i915_private *dev_priv)
7428 {
7429         struct pci_dev *pdev = dev_priv->drm.pdev;
7430         u16 gcfgc = 0;
7431
7432         pci_read_config_word(pdev, GCFGC, &gcfgc);
7433
7434         if (gcfgc & GC_LOW_FREQUENCY_ENABLE)
7435                 return 133333;
7436         else {
7437                 switch (gcfgc & GC_DISPLAY_CLOCK_MASK) {
7438                 case GC_DISPLAY_CLOCK_333_MHZ:
7439                         return 333333;
7440                 default:
7441                 case GC_DISPLAY_CLOCK_190_200_MHZ:
7442                         return 190000;
7443                 }
7444         }
7445 }
7446
7447 static int i865_get_display_clock_speed(struct drm_i915_private *dev_priv)
7448 {
7449         return 266667;
7450 }
7451
7452 static int i85x_get_display_clock_speed(struct drm_i915_private *dev_priv)
7453 {
7454         struct pci_dev *pdev = dev_priv->drm.pdev;
7455         u16 hpllcc = 0;
7456
7457         /*
7458          * 852GM/852GMV only supports 133 MHz and the HPLLCC
7459          * encoding is different :(
7460          * FIXME is this the right way to detect 852GM/852GMV?
7461          */
7462         if (pdev->revision == 0x1)
7463                 return 133333;
7464
7465         pci_bus_read_config_word(pdev->bus,
7466                                  PCI_DEVFN(0, 3), HPLLCC, &hpllcc);
7467
7468         /* Assume that the hardware is in the high speed state.  This
7469          * should be the default.
7470          */
7471         switch (hpllcc & GC_CLOCK_CONTROL_MASK) {
7472         case GC_CLOCK_133_200:
7473         case GC_CLOCK_133_200_2:
7474         case GC_CLOCK_100_200:
7475                 return 200000;
7476         case GC_CLOCK_166_250:
7477                 return 250000;
7478         case GC_CLOCK_100_133:
7479                 return 133333;
7480         case GC_CLOCK_133_266:
7481         case GC_CLOCK_133_266_2:
7482         case GC_CLOCK_166_266:
7483                 return 266667;
7484         }
7485
7486         /* Shouldn't happen */
7487         return 0;
7488 }
7489
7490 static int i830_get_display_clock_speed(struct drm_i915_private *dev_priv)
7491 {
7492         return 133333;
7493 }
7494
7495 static unsigned int intel_hpll_vco(struct drm_i915_private *dev_priv)
7496 {
7497         static const unsigned int blb_vco[8] = {
7498                 [0] = 3200000,
7499                 [1] = 4000000,
7500                 [2] = 5333333,
7501                 [3] = 4800000,
7502                 [4] = 6400000,
7503         };
7504         static const unsigned int pnv_vco[8] = {
7505                 [0] = 3200000,
7506                 [1] = 4000000,
7507                 [2] = 5333333,
7508                 [3] = 4800000,
7509                 [4] = 2666667,
7510         };
7511         static const unsigned int cl_vco[8] = {
7512                 [0] = 3200000,
7513                 [1] = 4000000,
7514                 [2] = 5333333,
7515                 [3] = 6400000,
7516                 [4] = 3333333,
7517                 [5] = 3566667,
7518                 [6] = 4266667,
7519         };
7520         static const unsigned int elk_vco[8] = {
7521                 [0] = 3200000,
7522                 [1] = 4000000,
7523                 [2] = 5333333,
7524                 [3] = 4800000,
7525         };
7526         static const unsigned int ctg_vco[8] = {
7527                 [0] = 3200000,
7528                 [1] = 4000000,
7529                 [2] = 5333333,
7530                 [3] = 6400000,
7531                 [4] = 2666667,
7532                 [5] = 4266667,
7533         };
7534         const unsigned int *vco_table;
7535         unsigned int vco;
7536         uint8_t tmp = 0;
7537
7538         /* FIXME other chipsets? */
7539         if (IS_GM45(dev_priv))
7540                 vco_table = ctg_vco;
7541         else if (IS_G4X(dev_priv))
7542                 vco_table = elk_vco;
7543         else if (IS_I965GM(dev_priv))
7544                 vco_table = cl_vco;
7545         else if (IS_PINEVIEW(dev_priv))
7546                 vco_table = pnv_vco;
7547         else if (IS_G33(dev_priv))
7548                 vco_table = blb_vco;
7549         else
7550                 return 0;
7551
7552         tmp = I915_READ(IS_MOBILE(dev_priv) ? HPLLVCO_MOBILE : HPLLVCO);
7553
7554         vco = vco_table[tmp & 0x7];
7555         if (vco == 0)
7556                 DRM_ERROR("Bad HPLL VCO (HPLLVCO=0x%02x)\n", tmp);
7557         else
7558                 DRM_DEBUG_KMS("HPLL VCO %u kHz\n", vco);
7559
7560         return vco;
7561 }
7562
7563 static int gm45_get_display_clock_speed(struct drm_i915_private *dev_priv)
7564 {
7565         struct pci_dev *pdev = dev_priv->drm.pdev;
7566         unsigned int cdclk_sel, vco = intel_hpll_vco(dev_priv);
7567         uint16_t tmp = 0;
7568
7569         pci_read_config_word(pdev, GCFGC, &tmp);
7570
7571         cdclk_sel = (tmp >> 12) & 0x1;
7572
7573         switch (vco) {
7574         case 2666667:
7575         case 4000000:
7576         case 5333333:
7577                 return cdclk_sel ? 333333 : 222222;
7578         case 3200000:
7579                 return cdclk_sel ? 320000 : 228571;
7580         default:
7581                 DRM_ERROR("Unable to determine CDCLK. HPLL VCO=%u, CFGC=0x%04x\n", vco, tmp);
7582                 return 222222;
7583         }
7584 }
7585
7586 static int i965gm_get_display_clock_speed(struct drm_i915_private *dev_priv)
7587 {
7588         struct pci_dev *pdev = dev_priv->drm.pdev;
7589         static const uint8_t div_3200[] = { 16, 10,  8 };
7590         static const uint8_t div_4000[] = { 20, 12, 10 };
7591         static const uint8_t div_5333[] = { 24, 16, 14 };
7592         const uint8_t *div_table;
7593         unsigned int cdclk_sel, vco = intel_hpll_vco(dev_priv);
7594         uint16_t tmp = 0;
7595
7596         pci_read_config_word(pdev, GCFGC, &tmp);
7597
7598         cdclk_sel = ((tmp >> 8) & 0x1f) - 1;
7599
7600         if (cdclk_sel >= ARRAY_SIZE(div_3200))
7601                 goto fail;
7602
7603         switch (vco) {
7604         case 3200000:
7605                 div_table = div_3200;
7606                 break;
7607         case 4000000:
7608                 div_table = div_4000;
7609                 break;
7610         case 5333333:
7611                 div_table = div_5333;
7612                 break;
7613         default:
7614                 goto fail;
7615         }
7616
7617         return DIV_ROUND_CLOSEST(vco, div_table[cdclk_sel]);
7618
7619 fail:
7620         DRM_ERROR("Unable to determine CDCLK. HPLL VCO=%u kHz, CFGC=0x%04x\n", vco, tmp);
7621         return 200000;
7622 }
7623
7624 static int g33_get_display_clock_speed(struct drm_i915_private *dev_priv)
7625 {
7626         struct pci_dev *pdev = dev_priv->drm.pdev;
7627         static const uint8_t div_3200[] = { 12, 10,  8,  7, 5, 16 };
7628         static const uint8_t div_4000[] = { 14, 12, 10,  8, 6, 20 };
7629         static const uint8_t div_4800[] = { 20, 14, 12, 10, 8, 24 };
7630         static const uint8_t div_5333[] = { 20, 16, 12, 12, 8, 28 };
7631         const uint8_t *div_table;
7632         unsigned int cdclk_sel, vco = intel_hpll_vco(dev_priv);
7633         uint16_t tmp = 0;
7634
7635         pci_read_config_word(pdev, GCFGC, &tmp);
7636
7637         cdclk_sel = (tmp >> 4) & 0x7;
7638
7639         if (cdclk_sel >= ARRAY_SIZE(div_3200))
7640                 goto fail;
7641
7642         switch (vco) {
7643         case 3200000:
7644                 div_table = div_3200;
7645                 break;
7646         case 4000000:
7647                 div_table = div_4000;
7648                 break;
7649         case 4800000:
7650                 div_table = div_4800;
7651                 break;
7652         case 5333333:
7653                 div_table = div_5333;
7654                 break;
7655         default:
7656                 goto fail;
7657         }
7658
7659         return DIV_ROUND_CLOSEST(vco, div_table[cdclk_sel]);
7660
7661 fail:
7662         DRM_ERROR("Unable to determine CDCLK. HPLL VCO=%u kHz, CFGC=0x%08x\n", vco, tmp);
7663         return 190476;
7664 }
7665
7666 static void
7667 intel_reduce_m_n_ratio(uint32_t *num, uint32_t *den)
7668 {
7669         while (*num > DATA_LINK_M_N_MASK ||
7670                *den > DATA_LINK_M_N_MASK) {
7671                 *num >>= 1;
7672                 *den >>= 1;
7673         }
7674 }
7675
7676 static void compute_m_n(unsigned int m, unsigned int n,
7677                         uint32_t *ret_m, uint32_t *ret_n)
7678 {
7679         *ret_n = min_t(unsigned int, roundup_pow_of_two(n), DATA_LINK_N_MAX);
7680         *ret_m = div_u64((uint64_t) m * *ret_n, n);
7681         intel_reduce_m_n_ratio(ret_m, ret_n);
7682 }
7683
7684 void
7685 intel_link_compute_m_n(int bits_per_pixel, int nlanes,
7686                        int pixel_clock, int link_clock,
7687                        struct intel_link_m_n *m_n)
7688 {
7689         m_n->tu = 64;
7690
7691         compute_m_n(bits_per_pixel * pixel_clock,
7692                     link_clock * nlanes * 8,
7693                     &m_n->gmch_m, &m_n->gmch_n);
7694
7695         compute_m_n(pixel_clock, link_clock,
7696                     &m_n->link_m, &m_n->link_n);
7697 }
7698
7699 static inline bool intel_panel_use_ssc(struct drm_i915_private *dev_priv)
7700 {
7701         if (i915.panel_use_ssc >= 0)
7702                 return i915.panel_use_ssc != 0;
7703         return dev_priv->vbt.lvds_use_ssc
7704                 && !(dev_priv->quirks & QUIRK_LVDS_SSC_DISABLE);
7705 }
7706
7707 static uint32_t pnv_dpll_compute_fp(struct dpll *dpll)
7708 {
7709         return (1 << dpll->n) << 16 | dpll->m2;
7710 }
7711
7712 static uint32_t i9xx_dpll_compute_fp(struct dpll *dpll)
7713 {
7714         return dpll->n << 16 | dpll->m1 << 8 | dpll->m2;
7715 }
7716
7717 static void i9xx_update_pll_dividers(struct intel_crtc *crtc,
7718                                      struct intel_crtc_state *crtc_state,
7719                                      struct dpll *reduced_clock)
7720 {
7721         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
7722         u32 fp, fp2 = 0;
7723
7724         if (IS_PINEVIEW(dev_priv)) {
7725                 fp = pnv_dpll_compute_fp(&crtc_state->dpll);
7726                 if (reduced_clock)
7727                         fp2 = pnv_dpll_compute_fp(reduced_clock);
7728         } else {
7729                 fp = i9xx_dpll_compute_fp(&crtc_state->dpll);
7730                 if (reduced_clock)
7731                         fp2 = i9xx_dpll_compute_fp(reduced_clock);
7732         }
7733
7734         crtc_state->dpll_hw_state.fp0 = fp;
7735
7736         crtc->lowfreq_avail = false;
7737         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS) &&
7738             reduced_clock) {
7739                 crtc_state->dpll_hw_state.fp1 = fp2;
7740                 crtc->lowfreq_avail = true;
7741         } else {
7742                 crtc_state->dpll_hw_state.fp1 = fp;
7743         }
7744 }
7745
7746 static void vlv_pllb_recal_opamp(struct drm_i915_private *dev_priv, enum pipe
7747                 pipe)
7748 {
7749         u32 reg_val;
7750
7751         /*
7752          * PLLB opamp always calibrates to max value of 0x3f, force enable it
7753          * and set it to a reasonable value instead.
7754          */
7755         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW9(1));
7756         reg_val &= 0xffffff00;
7757         reg_val |= 0x00000030;
7758         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW9(1), reg_val);
7759
7760         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_REF_DW13);
7761         reg_val &= 0x8cffffff;
7762         reg_val = 0x8c000000;
7763         vlv_dpio_write(dev_priv, pipe, VLV_REF_DW13, reg_val);
7764
7765         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW9(1));
7766         reg_val &= 0xffffff00;
7767         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW9(1), reg_val);
7768
7769         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_REF_DW13);
7770         reg_val &= 0x00ffffff;
7771         reg_val |= 0xb0000000;
7772         vlv_dpio_write(dev_priv, pipe, VLV_REF_DW13, reg_val);
7773 }
7774
7775 static void intel_pch_transcoder_set_m_n(struct intel_crtc *crtc,
7776                                          struct intel_link_m_n *m_n)
7777 {
7778         struct drm_device *dev = crtc->base.dev;
7779         struct drm_i915_private *dev_priv = to_i915(dev);
7780         int pipe = crtc->pipe;
7781
7782         I915_WRITE(PCH_TRANS_DATA_M1(pipe), TU_SIZE(m_n->tu) | m_n->gmch_m);
7783         I915_WRITE(PCH_TRANS_DATA_N1(pipe), m_n->gmch_n);
7784         I915_WRITE(PCH_TRANS_LINK_M1(pipe), m_n->link_m);
7785         I915_WRITE(PCH_TRANS_LINK_N1(pipe), m_n->link_n);
7786 }
7787
7788 static void intel_cpu_transcoder_set_m_n(struct intel_crtc *crtc,
7789                                          struct intel_link_m_n *m_n,
7790                                          struct intel_link_m_n *m2_n2)
7791 {
7792         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
7793         int pipe = crtc->pipe;
7794         enum transcoder transcoder = crtc->config->cpu_transcoder;
7795
7796         if (INTEL_GEN(dev_priv) >= 5) {
7797                 I915_WRITE(PIPE_DATA_M1(transcoder), TU_SIZE(m_n->tu) | m_n->gmch_m);
7798                 I915_WRITE(PIPE_DATA_N1(transcoder), m_n->gmch_n);
7799                 I915_WRITE(PIPE_LINK_M1(transcoder), m_n->link_m);
7800                 I915_WRITE(PIPE_LINK_N1(transcoder), m_n->link_n);
7801                 /* M2_N2 registers to be set only for gen < 8 (M2_N2 available
7802                  * for gen < 8) and if DRRS is supported (to make sure the
7803                  * registers are not unnecessarily accessed).
7804                  */
7805                 if (m2_n2 && (IS_CHERRYVIEW(dev_priv) ||
7806                     INTEL_GEN(dev_priv) < 8) && crtc->config->has_drrs) {
7807                         I915_WRITE(PIPE_DATA_M2(transcoder),
7808                                         TU_SIZE(m2_n2->tu) | m2_n2->gmch_m);
7809                         I915_WRITE(PIPE_DATA_N2(transcoder), m2_n2->gmch_n);
7810                         I915_WRITE(PIPE_LINK_M2(transcoder), m2_n2->link_m);
7811                         I915_WRITE(PIPE_LINK_N2(transcoder), m2_n2->link_n);
7812                 }
7813         } else {
7814                 I915_WRITE(PIPE_DATA_M_G4X(pipe), TU_SIZE(m_n->tu) | m_n->gmch_m);
7815                 I915_WRITE(PIPE_DATA_N_G4X(pipe), m_n->gmch_n);
7816                 I915_WRITE(PIPE_LINK_M_G4X(pipe), m_n->link_m);
7817                 I915_WRITE(PIPE_LINK_N_G4X(pipe), m_n->link_n);
7818         }
7819 }
7820
7821 void intel_dp_set_m_n(struct intel_crtc *crtc, enum link_m_n_set m_n)
7822 {
7823         struct intel_link_m_n *dp_m_n, *dp_m2_n2 = NULL;
7824
7825         if (m_n == M1_N1) {
7826                 dp_m_n = &crtc->config->dp_m_n;
7827                 dp_m2_n2 = &crtc->config->dp_m2_n2;
7828         } else if (m_n == M2_N2) {
7829
7830                 /*
7831                  * M2_N2 registers are not supported. Hence m2_n2 divider value
7832                  * needs to be programmed into M1_N1.
7833                  */
7834                 dp_m_n = &crtc->config->dp_m2_n2;
7835         } else {
7836                 DRM_ERROR("Unsupported divider value\n");
7837                 return;
7838         }
7839
7840         if (crtc->config->has_pch_encoder)
7841                 intel_pch_transcoder_set_m_n(crtc, &crtc->config->dp_m_n);
7842         else
7843                 intel_cpu_transcoder_set_m_n(crtc, dp_m_n, dp_m2_n2);
7844 }
7845
7846 static void vlv_compute_dpll(struct intel_crtc *crtc,
7847                              struct intel_crtc_state *pipe_config)
7848 {
7849         pipe_config->dpll_hw_state.dpll = DPLL_INTEGRATED_REF_CLK_VLV |
7850                 DPLL_REF_CLK_ENABLE_VLV | DPLL_VGA_MODE_DIS;
7851         if (crtc->pipe != PIPE_A)
7852                 pipe_config->dpll_hw_state.dpll |= DPLL_INTEGRATED_CRI_CLK_VLV;
7853
7854         /* DPLL not used with DSI, but still need the rest set up */
7855         if (!intel_crtc_has_type(pipe_config, INTEL_OUTPUT_DSI))
7856                 pipe_config->dpll_hw_state.dpll |= DPLL_VCO_ENABLE |
7857                         DPLL_EXT_BUFFER_ENABLE_VLV;
7858
7859         pipe_config->dpll_hw_state.dpll_md =
7860                 (pipe_config->pixel_multiplier - 1) << DPLL_MD_UDI_MULTIPLIER_SHIFT;
7861 }
7862
7863 static void chv_compute_dpll(struct intel_crtc *crtc,
7864                              struct intel_crtc_state *pipe_config)
7865 {
7866         pipe_config->dpll_hw_state.dpll = DPLL_SSC_REF_CLK_CHV |
7867                 DPLL_REF_CLK_ENABLE_VLV | DPLL_VGA_MODE_DIS;
7868         if (crtc->pipe != PIPE_A)
7869                 pipe_config->dpll_hw_state.dpll |= DPLL_INTEGRATED_CRI_CLK_VLV;
7870
7871         /* DPLL not used with DSI, but still need the rest set up */
7872         if (!intel_crtc_has_type(pipe_config, INTEL_OUTPUT_DSI))
7873                 pipe_config->dpll_hw_state.dpll |= DPLL_VCO_ENABLE;
7874
7875         pipe_config->dpll_hw_state.dpll_md =
7876                 (pipe_config->pixel_multiplier - 1) << DPLL_MD_UDI_MULTIPLIER_SHIFT;
7877 }
7878
7879 static void vlv_prepare_pll(struct intel_crtc *crtc,
7880                             const struct intel_crtc_state *pipe_config)
7881 {
7882         struct drm_device *dev = crtc->base.dev;
7883         struct drm_i915_private *dev_priv = to_i915(dev);
7884         enum pipe pipe = crtc->pipe;
7885         u32 mdiv;
7886         u32 bestn, bestm1, bestm2, bestp1, bestp2;
7887         u32 coreclk, reg_val;
7888
7889         /* Enable Refclk */
7890         I915_WRITE(DPLL(pipe),
7891                    pipe_config->dpll_hw_state.dpll &
7892                    ~(DPLL_VCO_ENABLE | DPLL_EXT_BUFFER_ENABLE_VLV));
7893
7894         /* No need to actually set up the DPLL with DSI */
7895         if ((pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE) == 0)
7896                 return;
7897
7898         mutex_lock(&dev_priv->sb_lock);
7899
7900         bestn = pipe_config->dpll.n;
7901         bestm1 = pipe_config->dpll.m1;
7902         bestm2 = pipe_config->dpll.m2;
7903         bestp1 = pipe_config->dpll.p1;
7904         bestp2 = pipe_config->dpll.p2;
7905
7906         /* See eDP HDMI DPIO driver vbios notes doc */
7907
7908         /* PLL B needs special handling */
7909         if (pipe == PIPE_B)
7910                 vlv_pllb_recal_opamp(dev_priv, pipe);
7911
7912         /* Set up Tx target for periodic Rcomp update */
7913         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW9_BCAST, 0x0100000f);
7914
7915         /* Disable target IRef on PLL */
7916         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW8(pipe));
7917         reg_val &= 0x00ffffff;
7918         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW8(pipe), reg_val);
7919
7920         /* Disable fast lock */
7921         vlv_dpio_write(dev_priv, pipe, VLV_CMN_DW0, 0x610);
7922
7923         /* Set idtafcrecal before PLL is enabled */
7924         mdiv = ((bestm1 << DPIO_M1DIV_SHIFT) | (bestm2 & DPIO_M2DIV_MASK));
7925         mdiv |= ((bestp1 << DPIO_P1_SHIFT) | (bestp2 << DPIO_P2_SHIFT));
7926         mdiv |= ((bestn << DPIO_N_SHIFT));
7927         mdiv |= (1 << DPIO_K_SHIFT);
7928
7929         /*
7930          * Post divider depends on pixel clock rate, DAC vs digital (and LVDS,
7931          * but we don't support that).
7932          * Note: don't use the DAC post divider as it seems unstable.
7933          */
7934         mdiv |= (DPIO_POST_DIV_HDMIDP << DPIO_POST_DIV_SHIFT);
7935         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW3(pipe), mdiv);
7936
7937         mdiv |= DPIO_ENABLE_CALIBRATION;
7938         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW3(pipe), mdiv);
7939
7940         /* Set HBR and RBR LPF coefficients */
7941         if (pipe_config->port_clock == 162000 ||
7942             intel_crtc_has_type(crtc->config, INTEL_OUTPUT_ANALOG) ||
7943             intel_crtc_has_type(crtc->config, INTEL_OUTPUT_HDMI))
7944                 vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW10(pipe),
7945                                  0x009f0003);
7946         else
7947                 vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW10(pipe),
7948                                  0x00d0000f);
7949
7950         if (intel_crtc_has_dp_encoder(pipe_config)) {
7951                 /* Use SSC source */
7952                 if (pipe == PIPE_A)
7953                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
7954                                          0x0df40000);
7955                 else
7956                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
7957                                          0x0df70000);
7958         } else { /* HDMI or VGA */
7959                 /* Use bend source */
7960                 if (pipe == PIPE_A)
7961                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
7962                                          0x0df70000);
7963                 else
7964                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
7965                                          0x0df40000);
7966         }
7967
7968         coreclk = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW7(pipe));
7969         coreclk = (coreclk & 0x0000ff00) | 0x01c00000;
7970         if (intel_crtc_has_dp_encoder(crtc->config))
7971                 coreclk |= 0x01000000;
7972         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW7(pipe), coreclk);
7973
7974         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW11(pipe), 0x87871000);
7975         mutex_unlock(&dev_priv->sb_lock);
7976 }
7977
7978 static void chv_prepare_pll(struct intel_crtc *crtc,
7979                             const struct intel_crtc_state *pipe_config)
7980 {
7981         struct drm_device *dev = crtc->base.dev;
7982         struct drm_i915_private *dev_priv = to_i915(dev);
7983         enum pipe pipe = crtc->pipe;
7984         enum dpio_channel port = vlv_pipe_to_channel(pipe);
7985         u32 loopfilter, tribuf_calcntr;
7986         u32 bestn, bestm1, bestm2, bestp1, bestp2, bestm2_frac;
7987         u32 dpio_val;
7988         int vco;
7989
7990         /* Enable Refclk and SSC */
7991         I915_WRITE(DPLL(pipe),
7992                    pipe_config->dpll_hw_state.dpll & ~DPLL_VCO_ENABLE);
7993
7994         /* No need to actually set up the DPLL with DSI */
7995         if ((pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE) == 0)
7996                 return;
7997
7998         bestn = pipe_config->dpll.n;
7999         bestm2_frac = pipe_config->dpll.m2 & 0x3fffff;
8000         bestm1 = pipe_config->dpll.m1;
8001         bestm2 = pipe_config->dpll.m2 >> 22;
8002         bestp1 = pipe_config->dpll.p1;
8003         bestp2 = pipe_config->dpll.p2;
8004         vco = pipe_config->dpll.vco;
8005         dpio_val = 0;
8006         loopfilter = 0;
8007
8008         mutex_lock(&dev_priv->sb_lock);
8009
8010         /* p1 and p2 divider */
8011         vlv_dpio_write(dev_priv, pipe, CHV_CMN_DW13(port),
8012                         5 << DPIO_CHV_S1_DIV_SHIFT |
8013                         bestp1 << DPIO_CHV_P1_DIV_SHIFT |
8014                         bestp2 << DPIO_CHV_P2_DIV_SHIFT |
8015                         1 << DPIO_CHV_K_DIV_SHIFT);
8016
8017         /* Feedback post-divider - m2 */
8018         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW0(port), bestm2);
8019
8020         /* Feedback refclk divider - n and m1 */
8021         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW1(port),
8022                         DPIO_CHV_M1_DIV_BY_2 |
8023                         1 << DPIO_CHV_N_DIV_SHIFT);
8024
8025         /* M2 fraction division */
8026         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW2(port), bestm2_frac);
8027
8028         /* M2 fraction division enable */
8029         dpio_val = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW3(port));
8030         dpio_val &= ~(DPIO_CHV_FEEDFWD_GAIN_MASK | DPIO_CHV_FRAC_DIV_EN);
8031         dpio_val |= (2 << DPIO_CHV_FEEDFWD_GAIN_SHIFT);
8032         if (bestm2_frac)
8033                 dpio_val |= DPIO_CHV_FRAC_DIV_EN;
8034         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW3(port), dpio_val);
8035
8036         /* Program digital lock detect threshold */
8037         dpio_val = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW9(port));
8038         dpio_val &= ~(DPIO_CHV_INT_LOCK_THRESHOLD_MASK |
8039                                         DPIO_CHV_INT_LOCK_THRESHOLD_SEL_COARSE);
8040         dpio_val |= (0x5 << DPIO_CHV_INT_LOCK_THRESHOLD_SHIFT);
8041         if (!bestm2_frac)
8042                 dpio_val |= DPIO_CHV_INT_LOCK_THRESHOLD_SEL_COARSE;
8043         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW9(port), dpio_val);
8044
8045         /* Loop filter */
8046         if (vco == 5400000) {
8047                 loopfilter |= (0x3 << DPIO_CHV_PROP_COEFF_SHIFT);
8048                 loopfilter |= (0x8 << DPIO_CHV_INT_COEFF_SHIFT);
8049                 loopfilter |= (0x1 << DPIO_CHV_GAIN_CTRL_SHIFT);
8050                 tribuf_calcntr = 0x9;
8051         } else if (vco <= 6200000) {
8052                 loopfilter |= (0x5 << DPIO_CHV_PROP_COEFF_SHIFT);
8053                 loopfilter |= (0xB << DPIO_CHV_INT_COEFF_SHIFT);
8054                 loopfilter |= (0x3 << DPIO_CHV_GAIN_CTRL_SHIFT);
8055                 tribuf_calcntr = 0x9;
8056         } else if (vco <= 6480000) {
8057                 loopfilter |= (0x4 << DPIO_CHV_PROP_COEFF_SHIFT);
8058                 loopfilter |= (0x9 << DPIO_CHV_INT_COEFF_SHIFT);
8059                 loopfilter |= (0x3 << DPIO_CHV_GAIN_CTRL_SHIFT);
8060                 tribuf_calcntr = 0x8;
8061         } else {
8062                 /* Not supported. Apply the same limits as in the max case */
8063                 loopfilter |= (0x4 << DPIO_CHV_PROP_COEFF_SHIFT);
8064                 loopfilter |= (0x9 << DPIO_CHV_INT_COEFF_SHIFT);
8065                 loopfilter |= (0x3 << DPIO_CHV_GAIN_CTRL_SHIFT);
8066                 tribuf_calcntr = 0;
8067         }
8068         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW6(port), loopfilter);
8069
8070         dpio_val = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW8(port));
8071         dpio_val &= ~DPIO_CHV_TDC_TARGET_CNT_MASK;
8072         dpio_val |= (tribuf_calcntr << DPIO_CHV_TDC_TARGET_CNT_SHIFT);
8073         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW8(port), dpio_val);
8074
8075         /* AFC Recal */
8076         vlv_dpio_write(dev_priv, pipe, CHV_CMN_DW14(port),
8077                         vlv_dpio_read(dev_priv, pipe, CHV_CMN_DW14(port)) |
8078                         DPIO_AFC_RECAL);
8079
8080         mutex_unlock(&dev_priv->sb_lock);
8081 }
8082
8083 /**
8084  * vlv_force_pll_on - forcibly enable just the PLL
8085  * @dev_priv: i915 private structure
8086  * @pipe: pipe PLL to enable
8087  * @dpll: PLL configuration
8088  *
8089  * Enable the PLL for @pipe using the supplied @dpll config. To be used
8090  * in cases where we need the PLL enabled even when @pipe is not going to
8091  * be enabled.
8092  */
8093 int vlv_force_pll_on(struct drm_i915_private *dev_priv, enum pipe pipe,
8094                      const struct dpll *dpll)
8095 {
8096         struct intel_crtc *crtc = intel_get_crtc_for_pipe(dev_priv, pipe);
8097         struct intel_crtc_state *pipe_config;
8098
8099         pipe_config = kzalloc(sizeof(*pipe_config), GFP_KERNEL);
8100         if (!pipe_config)
8101                 return -ENOMEM;
8102
8103         pipe_config->base.crtc = &crtc->base;
8104         pipe_config->pixel_multiplier = 1;
8105         pipe_config->dpll = *dpll;
8106
8107         if (IS_CHERRYVIEW(dev_priv)) {
8108                 chv_compute_dpll(crtc, pipe_config);
8109                 chv_prepare_pll(crtc, pipe_config);
8110                 chv_enable_pll(crtc, pipe_config);
8111         } else {
8112                 vlv_compute_dpll(crtc, pipe_config);
8113                 vlv_prepare_pll(crtc, pipe_config);
8114                 vlv_enable_pll(crtc, pipe_config);
8115         }
8116
8117         kfree(pipe_config);
8118
8119         return 0;
8120 }
8121
8122 /**
8123  * vlv_force_pll_off - forcibly disable just the PLL
8124  * @dev_priv: i915 private structure
8125  * @pipe: pipe PLL to disable
8126  *
8127  * Disable the PLL for @pipe. To be used in cases where we need
8128  * the PLL enabled even when @pipe is not going to be enabled.
8129  */
8130 void vlv_force_pll_off(struct drm_i915_private *dev_priv, enum pipe pipe)
8131 {
8132         if (IS_CHERRYVIEW(dev_priv))
8133                 chv_disable_pll(dev_priv, pipe);
8134         else
8135                 vlv_disable_pll(dev_priv, pipe);
8136 }
8137
8138 static void i9xx_compute_dpll(struct intel_crtc *crtc,
8139                               struct intel_crtc_state *crtc_state,
8140                               struct dpll *reduced_clock)
8141 {
8142         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
8143         u32 dpll;
8144         struct dpll *clock = &crtc_state->dpll;
8145
8146         i9xx_update_pll_dividers(crtc, crtc_state, reduced_clock);
8147
8148         dpll = DPLL_VGA_MODE_DIS;
8149
8150         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS))
8151                 dpll |= DPLLB_MODE_LVDS;
8152         else
8153                 dpll |= DPLLB_MODE_DAC_SERIAL;
8154
8155         if (IS_I945G(dev_priv) || IS_I945GM(dev_priv) ||
8156             IS_G33(dev_priv) || IS_PINEVIEW(dev_priv)) {
8157                 dpll |= (crtc_state->pixel_multiplier - 1)
8158                         << SDVO_MULTIPLIER_SHIFT_HIRES;
8159         }
8160
8161         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_SDVO) ||
8162             intel_crtc_has_type(crtc_state, INTEL_OUTPUT_HDMI))
8163                 dpll |= DPLL_SDVO_HIGH_SPEED;
8164
8165         if (intel_crtc_has_dp_encoder(crtc_state))
8166                 dpll |= DPLL_SDVO_HIGH_SPEED;
8167
8168         /* compute bitmask from p1 value */
8169         if (IS_PINEVIEW(dev_priv))
8170                 dpll |= (1 << (clock->p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT_PINEVIEW;
8171         else {
8172                 dpll |= (1 << (clock->p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT;
8173                 if (IS_G4X(dev_priv) && reduced_clock)
8174                         dpll |= (1 << (reduced_clock->p1 - 1)) << DPLL_FPA1_P1_POST_DIV_SHIFT;
8175         }
8176         switch (clock->p2) {
8177         case 5:
8178                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_5;
8179                 break;
8180         case 7:
8181                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_7;
8182                 break;
8183         case 10:
8184                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_10;
8185                 break;
8186         case 14:
8187                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_14;
8188                 break;
8189         }
8190         if (INTEL_GEN(dev_priv) >= 4)
8191                 dpll |= (6 << PLL_LOAD_PULSE_PHASE_SHIFT);
8192
8193         if (crtc_state->sdvo_tv_clock)
8194                 dpll |= PLL_REF_INPUT_TVCLKINBC;
8195         else if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS) &&
8196                  intel_panel_use_ssc(dev_priv))
8197                 dpll |= PLLB_REF_INPUT_SPREADSPECTRUMIN;
8198         else
8199                 dpll |= PLL_REF_INPUT_DREFCLK;
8200
8201         dpll |= DPLL_VCO_ENABLE;
8202         crtc_state->dpll_hw_state.dpll = dpll;
8203
8204         if (INTEL_GEN(dev_priv) >= 4) {
8205                 u32 dpll_md = (crtc_state->pixel_multiplier - 1)
8206                         << DPLL_MD_UDI_MULTIPLIER_SHIFT;
8207                 crtc_state->dpll_hw_state.dpll_md = dpll_md;
8208         }
8209 }
8210
8211 static void i8xx_compute_dpll(struct intel_crtc *crtc,
8212                               struct intel_crtc_state *crtc_state,
8213                               struct dpll *reduced_clock)
8214 {
8215         struct drm_device *dev = crtc->base.dev;
8216         struct drm_i915_private *dev_priv = to_i915(dev);
8217         u32 dpll;
8218         struct dpll *clock = &crtc_state->dpll;
8219
8220         i9xx_update_pll_dividers(crtc, crtc_state, reduced_clock);
8221
8222         dpll = DPLL_VGA_MODE_DIS;
8223
8224         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
8225                 dpll |= (1 << (clock->p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT;
8226         } else {
8227                 if (clock->p1 == 2)
8228                         dpll |= PLL_P1_DIVIDE_BY_TWO;
8229                 else
8230                         dpll |= (clock->p1 - 2) << DPLL_FPA01_P1_POST_DIV_SHIFT;
8231                 if (clock->p2 == 4)
8232                         dpll |= PLL_P2_DIVIDE_BY_4;
8233         }
8234
8235         if (!IS_I830(dev_priv) &&
8236             intel_crtc_has_type(crtc_state, INTEL_OUTPUT_DVO))
8237                 dpll |= DPLL_DVO_2X_MODE;
8238
8239         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS) &&
8240             intel_panel_use_ssc(dev_priv))
8241                 dpll |= PLLB_REF_INPUT_SPREADSPECTRUMIN;
8242         else
8243                 dpll |= PLL_REF_INPUT_DREFCLK;
8244
8245         dpll |= DPLL_VCO_ENABLE;
8246         crtc_state->dpll_hw_state.dpll = dpll;
8247 }
8248
8249 static void intel_set_pipe_timings(struct intel_crtc *intel_crtc)
8250 {
8251         struct drm_i915_private *dev_priv = to_i915(intel_crtc->base.dev);
8252         enum pipe pipe = intel_crtc->pipe;
8253         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
8254         const struct drm_display_mode *adjusted_mode = &intel_crtc->config->base.adjusted_mode;
8255         uint32_t crtc_vtotal, crtc_vblank_end;
8256         int vsyncshift = 0;
8257
8258         /* We need to be careful not to changed the adjusted mode, for otherwise
8259          * the hw state checker will get angry at the mismatch. */
8260         crtc_vtotal = adjusted_mode->crtc_vtotal;
8261         crtc_vblank_end = adjusted_mode->crtc_vblank_end;
8262
8263         if (adjusted_mode->flags & DRM_MODE_FLAG_INTERLACE) {
8264                 /* the chip adds 2 halflines automatically */
8265                 crtc_vtotal -= 1;
8266                 crtc_vblank_end -= 1;
8267
8268                 if (intel_crtc_has_type(intel_crtc->config, INTEL_OUTPUT_SDVO))
8269                         vsyncshift = (adjusted_mode->crtc_htotal - 1) / 2;
8270                 else
8271                         vsyncshift = adjusted_mode->crtc_hsync_start -
8272                                 adjusted_mode->crtc_htotal / 2;
8273                 if (vsyncshift < 0)
8274                         vsyncshift += adjusted_mode->crtc_htotal;
8275         }
8276
8277         if (INTEL_GEN(dev_priv) > 3)
8278                 I915_WRITE(VSYNCSHIFT(cpu_transcoder), vsyncshift);
8279
8280         I915_WRITE(HTOTAL(cpu_transcoder),
8281                    (adjusted_mode->crtc_hdisplay - 1) |
8282                    ((adjusted_mode->crtc_htotal - 1) << 16));
8283         I915_WRITE(HBLANK(cpu_transcoder),
8284                    (adjusted_mode->crtc_hblank_start - 1) |
8285                    ((adjusted_mode->crtc_hblank_end - 1) << 16));
8286         I915_WRITE(HSYNC(cpu_transcoder),
8287                    (adjusted_mode->crtc_hsync_start - 1) |
8288                    ((adjusted_mode->crtc_hsync_end - 1) << 16));
8289
8290         I915_WRITE(VTOTAL(cpu_transcoder),
8291                    (adjusted_mode->crtc_vdisplay - 1) |
8292                    ((crtc_vtotal - 1) << 16));
8293         I915_WRITE(VBLANK(cpu_transcoder),
8294                    (adjusted_mode->crtc_vblank_start - 1) |
8295                    ((crtc_vblank_end - 1) << 16));
8296         I915_WRITE(VSYNC(cpu_transcoder),
8297                    (adjusted_mode->crtc_vsync_start - 1) |
8298                    ((adjusted_mode->crtc_vsync_end - 1) << 16));
8299
8300         /* Workaround: when the EDP input selection is B, the VTOTAL_B must be
8301          * programmed with the VTOTAL_EDP value. Same for VTOTAL_C. This is
8302          * documented on the DDI_FUNC_CTL register description, EDP Input Select
8303          * bits. */
8304         if (IS_HASWELL(dev_priv) && cpu_transcoder == TRANSCODER_EDP &&
8305             (pipe == PIPE_B || pipe == PIPE_C))
8306                 I915_WRITE(VTOTAL(pipe), I915_READ(VTOTAL(cpu_transcoder)));
8307
8308 }
8309
8310 static void intel_set_pipe_src_size(struct intel_crtc *intel_crtc)
8311 {
8312         struct drm_device *dev = intel_crtc->base.dev;
8313         struct drm_i915_private *dev_priv = to_i915(dev);
8314         enum pipe pipe = intel_crtc->pipe;
8315
8316         /* pipesrc controls the size that is scaled from, which should
8317          * always be the user's requested size.
8318          */
8319         I915_WRITE(PIPESRC(pipe),
8320                    ((intel_crtc->config->pipe_src_w - 1) << 16) |
8321                    (intel_crtc->config->pipe_src_h - 1));
8322 }
8323
8324 static void intel_get_pipe_timings(struct intel_crtc *crtc,
8325                                    struct intel_crtc_state *pipe_config)
8326 {
8327         struct drm_device *dev = crtc->base.dev;
8328         struct drm_i915_private *dev_priv = to_i915(dev);
8329         enum transcoder cpu_transcoder = pipe_config->cpu_transcoder;
8330         uint32_t tmp;
8331
8332         tmp = I915_READ(HTOTAL(cpu_transcoder));
8333         pipe_config->base.adjusted_mode.crtc_hdisplay = (tmp & 0xffff) + 1;
8334         pipe_config->base.adjusted_mode.crtc_htotal = ((tmp >> 16) & 0xffff) + 1;
8335         tmp = I915_READ(HBLANK(cpu_transcoder));
8336         pipe_config->base.adjusted_mode.crtc_hblank_start = (tmp & 0xffff) + 1;
8337         pipe_config->base.adjusted_mode.crtc_hblank_end = ((tmp >> 16) & 0xffff) + 1;
8338         tmp = I915_READ(HSYNC(cpu_transcoder));
8339         pipe_config->base.adjusted_mode.crtc_hsync_start = (tmp & 0xffff) + 1;
8340         pipe_config->base.adjusted_mode.crtc_hsync_end = ((tmp >> 16) & 0xffff) + 1;
8341
8342         tmp = I915_READ(VTOTAL(cpu_transcoder));
8343         pipe_config->base.adjusted_mode.crtc_vdisplay = (tmp & 0xffff) + 1;
8344         pipe_config->base.adjusted_mode.crtc_vtotal = ((tmp >> 16) & 0xffff) + 1;
8345         tmp = I915_READ(VBLANK(cpu_transcoder));
8346         pipe_config->base.adjusted_mode.crtc_vblank_start = (tmp & 0xffff) + 1;
8347         pipe_config->base.adjusted_mode.crtc_vblank_end = ((tmp >> 16) & 0xffff) + 1;
8348         tmp = I915_READ(VSYNC(cpu_transcoder));
8349         pipe_config->base.adjusted_mode.crtc_vsync_start = (tmp & 0xffff) + 1;
8350         pipe_config->base.adjusted_mode.crtc_vsync_end = ((tmp >> 16) & 0xffff) + 1;
8351
8352         if (I915_READ(PIPECONF(cpu_transcoder)) & PIPECONF_INTERLACE_MASK) {
8353                 pipe_config->base.adjusted_mode.flags |= DRM_MODE_FLAG_INTERLACE;
8354                 pipe_config->base.adjusted_mode.crtc_vtotal += 1;
8355                 pipe_config->base.adjusted_mode.crtc_vblank_end += 1;
8356         }
8357 }
8358
8359 static void intel_get_pipe_src_size(struct intel_crtc *crtc,
8360                                     struct intel_crtc_state *pipe_config)
8361 {
8362         struct drm_device *dev = crtc->base.dev;
8363         struct drm_i915_private *dev_priv = to_i915(dev);
8364         u32 tmp;
8365
8366         tmp = I915_READ(PIPESRC(crtc->pipe));
8367         pipe_config->pipe_src_h = (tmp & 0xffff) + 1;
8368         pipe_config->pipe_src_w = ((tmp >> 16) & 0xffff) + 1;
8369
8370         pipe_config->base.mode.vdisplay = pipe_config->pipe_src_h;
8371         pipe_config->base.mode.hdisplay = pipe_config->pipe_src_w;
8372 }
8373
8374 void intel_mode_from_pipe_config(struct drm_display_mode *mode,
8375                                  struct intel_crtc_state *pipe_config)
8376 {
8377         mode->hdisplay = pipe_config->base.adjusted_mode.crtc_hdisplay;
8378         mode->htotal = pipe_config->base.adjusted_mode.crtc_htotal;
8379         mode->hsync_start = pipe_config->base.adjusted_mode.crtc_hsync_start;
8380         mode->hsync_end = pipe_config->base.adjusted_mode.crtc_hsync_end;
8381
8382         mode->vdisplay = pipe_config->base.adjusted_mode.crtc_vdisplay;
8383         mode->vtotal = pipe_config->base.adjusted_mode.crtc_vtotal;
8384         mode->vsync_start = pipe_config->base.adjusted_mode.crtc_vsync_start;
8385         mode->vsync_end = pipe_config->base.adjusted_mode.crtc_vsync_end;
8386
8387         mode->flags = pipe_config->base.adjusted_mode.flags;
8388         mode->type = DRM_MODE_TYPE_DRIVER;
8389
8390         mode->clock = pipe_config->base.adjusted_mode.crtc_clock;
8391
8392         mode->hsync = drm_mode_hsync(mode);
8393         mode->vrefresh = drm_mode_vrefresh(mode);
8394         drm_mode_set_name(mode);
8395 }
8396
8397 static void i9xx_set_pipeconf(struct intel_crtc *intel_crtc)
8398 {
8399         struct drm_i915_private *dev_priv = to_i915(intel_crtc->base.dev);
8400         uint32_t pipeconf;
8401
8402         pipeconf = 0;
8403
8404         if ((intel_crtc->pipe == PIPE_A && dev_priv->quirks & QUIRK_PIPEA_FORCE) ||
8405             (intel_crtc->pipe == PIPE_B && dev_priv->quirks & QUIRK_PIPEB_FORCE))
8406                 pipeconf |= I915_READ(PIPECONF(intel_crtc->pipe)) & PIPECONF_ENABLE;
8407
8408         if (intel_crtc->config->double_wide)
8409                 pipeconf |= PIPECONF_DOUBLE_WIDE;
8410
8411         /* only g4x and later have fancy bpc/dither controls */
8412         if (IS_G4X(dev_priv) || IS_VALLEYVIEW(dev_priv) ||
8413             IS_CHERRYVIEW(dev_priv)) {
8414                 /* Bspec claims that we can't use dithering for 30bpp pipes. */
8415                 if (intel_crtc->config->dither && intel_crtc->config->pipe_bpp != 30)
8416                         pipeconf |= PIPECONF_DITHER_EN |
8417                                     PIPECONF_DITHER_TYPE_SP;
8418
8419                 switch (intel_crtc->config->pipe_bpp) {
8420                 case 18:
8421                         pipeconf |= PIPECONF_6BPC;
8422                         break;
8423                 case 24:
8424                         pipeconf |= PIPECONF_8BPC;
8425                         break;
8426                 case 30:
8427                         pipeconf |= PIPECONF_10BPC;
8428                         break;
8429                 default:
8430                         /* Case prevented by intel_choose_pipe_bpp_dither. */
8431                         BUG();
8432                 }
8433         }
8434
8435         if (HAS_PIPE_CXSR(dev_priv)) {
8436                 if (intel_crtc->lowfreq_avail) {
8437                         DRM_DEBUG_KMS("enabling CxSR downclocking\n");
8438                         pipeconf |= PIPECONF_CXSR_DOWNCLOCK;
8439                 } else {
8440                         DRM_DEBUG_KMS("disabling CxSR downclocking\n");
8441                 }
8442         }
8443
8444         if (intel_crtc->config->base.adjusted_mode.flags & DRM_MODE_FLAG_INTERLACE) {
8445                 if (INTEL_GEN(dev_priv) < 4 ||
8446                     intel_crtc_has_type(intel_crtc->config, INTEL_OUTPUT_SDVO))
8447                         pipeconf |= PIPECONF_INTERLACE_W_FIELD_INDICATION;
8448                 else
8449                         pipeconf |= PIPECONF_INTERLACE_W_SYNC_SHIFT;
8450         } else
8451                 pipeconf |= PIPECONF_PROGRESSIVE;
8452
8453         if ((IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv)) &&
8454              intel_crtc->config->limited_color_range)
8455                 pipeconf |= PIPECONF_COLOR_RANGE_SELECT;
8456
8457         I915_WRITE(PIPECONF(intel_crtc->pipe), pipeconf);
8458         POSTING_READ(PIPECONF(intel_crtc->pipe));
8459 }
8460
8461 static int i8xx_crtc_compute_clock(struct intel_crtc *crtc,
8462                                    struct intel_crtc_state *crtc_state)
8463 {
8464         struct drm_device *dev = crtc->base.dev;
8465         struct drm_i915_private *dev_priv = to_i915(dev);
8466         const struct intel_limit *limit;
8467         int refclk = 48000;
8468
8469         memset(&crtc_state->dpll_hw_state, 0,
8470                sizeof(crtc_state->dpll_hw_state));
8471
8472         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
8473                 if (intel_panel_use_ssc(dev_priv)) {
8474                         refclk = dev_priv->vbt.lvds_ssc_freq;
8475                         DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n", refclk);
8476                 }
8477
8478                 limit = &intel_limits_i8xx_lvds;
8479         } else if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_DVO)) {
8480                 limit = &intel_limits_i8xx_dvo;
8481         } else {
8482                 limit = &intel_limits_i8xx_dac;
8483         }
8484
8485         if (!crtc_state->clock_set &&
8486             !i9xx_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
8487                                  refclk, NULL, &crtc_state->dpll)) {
8488                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
8489                 return -EINVAL;
8490         }
8491
8492         i8xx_compute_dpll(crtc, crtc_state, NULL);
8493
8494         return 0;
8495 }
8496
8497 static int g4x_crtc_compute_clock(struct intel_crtc *crtc,
8498                                   struct intel_crtc_state *crtc_state)
8499 {
8500         struct drm_device *dev = crtc->base.dev;
8501         struct drm_i915_private *dev_priv = to_i915(dev);
8502         const struct intel_limit *limit;
8503         int refclk = 96000;
8504
8505         memset(&crtc_state->dpll_hw_state, 0,
8506                sizeof(crtc_state->dpll_hw_state));
8507
8508         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
8509                 if (intel_panel_use_ssc(dev_priv)) {
8510                         refclk = dev_priv->vbt.lvds_ssc_freq;
8511                         DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n", refclk);
8512                 }
8513
8514                 if (intel_is_dual_link_lvds(dev))
8515                         limit = &intel_limits_g4x_dual_channel_lvds;
8516                 else
8517                         limit = &intel_limits_g4x_single_channel_lvds;
8518         } else if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_HDMI) ||
8519                    intel_crtc_has_type(crtc_state, INTEL_OUTPUT_ANALOG)) {
8520                 limit = &intel_limits_g4x_hdmi;
8521         } else if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_SDVO)) {
8522                 limit = &intel_limits_g4x_sdvo;
8523         } else {
8524                 /* The option is for other outputs */
8525                 limit = &intel_limits_i9xx_sdvo;
8526         }
8527
8528         if (!crtc_state->clock_set &&
8529             !g4x_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
8530                                 refclk, NULL, &crtc_state->dpll)) {
8531                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
8532                 return -EINVAL;
8533         }
8534
8535         i9xx_compute_dpll(crtc, crtc_state, NULL);
8536
8537         return 0;
8538 }
8539
8540 static int pnv_crtc_compute_clock(struct intel_crtc *crtc,
8541                                   struct intel_crtc_state *crtc_state)
8542 {
8543         struct drm_device *dev = crtc->base.dev;
8544         struct drm_i915_private *dev_priv = to_i915(dev);
8545         const struct intel_limit *limit;
8546         int refclk = 96000;
8547
8548         memset(&crtc_state->dpll_hw_state, 0,
8549                sizeof(crtc_state->dpll_hw_state));
8550
8551         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
8552                 if (intel_panel_use_ssc(dev_priv)) {
8553                         refclk = dev_priv->vbt.lvds_ssc_freq;
8554                         DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n", refclk);
8555                 }
8556
8557                 limit = &intel_limits_pineview_lvds;
8558         } else {
8559                 limit = &intel_limits_pineview_sdvo;
8560         }
8561
8562         if (!crtc_state->clock_set &&
8563             !pnv_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
8564                                 refclk, NULL, &crtc_state->dpll)) {
8565                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
8566                 return -EINVAL;
8567         }
8568
8569         i9xx_compute_dpll(crtc, crtc_state, NULL);
8570
8571         return 0;
8572 }
8573
8574 static int i9xx_crtc_compute_clock(struct intel_crtc *crtc,
8575                                    struct intel_crtc_state *crtc_state)
8576 {
8577         struct drm_device *dev = crtc->base.dev;
8578         struct drm_i915_private *dev_priv = to_i915(dev);
8579         const struct intel_limit *limit;
8580         int refclk = 96000;
8581
8582         memset(&crtc_state->dpll_hw_state, 0,
8583                sizeof(crtc_state->dpll_hw_state));
8584
8585         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
8586                 if (intel_panel_use_ssc(dev_priv)) {
8587                         refclk = dev_priv->vbt.lvds_ssc_freq;
8588                         DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n", refclk);
8589                 }
8590
8591                 limit = &intel_limits_i9xx_lvds;
8592         } else {
8593                 limit = &intel_limits_i9xx_sdvo;
8594         }
8595
8596         if (!crtc_state->clock_set &&
8597             !i9xx_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
8598                                  refclk, NULL, &crtc_state->dpll)) {
8599                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
8600                 return -EINVAL;
8601         }
8602
8603         i9xx_compute_dpll(crtc, crtc_state, NULL);
8604
8605         return 0;
8606 }
8607
8608 static int chv_crtc_compute_clock(struct intel_crtc *crtc,
8609                                   struct intel_crtc_state *crtc_state)
8610 {
8611         int refclk = 100000;
8612         const struct intel_limit *limit = &intel_limits_chv;
8613
8614         memset(&crtc_state->dpll_hw_state, 0,
8615                sizeof(crtc_state->dpll_hw_state));
8616
8617         if (!crtc_state->clock_set &&
8618             !chv_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
8619                                 refclk, NULL, &crtc_state->dpll)) {
8620                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
8621                 return -EINVAL;
8622         }
8623
8624         chv_compute_dpll(crtc, crtc_state);
8625
8626         return 0;
8627 }
8628
8629 static int vlv_crtc_compute_clock(struct intel_crtc *crtc,
8630                                   struct intel_crtc_state *crtc_state)
8631 {
8632         int refclk = 100000;
8633         const struct intel_limit *limit = &intel_limits_vlv;
8634
8635         memset(&crtc_state->dpll_hw_state, 0,
8636                sizeof(crtc_state->dpll_hw_state));
8637
8638         if (!crtc_state->clock_set &&
8639             !vlv_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
8640                                 refclk, NULL, &crtc_state->dpll)) {
8641                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
8642                 return -EINVAL;
8643         }
8644
8645         vlv_compute_dpll(crtc, crtc_state);
8646
8647         return 0;
8648 }
8649
8650 static void i9xx_get_pfit_config(struct intel_crtc *crtc,
8651                                  struct intel_crtc_state *pipe_config)
8652 {
8653         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
8654         uint32_t tmp;
8655
8656         if (INTEL_GEN(dev_priv) <= 3 &&
8657             (IS_I830(dev_priv) || !IS_MOBILE(dev_priv)))
8658                 return;
8659
8660         tmp = I915_READ(PFIT_CONTROL);
8661         if (!(tmp & PFIT_ENABLE))
8662                 return;
8663
8664         /* Check whether the pfit is attached to our pipe. */
8665         if (INTEL_GEN(dev_priv) < 4) {
8666                 if (crtc->pipe != PIPE_B)
8667                         return;
8668         } else {
8669                 if ((tmp & PFIT_PIPE_MASK) != (crtc->pipe << PFIT_PIPE_SHIFT))
8670                         return;
8671         }
8672
8673         pipe_config->gmch_pfit.control = tmp;
8674         pipe_config->gmch_pfit.pgm_ratios = I915_READ(PFIT_PGM_RATIOS);
8675 }
8676
8677 static void vlv_crtc_clock_get(struct intel_crtc *crtc,
8678                                struct intel_crtc_state *pipe_config)
8679 {
8680         struct drm_device *dev = crtc->base.dev;
8681         struct drm_i915_private *dev_priv = to_i915(dev);
8682         int pipe = pipe_config->cpu_transcoder;
8683         struct dpll clock;
8684         u32 mdiv;
8685         int refclk = 100000;
8686
8687         /* In case of DSI, DPLL will not be used */
8688         if ((pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE) == 0)
8689                 return;
8690
8691         mutex_lock(&dev_priv->sb_lock);
8692         mdiv = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW3(pipe));
8693         mutex_unlock(&dev_priv->sb_lock);
8694
8695         clock.m1 = (mdiv >> DPIO_M1DIV_SHIFT) & 7;
8696         clock.m2 = mdiv & DPIO_M2DIV_MASK;
8697         clock.n = (mdiv >> DPIO_N_SHIFT) & 0xf;
8698         clock.p1 = (mdiv >> DPIO_P1_SHIFT) & 7;
8699         clock.p2 = (mdiv >> DPIO_P2_SHIFT) & 0x1f;
8700
8701         pipe_config->port_clock = vlv_calc_dpll_params(refclk, &clock);
8702 }
8703
8704 static void
8705 i9xx_get_initial_plane_config(struct intel_crtc *crtc,
8706                               struct intel_initial_plane_config *plane_config)
8707 {
8708         struct drm_device *dev = crtc->base.dev;
8709         struct drm_i915_private *dev_priv = to_i915(dev);
8710         u32 val, base, offset;
8711         int pipe = crtc->pipe, plane = crtc->plane;
8712         int fourcc, pixel_format;
8713         unsigned int aligned_height;
8714         struct drm_framebuffer *fb;
8715         struct intel_framebuffer *intel_fb;
8716
8717         val = I915_READ(DSPCNTR(plane));
8718         if (!(val & DISPLAY_PLANE_ENABLE))
8719                 return;
8720
8721         intel_fb = kzalloc(sizeof(*intel_fb), GFP_KERNEL);
8722         if (!intel_fb) {
8723                 DRM_DEBUG_KMS("failed to alloc fb\n");
8724                 return;
8725         }
8726
8727         fb = &intel_fb->base;
8728
8729         fb->dev = dev;
8730
8731         if (INTEL_GEN(dev_priv) >= 4) {
8732                 if (val & DISPPLANE_TILED) {
8733                         plane_config->tiling = I915_TILING_X;
8734                         fb->modifier = I915_FORMAT_MOD_X_TILED;
8735                 }
8736         }
8737
8738         pixel_format = val & DISPPLANE_PIXFORMAT_MASK;
8739         fourcc = i9xx_format_to_fourcc(pixel_format);
8740         fb->format = drm_format_info(fourcc);
8741
8742         if (INTEL_GEN(dev_priv) >= 4) {
8743                 if (plane_config->tiling)
8744                         offset = I915_READ(DSPTILEOFF(plane));
8745                 else
8746                         offset = I915_READ(DSPLINOFF(plane));
8747                 base = I915_READ(DSPSURF(plane)) & 0xfffff000;
8748         } else {
8749                 base = I915_READ(DSPADDR(plane));
8750         }
8751         plane_config->base = base;
8752
8753         val = I915_READ(PIPESRC(pipe));
8754         fb->width = ((val >> 16) & 0xfff) + 1;
8755         fb->height = ((val >> 0) & 0xfff) + 1;
8756
8757         val = I915_READ(DSPSTRIDE(pipe));
8758         fb->pitches[0] = val & 0xffffffc0;
8759
8760         aligned_height = intel_fb_align_height(dev, fb->height,
8761                                                fb->format->format,
8762                                                fb->modifier);
8763
8764         plane_config->size = fb->pitches[0] * aligned_height;
8765
8766         DRM_DEBUG_KMS("pipe/plane %c/%d with fb: size=%dx%d@%d, offset=%x, pitch %d, size 0x%x\n",
8767                       pipe_name(pipe), plane, fb->width, fb->height,
8768                       fb->format->cpp[0] * 8, base, fb->pitches[0],
8769                       plane_config->size);
8770
8771         plane_config->fb = intel_fb;
8772 }
8773
8774 static void chv_crtc_clock_get(struct intel_crtc *crtc,
8775                                struct intel_crtc_state *pipe_config)
8776 {
8777         struct drm_device *dev = crtc->base.dev;
8778         struct drm_i915_private *dev_priv = to_i915(dev);
8779         int pipe = pipe_config->cpu_transcoder;
8780         enum dpio_channel port = vlv_pipe_to_channel(pipe);
8781         struct dpll clock;
8782         u32 cmn_dw13, pll_dw0, pll_dw1, pll_dw2, pll_dw3;
8783         int refclk = 100000;
8784
8785         /* In case of DSI, DPLL will not be used */
8786         if ((pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE) == 0)
8787                 return;
8788
8789         mutex_lock(&dev_priv->sb_lock);
8790         cmn_dw13 = vlv_dpio_read(dev_priv, pipe, CHV_CMN_DW13(port));
8791         pll_dw0 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW0(port));
8792         pll_dw1 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW1(port));
8793         pll_dw2 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW2(port));
8794         pll_dw3 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW3(port));
8795         mutex_unlock(&dev_priv->sb_lock);
8796
8797         clock.m1 = (pll_dw1 & 0x7) == DPIO_CHV_M1_DIV_BY_2 ? 2 : 0;
8798         clock.m2 = (pll_dw0 & 0xff) << 22;
8799         if (pll_dw3 & DPIO_CHV_FRAC_DIV_EN)
8800                 clock.m2 |= pll_dw2 & 0x3fffff;
8801         clock.n = (pll_dw1 >> DPIO_CHV_N_DIV_SHIFT) & 0xf;
8802         clock.p1 = (cmn_dw13 >> DPIO_CHV_P1_DIV_SHIFT) & 0x7;
8803         clock.p2 = (cmn_dw13 >> DPIO_CHV_P2_DIV_SHIFT) & 0x1f;
8804
8805         pipe_config->port_clock = chv_calc_dpll_params(refclk, &clock);
8806 }
8807
8808 static bool i9xx_get_pipe_config(struct intel_crtc *crtc,
8809                                  struct intel_crtc_state *pipe_config)
8810 {
8811         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
8812         enum intel_display_power_domain power_domain;
8813         uint32_t tmp;
8814         bool ret;
8815
8816         power_domain = POWER_DOMAIN_PIPE(crtc->pipe);
8817         if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
8818                 return false;
8819
8820         pipe_config->cpu_transcoder = (enum transcoder) crtc->pipe;
8821         pipe_config->shared_dpll = NULL;
8822
8823         ret = false;
8824
8825         tmp = I915_READ(PIPECONF(crtc->pipe));
8826         if (!(tmp & PIPECONF_ENABLE))
8827                 goto out;
8828
8829         if (IS_G4X(dev_priv) || IS_VALLEYVIEW(dev_priv) ||
8830             IS_CHERRYVIEW(dev_priv)) {
8831                 switch (tmp & PIPECONF_BPC_MASK) {
8832                 case PIPECONF_6BPC:
8833                         pipe_config->pipe_bpp = 18;
8834                         break;
8835                 case PIPECONF_8BPC:
8836                         pipe_config->pipe_bpp = 24;
8837                         break;
8838                 case PIPECONF_10BPC:
8839                         pipe_config->pipe_bpp = 30;
8840                         break;
8841                 default:
8842                         break;
8843                 }
8844         }
8845
8846         if ((IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv)) &&
8847             (tmp & PIPECONF_COLOR_RANGE_SELECT))
8848                 pipe_config->limited_color_range = true;
8849
8850         if (INTEL_GEN(dev_priv) < 4)
8851                 pipe_config->double_wide = tmp & PIPECONF_DOUBLE_WIDE;
8852
8853         intel_get_pipe_timings(crtc, pipe_config);
8854         intel_get_pipe_src_size(crtc, pipe_config);
8855
8856         i9xx_get_pfit_config(crtc, pipe_config);
8857
8858         if (INTEL_GEN(dev_priv) >= 4) {
8859                 /* No way to read it out on pipes B and C */
8860                 if (IS_CHERRYVIEW(dev_priv) && crtc->pipe != PIPE_A)
8861                         tmp = dev_priv->chv_dpll_md[crtc->pipe];
8862                 else
8863                         tmp = I915_READ(DPLL_MD(crtc->pipe));
8864                 pipe_config->pixel_multiplier =
8865                         ((tmp & DPLL_MD_UDI_MULTIPLIER_MASK)
8866                          >> DPLL_MD_UDI_MULTIPLIER_SHIFT) + 1;
8867                 pipe_config->dpll_hw_state.dpll_md = tmp;
8868         } else if (IS_I945G(dev_priv) || IS_I945GM(dev_priv) ||
8869                    IS_G33(dev_priv) || IS_PINEVIEW(dev_priv)) {
8870                 tmp = I915_READ(DPLL(crtc->pipe));
8871                 pipe_config->pixel_multiplier =
8872                         ((tmp & SDVO_MULTIPLIER_MASK)
8873                          >> SDVO_MULTIPLIER_SHIFT_HIRES) + 1;
8874         } else {
8875                 /* Note that on i915G/GM the pixel multiplier is in the sdvo
8876                  * port and will be fixed up in the encoder->get_config
8877                  * function. */
8878                 pipe_config->pixel_multiplier = 1;
8879         }
8880         pipe_config->dpll_hw_state.dpll = I915_READ(DPLL(crtc->pipe));
8881         if (!IS_VALLEYVIEW(dev_priv) && !IS_CHERRYVIEW(dev_priv)) {
8882                 /*
8883                  * DPLL_DVO_2X_MODE must be enabled for both DPLLs
8884                  * on 830. Filter it out here so that we don't
8885                  * report errors due to that.
8886                  */
8887                 if (IS_I830(dev_priv))
8888                         pipe_config->dpll_hw_state.dpll &= ~DPLL_DVO_2X_MODE;
8889
8890                 pipe_config->dpll_hw_state.fp0 = I915_READ(FP0(crtc->pipe));
8891                 pipe_config->dpll_hw_state.fp1 = I915_READ(FP1(crtc->pipe));
8892         } else {
8893                 /* Mask out read-only status bits. */
8894                 pipe_config->dpll_hw_state.dpll &= ~(DPLL_LOCK_VLV |
8895                                                      DPLL_PORTC_READY_MASK |
8896                                                      DPLL_PORTB_READY_MASK);
8897         }
8898
8899         if (IS_CHERRYVIEW(dev_priv))
8900                 chv_crtc_clock_get(crtc, pipe_config);
8901         else if (IS_VALLEYVIEW(dev_priv))
8902                 vlv_crtc_clock_get(crtc, pipe_config);
8903         else
8904                 i9xx_crtc_clock_get(crtc, pipe_config);
8905
8906         /*
8907          * Normally the dotclock is filled in by the encoder .get_config()
8908          * but in case the pipe is enabled w/o any ports we need a sane
8909          * default.
8910          */
8911         pipe_config->base.adjusted_mode.crtc_clock =
8912                 pipe_config->port_clock / pipe_config->pixel_multiplier;
8913
8914         ret = true;
8915
8916 out:
8917         intel_display_power_put(dev_priv, power_domain);
8918
8919         return ret;
8920 }
8921
8922 static void ironlake_init_pch_refclk(struct drm_i915_private *dev_priv)
8923 {
8924         struct intel_encoder *encoder;
8925         int i;
8926         u32 val, final;
8927         bool has_lvds = false;
8928         bool has_cpu_edp = false;
8929         bool has_panel = false;
8930         bool has_ck505 = false;
8931         bool can_ssc = false;
8932         bool using_ssc_source = false;
8933
8934         /* We need to take the global config into account */
8935         for_each_intel_encoder(&dev_priv->drm, encoder) {
8936                 switch (encoder->type) {
8937                 case INTEL_OUTPUT_LVDS:
8938                         has_panel = true;
8939                         has_lvds = true;
8940                         break;
8941                 case INTEL_OUTPUT_EDP:
8942                         has_panel = true;
8943                         if (enc_to_dig_port(&encoder->base)->port == PORT_A)
8944                                 has_cpu_edp = true;
8945                         break;
8946                 default:
8947                         break;
8948                 }
8949         }
8950
8951         if (HAS_PCH_IBX(dev_priv)) {
8952                 has_ck505 = dev_priv->vbt.display_clock_mode;
8953                 can_ssc = has_ck505;
8954         } else {
8955                 has_ck505 = false;
8956                 can_ssc = true;
8957         }
8958
8959         /* Check if any DPLLs are using the SSC source */
8960         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
8961                 u32 temp = I915_READ(PCH_DPLL(i));
8962
8963                 if (!(temp & DPLL_VCO_ENABLE))
8964                         continue;
8965
8966                 if ((temp & PLL_REF_INPUT_MASK) ==
8967                     PLLB_REF_INPUT_SPREADSPECTRUMIN) {
8968                         using_ssc_source = true;
8969                         break;
8970                 }
8971         }
8972
8973         DRM_DEBUG_KMS("has_panel %d has_lvds %d has_ck505 %d using_ssc_source %d\n",
8974                       has_panel, has_lvds, has_ck505, using_ssc_source);
8975
8976         /* Ironlake: try to setup display ref clock before DPLL
8977          * enabling. This is only under driver's control after
8978          * PCH B stepping, previous chipset stepping should be
8979          * ignoring this setting.
8980          */
8981         val = I915_READ(PCH_DREF_CONTROL);
8982
8983         /* As we must carefully and slowly disable/enable each source in turn,
8984          * compute the final state we want first and check if we need to
8985          * make any changes at all.
8986          */
8987         final = val;
8988         final &= ~DREF_NONSPREAD_SOURCE_MASK;
8989         if (has_ck505)
8990                 final |= DREF_NONSPREAD_CK505_ENABLE;
8991         else
8992                 final |= DREF_NONSPREAD_SOURCE_ENABLE;
8993
8994         final &= ~DREF_SSC_SOURCE_MASK;
8995         final &= ~DREF_CPU_SOURCE_OUTPUT_MASK;
8996         final &= ~DREF_SSC1_ENABLE;
8997
8998         if (has_panel) {
8999                 final |= DREF_SSC_SOURCE_ENABLE;
9000
9001                 if (intel_panel_use_ssc(dev_priv) && can_ssc)
9002                         final |= DREF_SSC1_ENABLE;
9003
9004                 if (has_cpu_edp) {
9005                         if (intel_panel_use_ssc(dev_priv) && can_ssc)
9006                                 final |= DREF_CPU_SOURCE_OUTPUT_DOWNSPREAD;
9007                         else
9008                                 final |= DREF_CPU_SOURCE_OUTPUT_NONSPREAD;
9009                 } else
9010                         final |= DREF_CPU_SOURCE_OUTPUT_DISABLE;
9011         } else if (using_ssc_source) {
9012                 final |= DREF_SSC_SOURCE_ENABLE;
9013                 final |= DREF_SSC1_ENABLE;
9014         }
9015
9016         if (final == val)
9017                 return;
9018
9019         /* Always enable nonspread source */
9020         val &= ~DREF_NONSPREAD_SOURCE_MASK;
9021
9022         if (has_ck505)
9023                 val |= DREF_NONSPREAD_CK505_ENABLE;
9024         else
9025                 val |= DREF_NONSPREAD_SOURCE_ENABLE;
9026
9027         if (has_panel) {
9028                 val &= ~DREF_SSC_SOURCE_MASK;
9029                 val |= DREF_SSC_SOURCE_ENABLE;
9030
9031                 /* SSC must be turned on before enabling the CPU output  */
9032                 if (intel_panel_use_ssc(dev_priv) && can_ssc) {
9033                         DRM_DEBUG_KMS("Using SSC on panel\n");
9034                         val |= DREF_SSC1_ENABLE;
9035                 } else
9036                         val &= ~DREF_SSC1_ENABLE;
9037
9038                 /* Get SSC going before enabling the outputs */
9039                 I915_WRITE(PCH_DREF_CONTROL, val);
9040                 POSTING_READ(PCH_DREF_CONTROL);
9041                 udelay(200);
9042
9043                 val &= ~DREF_CPU_SOURCE_OUTPUT_MASK;
9044
9045                 /* Enable CPU source on CPU attached eDP */
9046                 if (has_cpu_edp) {
9047                         if (intel_panel_use_ssc(dev_priv) && can_ssc) {
9048                                 DRM_DEBUG_KMS("Using SSC on eDP\n");
9049                                 val |= DREF_CPU_SOURCE_OUTPUT_DOWNSPREAD;
9050                         } else
9051                                 val |= DREF_CPU_SOURCE_OUTPUT_NONSPREAD;
9052                 } else
9053                         val |= DREF_CPU_SOURCE_OUTPUT_DISABLE;
9054
9055                 I915_WRITE(PCH_DREF_CONTROL, val);
9056                 POSTING_READ(PCH_DREF_CONTROL);
9057                 udelay(200);
9058         } else {
9059                 DRM_DEBUG_KMS("Disabling CPU source output\n");
9060
9061                 val &= ~DREF_CPU_SOURCE_OUTPUT_MASK;
9062
9063                 /* Turn off CPU output */
9064                 val |= DREF_CPU_SOURCE_OUTPUT_DISABLE;
9065
9066                 I915_WRITE(PCH_DREF_CONTROL, val);
9067                 POSTING_READ(PCH_DREF_CONTROL);
9068                 udelay(200);
9069
9070                 if (!using_ssc_source) {
9071                         DRM_DEBUG_KMS("Disabling SSC source\n");
9072
9073                         /* Turn off the SSC source */
9074                         val &= ~DREF_SSC_SOURCE_MASK;
9075                         val |= DREF_SSC_SOURCE_DISABLE;
9076
9077                         /* Turn off SSC1 */
9078                         val &= ~DREF_SSC1_ENABLE;
9079
9080                         I915_WRITE(PCH_DREF_CONTROL, val);
9081                         POSTING_READ(PCH_DREF_CONTROL);
9082                         udelay(200);
9083                 }
9084         }
9085
9086         BUG_ON(val != final);
9087 }
9088
9089 static void lpt_reset_fdi_mphy(struct drm_i915_private *dev_priv)
9090 {
9091         uint32_t tmp;
9092
9093         tmp = I915_READ(SOUTH_CHICKEN2);
9094         tmp |= FDI_MPHY_IOSFSB_RESET_CTL;
9095         I915_WRITE(SOUTH_CHICKEN2, tmp);
9096
9097         if (wait_for_us(I915_READ(SOUTH_CHICKEN2) &
9098                         FDI_MPHY_IOSFSB_RESET_STATUS, 100))
9099                 DRM_ERROR("FDI mPHY reset assert timeout\n");
9100
9101         tmp = I915_READ(SOUTH_CHICKEN2);
9102         tmp &= ~FDI_MPHY_IOSFSB_RESET_CTL;
9103         I915_WRITE(SOUTH_CHICKEN2, tmp);
9104
9105         if (wait_for_us((I915_READ(SOUTH_CHICKEN2) &
9106                          FDI_MPHY_IOSFSB_RESET_STATUS) == 0, 100))
9107                 DRM_ERROR("FDI mPHY reset de-assert timeout\n");
9108 }
9109
9110 /* WaMPhyProgramming:hsw */
9111 static void lpt_program_fdi_mphy(struct drm_i915_private *dev_priv)
9112 {
9113         uint32_t tmp;
9114
9115         tmp = intel_sbi_read(dev_priv, 0x8008, SBI_MPHY);
9116         tmp &= ~(0xFF << 24);
9117         tmp |= (0x12 << 24);
9118         intel_sbi_write(dev_priv, 0x8008, tmp, SBI_MPHY);
9119
9120         tmp = intel_sbi_read(dev_priv, 0x2008, SBI_MPHY);
9121         tmp |= (1 << 11);
9122         intel_sbi_write(dev_priv, 0x2008, tmp, SBI_MPHY);
9123
9124         tmp = intel_sbi_read(dev_priv, 0x2108, SBI_MPHY);
9125         tmp |= (1 << 11);
9126         intel_sbi_write(dev_priv, 0x2108, tmp, SBI_MPHY);
9127
9128         tmp = intel_sbi_read(dev_priv, 0x206C, SBI_MPHY);
9129         tmp |= (1 << 24) | (1 << 21) | (1 << 18);
9130         intel_sbi_write(dev_priv, 0x206C, tmp, SBI_MPHY);
9131
9132         tmp = intel_sbi_read(dev_priv, 0x216C, SBI_MPHY);
9133         tmp |= (1 << 24) | (1 << 21) | (1 << 18);
9134         intel_sbi_write(dev_priv, 0x216C, tmp, SBI_MPHY);
9135
9136         tmp = intel_sbi_read(dev_priv, 0x2080, SBI_MPHY);
9137         tmp &= ~(7 << 13);
9138         tmp |= (5 << 13);
9139         intel_sbi_write(dev_priv, 0x2080, tmp, SBI_MPHY);
9140
9141         tmp = intel_sbi_read(dev_priv, 0x2180, SBI_MPHY);
9142         tmp &= ~(7 << 13);
9143         tmp |= (5 << 13);
9144         intel_sbi_write(dev_priv, 0x2180, tmp, SBI_MPHY);
9145
9146         tmp = intel_sbi_read(dev_priv, 0x208C, SBI_MPHY);
9147         tmp &= ~0xFF;
9148         tmp |= 0x1C;
9149         intel_sbi_write(dev_priv, 0x208C, tmp, SBI_MPHY);
9150
9151         tmp = intel_sbi_read(dev_priv, 0x218C, SBI_MPHY);
9152         tmp &= ~0xFF;
9153         tmp |= 0x1C;
9154         intel_sbi_write(dev_priv, 0x218C, tmp, SBI_MPHY);
9155
9156         tmp = intel_sbi_read(dev_priv, 0x2098, SBI_MPHY);
9157         tmp &= ~(0xFF << 16);
9158         tmp |= (0x1C << 16);
9159         intel_sbi_write(dev_priv, 0x2098, tmp, SBI_MPHY);
9160
9161         tmp = intel_sbi_read(dev_priv, 0x2198, SBI_MPHY);
9162         tmp &= ~(0xFF << 16);
9163         tmp |= (0x1C << 16);
9164         intel_sbi_write(dev_priv, 0x2198, tmp, SBI_MPHY);
9165
9166         tmp = intel_sbi_read(dev_priv, 0x20C4, SBI_MPHY);
9167         tmp |= (1 << 27);
9168         intel_sbi_write(dev_priv, 0x20C4, tmp, SBI_MPHY);
9169
9170         tmp = intel_sbi_read(dev_priv, 0x21C4, SBI_MPHY);
9171         tmp |= (1 << 27);
9172         intel_sbi_write(dev_priv, 0x21C4, tmp, SBI_MPHY);
9173
9174         tmp = intel_sbi_read(dev_priv, 0x20EC, SBI_MPHY);
9175         tmp &= ~(0xF << 28);
9176         tmp |= (4 << 28);
9177         intel_sbi_write(dev_priv, 0x20EC, tmp, SBI_MPHY);
9178
9179         tmp = intel_sbi_read(dev_priv, 0x21EC, SBI_MPHY);
9180         tmp &= ~(0xF << 28);
9181         tmp |= (4 << 28);
9182         intel_sbi_write(dev_priv, 0x21EC, tmp, SBI_MPHY);
9183 }
9184
9185 /* Implements 3 different sequences from BSpec chapter "Display iCLK
9186  * Programming" based on the parameters passed:
9187  * - Sequence to enable CLKOUT_DP
9188  * - Sequence to enable CLKOUT_DP without spread
9189  * - Sequence to enable CLKOUT_DP for FDI usage and configure PCH FDI I/O
9190  */
9191 static void lpt_enable_clkout_dp(struct drm_i915_private *dev_priv,
9192                                  bool with_spread, bool with_fdi)
9193 {
9194         uint32_t reg, tmp;
9195
9196         if (WARN(with_fdi && !with_spread, "FDI requires downspread\n"))
9197                 with_spread = true;
9198         if (WARN(HAS_PCH_LPT_LP(dev_priv) &&
9199             with_fdi, "LP PCH doesn't have FDI\n"))
9200                 with_fdi = false;
9201
9202         mutex_lock(&dev_priv->sb_lock);
9203
9204         tmp = intel_sbi_read(dev_priv, SBI_SSCCTL, SBI_ICLK);
9205         tmp &= ~SBI_SSCCTL_DISABLE;
9206         tmp |= SBI_SSCCTL_PATHALT;
9207         intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
9208
9209         udelay(24);
9210
9211         if (with_spread) {
9212                 tmp = intel_sbi_read(dev_priv, SBI_SSCCTL, SBI_ICLK);
9213                 tmp &= ~SBI_SSCCTL_PATHALT;
9214                 intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
9215
9216                 if (with_fdi) {
9217                         lpt_reset_fdi_mphy(dev_priv);
9218                         lpt_program_fdi_mphy(dev_priv);
9219                 }
9220         }
9221
9222         reg = HAS_PCH_LPT_LP(dev_priv) ? SBI_GEN0 : SBI_DBUFF0;
9223         tmp = intel_sbi_read(dev_priv, reg, SBI_ICLK);
9224         tmp |= SBI_GEN0_CFG_BUFFENABLE_DISABLE;
9225         intel_sbi_write(dev_priv, reg, tmp, SBI_ICLK);
9226
9227         mutex_unlock(&dev_priv->sb_lock);
9228 }
9229
9230 /* Sequence to disable CLKOUT_DP */
9231 static void lpt_disable_clkout_dp(struct drm_i915_private *dev_priv)
9232 {
9233         uint32_t reg, tmp;
9234
9235         mutex_lock(&dev_priv->sb_lock);
9236
9237         reg = HAS_PCH_LPT_LP(dev_priv) ? SBI_GEN0 : SBI_DBUFF0;
9238         tmp = intel_sbi_read(dev_priv, reg, SBI_ICLK);
9239         tmp &= ~SBI_GEN0_CFG_BUFFENABLE_DISABLE;
9240         intel_sbi_write(dev_priv, reg, tmp, SBI_ICLK);
9241
9242         tmp = intel_sbi_read(dev_priv, SBI_SSCCTL, SBI_ICLK);
9243         if (!(tmp & SBI_SSCCTL_DISABLE)) {
9244                 if (!(tmp & SBI_SSCCTL_PATHALT)) {
9245                         tmp |= SBI_SSCCTL_PATHALT;
9246                         intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
9247                         udelay(32);
9248                 }
9249                 tmp |= SBI_SSCCTL_DISABLE;
9250                 intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
9251         }
9252
9253         mutex_unlock(&dev_priv->sb_lock);
9254 }
9255
9256 #define BEND_IDX(steps) ((50 + (steps)) / 5)
9257
9258 static const uint16_t sscdivintphase[] = {
9259         [BEND_IDX( 50)] = 0x3B23,
9260         [BEND_IDX( 45)] = 0x3B23,
9261         [BEND_IDX( 40)] = 0x3C23,
9262         [BEND_IDX( 35)] = 0x3C23,
9263         [BEND_IDX( 30)] = 0x3D23,
9264         [BEND_IDX( 25)] = 0x3D23,
9265         [BEND_IDX( 20)] = 0x3E23,
9266         [BEND_IDX( 15)] = 0x3E23,
9267         [BEND_IDX( 10)] = 0x3F23,
9268         [BEND_IDX(  5)] = 0x3F23,
9269         [BEND_IDX(  0)] = 0x0025,
9270         [BEND_IDX( -5)] = 0x0025,
9271         [BEND_IDX(-10)] = 0x0125,
9272         [BEND_IDX(-15)] = 0x0125,
9273         [BEND_IDX(-20)] = 0x0225,
9274         [BEND_IDX(-25)] = 0x0225,
9275         [BEND_IDX(-30)] = 0x0325,
9276         [BEND_IDX(-35)] = 0x0325,
9277         [BEND_IDX(-40)] = 0x0425,
9278         [BEND_IDX(-45)] = 0x0425,
9279         [BEND_IDX(-50)] = 0x0525,
9280 };
9281
9282 /*
9283  * Bend CLKOUT_DP
9284  * steps -50 to 50 inclusive, in steps of 5
9285  * < 0 slow down the clock, > 0 speed up the clock, 0 == no bend (135MHz)
9286  * change in clock period = -(steps / 10) * 5.787 ps
9287  */
9288 static void lpt_bend_clkout_dp(struct drm_i915_private *dev_priv, int steps)
9289 {
9290         uint32_t tmp;
9291         int idx = BEND_IDX(steps);
9292
9293         if (WARN_ON(steps % 5 != 0))
9294                 return;
9295
9296         if (WARN_ON(idx >= ARRAY_SIZE(sscdivintphase)))
9297                 return;
9298
9299         mutex_lock(&dev_priv->sb_lock);
9300
9301         if (steps % 10 != 0)
9302                 tmp = 0xAAAAAAAB;
9303         else
9304                 tmp = 0x00000000;
9305         intel_sbi_write(dev_priv, SBI_SSCDITHPHASE, tmp, SBI_ICLK);
9306
9307         tmp = intel_sbi_read(dev_priv, SBI_SSCDIVINTPHASE, SBI_ICLK);
9308         tmp &= 0xffff0000;
9309         tmp |= sscdivintphase[idx];
9310         intel_sbi_write(dev_priv, SBI_SSCDIVINTPHASE, tmp, SBI_ICLK);
9311
9312         mutex_unlock(&dev_priv->sb_lock);
9313 }
9314
9315 #undef BEND_IDX
9316
9317 static void lpt_init_pch_refclk(struct drm_i915_private *dev_priv)
9318 {
9319         struct intel_encoder *encoder;
9320         bool has_vga = false;
9321
9322         for_each_intel_encoder(&dev_priv->drm, encoder) {
9323                 switch (encoder->type) {
9324                 case INTEL_OUTPUT_ANALOG:
9325                         has_vga = true;
9326                         break;
9327                 default:
9328                         break;
9329                 }
9330         }
9331
9332         if (has_vga) {
9333                 lpt_bend_clkout_dp(dev_priv, 0);
9334                 lpt_enable_clkout_dp(dev_priv, true, true);
9335         } else {
9336                 lpt_disable_clkout_dp(dev_priv);
9337         }
9338 }
9339
9340 /*
9341  * Initialize reference clocks when the driver loads
9342  */
9343 void intel_init_pch_refclk(struct drm_i915_private *dev_priv)
9344 {
9345         if (HAS_PCH_IBX(dev_priv) || HAS_PCH_CPT(dev_priv))
9346                 ironlake_init_pch_refclk(dev_priv);
9347         else if (HAS_PCH_LPT(dev_priv))
9348                 lpt_init_pch_refclk(dev_priv);
9349 }
9350
9351 static void ironlake_set_pipeconf(struct drm_crtc *crtc)
9352 {
9353         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
9354         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
9355         int pipe = intel_crtc->pipe;
9356         uint32_t val;
9357
9358         val = 0;
9359
9360         switch (intel_crtc->config->pipe_bpp) {
9361         case 18:
9362                 val |= PIPECONF_6BPC;
9363                 break;
9364         case 24:
9365                 val |= PIPECONF_8BPC;
9366                 break;
9367         case 30:
9368                 val |= PIPECONF_10BPC;
9369                 break;
9370         case 36:
9371                 val |= PIPECONF_12BPC;
9372                 break;
9373         default:
9374                 /* Case prevented by intel_choose_pipe_bpp_dither. */
9375                 BUG();
9376         }
9377
9378         if (intel_crtc->config->dither)
9379                 val |= (PIPECONF_DITHER_EN | PIPECONF_DITHER_TYPE_SP);
9380
9381         if (intel_crtc->config->base.adjusted_mode.flags & DRM_MODE_FLAG_INTERLACE)
9382                 val |= PIPECONF_INTERLACED_ILK;
9383         else
9384                 val |= PIPECONF_PROGRESSIVE;
9385
9386         if (intel_crtc->config->limited_color_range)
9387                 val |= PIPECONF_COLOR_RANGE_SELECT;
9388
9389         I915_WRITE(PIPECONF(pipe), val);
9390         POSTING_READ(PIPECONF(pipe));
9391 }
9392
9393 static void haswell_set_pipeconf(struct drm_crtc *crtc)
9394 {
9395         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
9396         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
9397         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
9398         u32 val = 0;
9399
9400         if (IS_HASWELL(dev_priv) && intel_crtc->config->dither)
9401                 val |= (PIPECONF_DITHER_EN | PIPECONF_DITHER_TYPE_SP);
9402
9403         if (intel_crtc->config->base.adjusted_mode.flags & DRM_MODE_FLAG_INTERLACE)
9404                 val |= PIPECONF_INTERLACED_ILK;
9405         else
9406                 val |= PIPECONF_PROGRESSIVE;
9407
9408         I915_WRITE(PIPECONF(cpu_transcoder), val);
9409         POSTING_READ(PIPECONF(cpu_transcoder));
9410 }
9411
9412 static void haswell_set_pipemisc(struct drm_crtc *crtc)
9413 {
9414         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
9415         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
9416
9417         if (IS_BROADWELL(dev_priv) || INTEL_INFO(dev_priv)->gen >= 9) {
9418                 u32 val = 0;
9419
9420                 switch (intel_crtc->config->pipe_bpp) {
9421                 case 18:
9422                         val |= PIPEMISC_DITHER_6_BPC;
9423                         break;
9424                 case 24:
9425                         val |= PIPEMISC_DITHER_8_BPC;
9426                         break;
9427                 case 30:
9428                         val |= PIPEMISC_DITHER_10_BPC;
9429                         break;
9430                 case 36:
9431                         val |= PIPEMISC_DITHER_12_BPC;
9432                         break;
9433                 default:
9434                         /* Case prevented by pipe_config_set_bpp. */
9435                         BUG();
9436                 }
9437
9438                 if (intel_crtc->config->dither)
9439                         val |= PIPEMISC_DITHER_ENABLE | PIPEMISC_DITHER_TYPE_SP;
9440
9441                 I915_WRITE(PIPEMISC(intel_crtc->pipe), val);
9442         }
9443 }
9444
9445 int ironlake_get_lanes_required(int target_clock, int link_bw, int bpp)
9446 {
9447         /*
9448          * Account for spread spectrum to avoid
9449          * oversubscribing the link. Max center spread
9450          * is 2.5%; use 5% for safety's sake.
9451          */
9452         u32 bps = target_clock * bpp * 21 / 20;
9453         return DIV_ROUND_UP(bps, link_bw * 8);
9454 }
9455
9456 static bool ironlake_needs_fb_cb_tune(struct dpll *dpll, int factor)
9457 {
9458         return i9xx_dpll_compute_m(dpll) < factor * dpll->n;
9459 }
9460
9461 static void ironlake_compute_dpll(struct intel_crtc *intel_crtc,
9462                                   struct intel_crtc_state *crtc_state,
9463                                   struct dpll *reduced_clock)
9464 {
9465         struct drm_crtc *crtc = &intel_crtc->base;
9466         struct drm_device *dev = crtc->dev;
9467         struct drm_i915_private *dev_priv = to_i915(dev);
9468         u32 dpll, fp, fp2;
9469         int factor;
9470
9471         /* Enable autotuning of the PLL clock (if permissible) */
9472         factor = 21;
9473         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
9474                 if ((intel_panel_use_ssc(dev_priv) &&
9475                      dev_priv->vbt.lvds_ssc_freq == 100000) ||
9476                     (HAS_PCH_IBX(dev_priv) && intel_is_dual_link_lvds(dev)))
9477                         factor = 25;
9478         } else if (crtc_state->sdvo_tv_clock)
9479                 factor = 20;
9480
9481         fp = i9xx_dpll_compute_fp(&crtc_state->dpll);
9482
9483         if (ironlake_needs_fb_cb_tune(&crtc_state->dpll, factor))
9484                 fp |= FP_CB_TUNE;
9485
9486         if (reduced_clock) {
9487                 fp2 = i9xx_dpll_compute_fp(reduced_clock);
9488
9489                 if (reduced_clock->m < factor * reduced_clock->n)
9490                         fp2 |= FP_CB_TUNE;
9491         } else {
9492                 fp2 = fp;
9493         }
9494
9495         dpll = 0;
9496
9497         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS))
9498                 dpll |= DPLLB_MODE_LVDS;
9499         else
9500                 dpll |= DPLLB_MODE_DAC_SERIAL;
9501
9502         dpll |= (crtc_state->pixel_multiplier - 1)
9503                 << PLL_REF_SDVO_HDMI_MULTIPLIER_SHIFT;
9504
9505         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_SDVO) ||
9506             intel_crtc_has_type(crtc_state, INTEL_OUTPUT_HDMI))
9507                 dpll |= DPLL_SDVO_HIGH_SPEED;
9508
9509         if (intel_crtc_has_dp_encoder(crtc_state))
9510                 dpll |= DPLL_SDVO_HIGH_SPEED;
9511
9512         /*
9513          * The high speed IO clock is only really required for
9514          * SDVO/HDMI/DP, but we also enable it for CRT to make it
9515          * possible to share the DPLL between CRT and HDMI. Enabling
9516          * the clock needlessly does no real harm, except use up a
9517          * bit of power potentially.
9518          *
9519          * We'll limit this to IVB with 3 pipes, since it has only two
9520          * DPLLs and so DPLL sharing is the only way to get three pipes
9521          * driving PCH ports at the same time. On SNB we could do this,
9522          * and potentially avoid enabling the second DPLL, but it's not
9523          * clear if it''s a win or loss power wise. No point in doing
9524          * this on ILK at all since it has a fixed DPLL<->pipe mapping.
9525          */
9526         if (INTEL_INFO(dev_priv)->num_pipes == 3 &&
9527             intel_crtc_has_type(crtc_state, INTEL_OUTPUT_ANALOG))
9528                 dpll |= DPLL_SDVO_HIGH_SPEED;
9529
9530         /* compute bitmask from p1 value */
9531         dpll |= (1 << (crtc_state->dpll.p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT;
9532         /* also FPA1 */
9533         dpll |= (1 << (crtc_state->dpll.p1 - 1)) << DPLL_FPA1_P1_POST_DIV_SHIFT;
9534
9535         switch (crtc_state->dpll.p2) {
9536         case 5:
9537                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_5;
9538                 break;
9539         case 7:
9540                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_7;
9541                 break;
9542         case 10:
9543                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_10;
9544                 break;
9545         case 14:
9546                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_14;
9547                 break;
9548         }
9549
9550         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS) &&
9551             intel_panel_use_ssc(dev_priv))
9552                 dpll |= PLLB_REF_INPUT_SPREADSPECTRUMIN;
9553         else
9554                 dpll |= PLL_REF_INPUT_DREFCLK;
9555
9556         dpll |= DPLL_VCO_ENABLE;
9557
9558         crtc_state->dpll_hw_state.dpll = dpll;
9559         crtc_state->dpll_hw_state.fp0 = fp;
9560         crtc_state->dpll_hw_state.fp1 = fp2;
9561 }
9562
9563 static int ironlake_crtc_compute_clock(struct intel_crtc *crtc,
9564                                        struct intel_crtc_state *crtc_state)
9565 {
9566         struct drm_device *dev = crtc->base.dev;
9567         struct drm_i915_private *dev_priv = to_i915(dev);
9568         struct dpll reduced_clock;
9569         bool has_reduced_clock = false;
9570         struct intel_shared_dpll *pll;
9571         const struct intel_limit *limit;
9572         int refclk = 120000;
9573
9574         memset(&crtc_state->dpll_hw_state, 0,
9575                sizeof(crtc_state->dpll_hw_state));
9576
9577         crtc->lowfreq_avail = false;
9578
9579         /* CPU eDP is the only output that doesn't need a PCH PLL of its own. */
9580         if (!crtc_state->has_pch_encoder)
9581                 return 0;
9582
9583         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
9584                 if (intel_panel_use_ssc(dev_priv)) {
9585                         DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n",
9586                                       dev_priv->vbt.lvds_ssc_freq);
9587                         refclk = dev_priv->vbt.lvds_ssc_freq;
9588                 }
9589
9590                 if (intel_is_dual_link_lvds(dev)) {
9591                         if (refclk == 100000)
9592                                 limit = &intel_limits_ironlake_dual_lvds_100m;
9593                         else
9594                                 limit = &intel_limits_ironlake_dual_lvds;
9595                 } else {
9596                         if (refclk == 100000)
9597                                 limit = &intel_limits_ironlake_single_lvds_100m;
9598                         else
9599                                 limit = &intel_limits_ironlake_single_lvds;
9600                 }
9601         } else {
9602                 limit = &intel_limits_ironlake_dac;
9603         }
9604
9605         if (!crtc_state->clock_set &&
9606             !g4x_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
9607                                 refclk, NULL, &crtc_state->dpll)) {
9608                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
9609                 return -EINVAL;
9610         }
9611
9612         ironlake_compute_dpll(crtc, crtc_state,
9613                               has_reduced_clock ? &reduced_clock : NULL);
9614
9615         pll = intel_get_shared_dpll(crtc, crtc_state, NULL);
9616         if (pll == NULL) {
9617                 DRM_DEBUG_DRIVER("failed to find PLL for pipe %c\n",
9618                                  pipe_name(crtc->pipe));
9619                 return -EINVAL;
9620         }
9621
9622         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS) &&
9623             has_reduced_clock)
9624                 crtc->lowfreq_avail = true;
9625
9626         return 0;
9627 }
9628
9629 static void intel_pch_transcoder_get_m_n(struct intel_crtc *crtc,
9630                                          struct intel_link_m_n *m_n)
9631 {
9632         struct drm_device *dev = crtc->base.dev;
9633         struct drm_i915_private *dev_priv = to_i915(dev);
9634         enum pipe pipe = crtc->pipe;
9635
9636         m_n->link_m = I915_READ(PCH_TRANS_LINK_M1(pipe));
9637         m_n->link_n = I915_READ(PCH_TRANS_LINK_N1(pipe));
9638         m_n->gmch_m = I915_READ(PCH_TRANS_DATA_M1(pipe))
9639                 & ~TU_SIZE_MASK;
9640         m_n->gmch_n = I915_READ(PCH_TRANS_DATA_N1(pipe));
9641         m_n->tu = ((I915_READ(PCH_TRANS_DATA_M1(pipe))
9642                     & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
9643 }
9644
9645 static void intel_cpu_transcoder_get_m_n(struct intel_crtc *crtc,
9646                                          enum transcoder transcoder,
9647                                          struct intel_link_m_n *m_n,
9648                                          struct intel_link_m_n *m2_n2)
9649 {
9650         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
9651         enum pipe pipe = crtc->pipe;
9652
9653         if (INTEL_GEN(dev_priv) >= 5) {
9654                 m_n->link_m = I915_READ(PIPE_LINK_M1(transcoder));
9655                 m_n->link_n = I915_READ(PIPE_LINK_N1(transcoder));
9656                 m_n->gmch_m = I915_READ(PIPE_DATA_M1(transcoder))
9657                         & ~TU_SIZE_MASK;
9658                 m_n->gmch_n = I915_READ(PIPE_DATA_N1(transcoder));
9659                 m_n->tu = ((I915_READ(PIPE_DATA_M1(transcoder))
9660                             & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
9661                 /* Read M2_N2 registers only for gen < 8 (M2_N2 available for
9662                  * gen < 8) and if DRRS is supported (to make sure the
9663                  * registers are not unnecessarily read).
9664                  */
9665                 if (m2_n2 && INTEL_GEN(dev_priv) < 8 &&
9666                         crtc->config->has_drrs) {
9667                         m2_n2->link_m = I915_READ(PIPE_LINK_M2(transcoder));
9668                         m2_n2->link_n = I915_READ(PIPE_LINK_N2(transcoder));
9669                         m2_n2->gmch_m = I915_READ(PIPE_DATA_M2(transcoder))
9670                                         & ~TU_SIZE_MASK;
9671                         m2_n2->gmch_n = I915_READ(PIPE_DATA_N2(transcoder));
9672                         m2_n2->tu = ((I915_READ(PIPE_DATA_M2(transcoder))
9673                                         & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
9674                 }
9675         } else {
9676                 m_n->link_m = I915_READ(PIPE_LINK_M_G4X(pipe));
9677                 m_n->link_n = I915_READ(PIPE_LINK_N_G4X(pipe));
9678                 m_n->gmch_m = I915_READ(PIPE_DATA_M_G4X(pipe))
9679                         & ~TU_SIZE_MASK;
9680                 m_n->gmch_n = I915_READ(PIPE_DATA_N_G4X(pipe));
9681                 m_n->tu = ((I915_READ(PIPE_DATA_M_G4X(pipe))
9682                             & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
9683         }
9684 }
9685
9686 void intel_dp_get_m_n(struct intel_crtc *crtc,
9687                       struct intel_crtc_state *pipe_config)
9688 {
9689         if (pipe_config->has_pch_encoder)
9690                 intel_pch_transcoder_get_m_n(crtc, &pipe_config->dp_m_n);
9691         else
9692                 intel_cpu_transcoder_get_m_n(crtc, pipe_config->cpu_transcoder,
9693                                              &pipe_config->dp_m_n,
9694                                              &pipe_config->dp_m2_n2);
9695 }
9696
9697 static void ironlake_get_fdi_m_n_config(struct intel_crtc *crtc,
9698                                         struct intel_crtc_state *pipe_config)
9699 {
9700         intel_cpu_transcoder_get_m_n(crtc, pipe_config->cpu_transcoder,
9701                                      &pipe_config->fdi_m_n, NULL);
9702 }
9703
9704 static void skylake_get_pfit_config(struct intel_crtc *crtc,
9705                                     struct intel_crtc_state *pipe_config)
9706 {
9707         struct drm_device *dev = crtc->base.dev;
9708         struct drm_i915_private *dev_priv = to_i915(dev);
9709         struct intel_crtc_scaler_state *scaler_state = &pipe_config->scaler_state;
9710         uint32_t ps_ctrl = 0;
9711         int id = -1;
9712         int i;
9713
9714         /* find scaler attached to this pipe */
9715         for (i = 0; i < crtc->num_scalers; i++) {
9716                 ps_ctrl = I915_READ(SKL_PS_CTRL(crtc->pipe, i));
9717                 if (ps_ctrl & PS_SCALER_EN && !(ps_ctrl & PS_PLANE_SEL_MASK)) {
9718                         id = i;
9719                         pipe_config->pch_pfit.enabled = true;
9720                         pipe_config->pch_pfit.pos = I915_READ(SKL_PS_WIN_POS(crtc->pipe, i));
9721                         pipe_config->pch_pfit.size = I915_READ(SKL_PS_WIN_SZ(crtc->pipe, i));
9722                         break;
9723                 }
9724         }
9725
9726         scaler_state->scaler_id = id;
9727         if (id >= 0) {
9728                 scaler_state->scaler_users |= (1 << SKL_CRTC_INDEX);
9729         } else {
9730                 scaler_state->scaler_users &= ~(1 << SKL_CRTC_INDEX);
9731         }
9732 }
9733
9734 static void
9735 skylake_get_initial_plane_config(struct intel_crtc *crtc,
9736                                  struct intel_initial_plane_config *plane_config)
9737 {
9738         struct drm_device *dev = crtc->base.dev;
9739         struct drm_i915_private *dev_priv = to_i915(dev);
9740         u32 val, base, offset, stride_mult, tiling;
9741         int pipe = crtc->pipe;
9742         int fourcc, pixel_format;
9743         unsigned int aligned_height;
9744         struct drm_framebuffer *fb;
9745         struct intel_framebuffer *intel_fb;
9746
9747         intel_fb = kzalloc(sizeof(*intel_fb), GFP_KERNEL);
9748         if (!intel_fb) {
9749                 DRM_DEBUG_KMS("failed to alloc fb\n");
9750                 return;
9751         }
9752
9753         fb = &intel_fb->base;
9754
9755         fb->dev = dev;
9756
9757         val = I915_READ(PLANE_CTL(pipe, 0));
9758         if (!(val & PLANE_CTL_ENABLE))
9759                 goto error;
9760
9761         pixel_format = val & PLANE_CTL_FORMAT_MASK;
9762         fourcc = skl_format_to_fourcc(pixel_format,
9763                                       val & PLANE_CTL_ORDER_RGBX,
9764                                       val & PLANE_CTL_ALPHA_MASK);
9765         fb->format = drm_format_info(fourcc);
9766
9767         tiling = val & PLANE_CTL_TILED_MASK;
9768         switch (tiling) {
9769         case PLANE_CTL_TILED_LINEAR:
9770                 fb->modifier = DRM_FORMAT_MOD_NONE;
9771                 break;
9772         case PLANE_CTL_TILED_X:
9773                 plane_config->tiling = I915_TILING_X;
9774                 fb->modifier = I915_FORMAT_MOD_X_TILED;
9775                 break;
9776         case PLANE_CTL_TILED_Y:
9777                 fb->modifier = I915_FORMAT_MOD_Y_TILED;
9778                 break;
9779         case PLANE_CTL_TILED_YF:
9780                 fb->modifier = I915_FORMAT_MOD_Yf_TILED;
9781                 break;
9782         default:
9783                 MISSING_CASE(tiling);
9784                 goto error;
9785         }
9786
9787         base = I915_READ(PLANE_SURF(pipe, 0)) & 0xfffff000;
9788         plane_config->base = base;
9789
9790         offset = I915_READ(PLANE_OFFSET(pipe, 0));
9791
9792         val = I915_READ(PLANE_SIZE(pipe, 0));
9793         fb->height = ((val >> 16) & 0xfff) + 1;
9794         fb->width = ((val >> 0) & 0x1fff) + 1;
9795
9796         val = I915_READ(PLANE_STRIDE(pipe, 0));
9797         stride_mult = intel_fb_stride_alignment(dev_priv, fb->modifier,
9798                                                 fb->format->format);
9799         fb->pitches[0] = (val & 0x3ff) * stride_mult;
9800
9801         aligned_height = intel_fb_align_height(dev, fb->height,
9802                                                fb->format->format,
9803                                                fb->modifier);
9804
9805         plane_config->size = fb->pitches[0] * aligned_height;
9806
9807         DRM_DEBUG_KMS("pipe %c with fb: size=%dx%d@%d, offset=%x, pitch %d, size 0x%x\n",
9808                       pipe_name(pipe), fb->width, fb->height,
9809                       fb->format->cpp[0] * 8, base, fb->pitches[0],
9810                       plane_config->size);
9811
9812         plane_config->fb = intel_fb;
9813         return;
9814
9815 error:
9816         kfree(intel_fb);
9817 }
9818
9819 static void ironlake_get_pfit_config(struct intel_crtc *crtc,
9820                                      struct intel_crtc_state *pipe_config)
9821 {
9822         struct drm_device *dev = crtc->base.dev;
9823         struct drm_i915_private *dev_priv = to_i915(dev);
9824         uint32_t tmp;
9825
9826         tmp = I915_READ(PF_CTL(crtc->pipe));
9827
9828         if (tmp & PF_ENABLE) {
9829                 pipe_config->pch_pfit.enabled = true;
9830                 pipe_config->pch_pfit.pos = I915_READ(PF_WIN_POS(crtc->pipe));
9831                 pipe_config->pch_pfit.size = I915_READ(PF_WIN_SZ(crtc->pipe));
9832
9833                 /* We currently do not free assignements of panel fitters on
9834                  * ivb/hsw (since we don't use the higher upscaling modes which
9835                  * differentiates them) so just WARN about this case for now. */
9836                 if (IS_GEN7(dev_priv)) {
9837                         WARN_ON((tmp & PF_PIPE_SEL_MASK_IVB) !=
9838                                 PF_PIPE_SEL_IVB(crtc->pipe));
9839                 }
9840         }
9841 }
9842
9843 static void
9844 ironlake_get_initial_plane_config(struct intel_crtc *crtc,
9845                                   struct intel_initial_plane_config *plane_config)
9846 {
9847         struct drm_device *dev = crtc->base.dev;
9848         struct drm_i915_private *dev_priv = to_i915(dev);
9849         u32 val, base, offset;
9850         int pipe = crtc->pipe;
9851         int fourcc, pixel_format;
9852         unsigned int aligned_height;
9853         struct drm_framebuffer *fb;
9854         struct intel_framebuffer *intel_fb;
9855
9856         val = I915_READ(DSPCNTR(pipe));
9857         if (!(val & DISPLAY_PLANE_ENABLE))
9858                 return;
9859
9860         intel_fb = kzalloc(sizeof(*intel_fb), GFP_KERNEL);
9861         if (!intel_fb) {
9862                 DRM_DEBUG_KMS("failed to alloc fb\n");
9863                 return;
9864         }
9865
9866         fb = &intel_fb->base;
9867
9868         fb->dev = dev;
9869
9870         if (INTEL_GEN(dev_priv) >= 4) {
9871                 if (val & DISPPLANE_TILED) {
9872                         plane_config->tiling = I915_TILING_X;
9873                         fb->modifier = I915_FORMAT_MOD_X_TILED;
9874                 }
9875         }
9876
9877         pixel_format = val & DISPPLANE_PIXFORMAT_MASK;
9878         fourcc = i9xx_format_to_fourcc(pixel_format);
9879         fb->format = drm_format_info(fourcc);
9880
9881         base = I915_READ(DSPSURF(pipe)) & 0xfffff000;
9882         if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv)) {
9883                 offset = I915_READ(DSPOFFSET(pipe));
9884         } else {
9885                 if (plane_config->tiling)
9886                         offset = I915_READ(DSPTILEOFF(pipe));
9887                 else
9888                         offset = I915_READ(DSPLINOFF(pipe));
9889         }
9890         plane_config->base = base;
9891
9892         val = I915_READ(PIPESRC(pipe));
9893         fb->width = ((val >> 16) & 0xfff) + 1;
9894         fb->height = ((val >> 0) & 0xfff) + 1;
9895
9896         val = I915_READ(DSPSTRIDE(pipe));
9897         fb->pitches[0] = val & 0xffffffc0;
9898
9899         aligned_height = intel_fb_align_height(dev, fb->height,
9900                                                fb->format->format,
9901                                                fb->modifier);
9902
9903         plane_config->size = fb->pitches[0] * aligned_height;
9904
9905         DRM_DEBUG_KMS("pipe %c with fb: size=%dx%d@%d, offset=%x, pitch %d, size 0x%x\n",
9906                       pipe_name(pipe), fb->width, fb->height,
9907                       fb->format->cpp[0] * 8, base, fb->pitches[0],
9908                       plane_config->size);
9909
9910         plane_config->fb = intel_fb;
9911 }
9912
9913 static bool ironlake_get_pipe_config(struct intel_crtc *crtc,
9914                                      struct intel_crtc_state *pipe_config)
9915 {
9916         struct drm_device *dev = crtc->base.dev;
9917         struct drm_i915_private *dev_priv = to_i915(dev);
9918         enum intel_display_power_domain power_domain;
9919         uint32_t tmp;
9920         bool ret;
9921
9922         power_domain = POWER_DOMAIN_PIPE(crtc->pipe);
9923         if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
9924                 return false;
9925
9926         pipe_config->cpu_transcoder = (enum transcoder) crtc->pipe;
9927         pipe_config->shared_dpll = NULL;
9928
9929         ret = false;
9930         tmp = I915_READ(PIPECONF(crtc->pipe));
9931         if (!(tmp & PIPECONF_ENABLE))
9932                 goto out;
9933
9934         switch (tmp & PIPECONF_BPC_MASK) {
9935         case PIPECONF_6BPC:
9936                 pipe_config->pipe_bpp = 18;
9937                 break;
9938         case PIPECONF_8BPC:
9939                 pipe_config->pipe_bpp = 24;
9940                 break;
9941         case PIPECONF_10BPC:
9942                 pipe_config->pipe_bpp = 30;
9943                 break;
9944         case PIPECONF_12BPC:
9945                 pipe_config->pipe_bpp = 36;
9946                 break;
9947         default:
9948                 break;
9949         }
9950
9951         if (tmp & PIPECONF_COLOR_RANGE_SELECT)
9952                 pipe_config->limited_color_range = true;
9953
9954         if (I915_READ(PCH_TRANSCONF(crtc->pipe)) & TRANS_ENABLE) {
9955                 struct intel_shared_dpll *pll;
9956                 enum intel_dpll_id pll_id;
9957
9958                 pipe_config->has_pch_encoder = true;
9959
9960                 tmp = I915_READ(FDI_RX_CTL(crtc->pipe));
9961                 pipe_config->fdi_lanes = ((FDI_DP_PORT_WIDTH_MASK & tmp) >>
9962                                           FDI_DP_PORT_WIDTH_SHIFT) + 1;
9963
9964                 ironlake_get_fdi_m_n_config(crtc, pipe_config);
9965
9966                 if (HAS_PCH_IBX(dev_priv)) {
9967                         /*
9968                          * The pipe->pch transcoder and pch transcoder->pll
9969                          * mapping is fixed.
9970                          */
9971                         pll_id = (enum intel_dpll_id) crtc->pipe;
9972                 } else {
9973                         tmp = I915_READ(PCH_DPLL_SEL);
9974                         if (tmp & TRANS_DPLLB_SEL(crtc->pipe))
9975                                 pll_id = DPLL_ID_PCH_PLL_B;
9976                         else
9977                                 pll_id= DPLL_ID_PCH_PLL_A;
9978                 }
9979
9980                 pipe_config->shared_dpll =
9981                         intel_get_shared_dpll_by_id(dev_priv, pll_id);
9982                 pll = pipe_config->shared_dpll;
9983
9984                 WARN_ON(!pll->funcs.get_hw_state(dev_priv, pll,
9985                                                  &pipe_config->dpll_hw_state));
9986
9987                 tmp = pipe_config->dpll_hw_state.dpll;
9988                 pipe_config->pixel_multiplier =
9989                         ((tmp & PLL_REF_SDVO_HDMI_MULTIPLIER_MASK)
9990                          >> PLL_REF_SDVO_HDMI_MULTIPLIER_SHIFT) + 1;
9991
9992                 ironlake_pch_clock_get(crtc, pipe_config);
9993         } else {
9994                 pipe_config->pixel_multiplier = 1;
9995         }
9996
9997         intel_get_pipe_timings(crtc, pipe_config);
9998         intel_get_pipe_src_size(crtc, pipe_config);
9999
10000         ironlake_get_pfit_config(crtc, pipe_config);
10001
10002         ret = true;
10003
10004 out:
10005         intel_display_power_put(dev_priv, power_domain);
10006
10007         return ret;
10008 }
10009
10010 static void assert_can_disable_lcpll(struct drm_i915_private *dev_priv)
10011 {
10012         struct drm_device *dev = &dev_priv->drm;
10013         struct intel_crtc *crtc;
10014
10015         for_each_intel_crtc(dev, crtc)
10016                 I915_STATE_WARN(crtc->active, "CRTC for pipe %c enabled\n",
10017                      pipe_name(crtc->pipe));
10018
10019         I915_STATE_WARN(I915_READ(HSW_PWR_WELL_DRIVER), "Power well on\n");
10020         I915_STATE_WARN(I915_READ(SPLL_CTL) & SPLL_PLL_ENABLE, "SPLL enabled\n");
10021         I915_STATE_WARN(I915_READ(WRPLL_CTL(0)) & WRPLL_PLL_ENABLE, "WRPLL1 enabled\n");
10022         I915_STATE_WARN(I915_READ(WRPLL_CTL(1)) & WRPLL_PLL_ENABLE, "WRPLL2 enabled\n");
10023         I915_STATE_WARN(I915_READ(PP_STATUS(0)) & PP_ON, "Panel power on\n");
10024         I915_STATE_WARN(I915_READ(BLC_PWM_CPU_CTL2) & BLM_PWM_ENABLE,
10025              "CPU PWM1 enabled\n");
10026         if (IS_HASWELL(dev_priv))
10027                 I915_STATE_WARN(I915_READ(HSW_BLC_PWM2_CTL) & BLM_PWM_ENABLE,
10028                      "CPU PWM2 enabled\n");
10029         I915_STATE_WARN(I915_READ(BLC_PWM_PCH_CTL1) & BLM_PCH_PWM_ENABLE,
10030              "PCH PWM1 enabled\n");
10031         I915_STATE_WARN(I915_READ(UTIL_PIN_CTL) & UTIL_PIN_ENABLE,
10032              "Utility pin enabled\n");
10033         I915_STATE_WARN(I915_READ(PCH_GTC_CTL) & PCH_GTC_ENABLE, "PCH GTC enabled\n");
10034
10035         /*
10036          * In theory we can still leave IRQs enabled, as long as only the HPD
10037          * interrupts remain enabled. We used to check for that, but since it's
10038          * gen-specific and since we only disable LCPLL after we fully disable
10039          * the interrupts, the check below should be enough.
10040          */
10041         I915_STATE_WARN(intel_irqs_enabled(dev_priv), "IRQs enabled\n");
10042 }
10043
10044 static uint32_t hsw_read_dcomp(struct drm_i915_private *dev_priv)
10045 {
10046         if (IS_HASWELL(dev_priv))
10047                 return I915_READ(D_COMP_HSW);
10048         else
10049                 return I915_READ(D_COMP_BDW);
10050 }
10051
10052 static void hsw_write_dcomp(struct drm_i915_private *dev_priv, uint32_t val)
10053 {
10054         if (IS_HASWELL(dev_priv)) {
10055                 mutex_lock(&dev_priv->rps.hw_lock);
10056                 if (sandybridge_pcode_write(dev_priv, GEN6_PCODE_WRITE_D_COMP,
10057                                             val))
10058                         DRM_DEBUG_KMS("Failed to write to D_COMP\n");
10059                 mutex_unlock(&dev_priv->rps.hw_lock);
10060         } else {
10061                 I915_WRITE(D_COMP_BDW, val);
10062                 POSTING_READ(D_COMP_BDW);
10063         }
10064 }
10065
10066 /*
10067  * This function implements pieces of two sequences from BSpec:
10068  * - Sequence for display software to disable LCPLL
10069  * - Sequence for display software to allow package C8+
10070  * The steps implemented here are just the steps that actually touch the LCPLL
10071  * register. Callers should take care of disabling all the display engine
10072  * functions, doing the mode unset, fixing interrupts, etc.
10073  */
10074 static void hsw_disable_lcpll(struct drm_i915_private *dev_priv,
10075                               bool switch_to_fclk, bool allow_power_down)
10076 {
10077         uint32_t val;
10078
10079         assert_can_disable_lcpll(dev_priv);
10080
10081         val = I915_READ(LCPLL_CTL);
10082
10083         if (switch_to_fclk) {
10084                 val |= LCPLL_CD_SOURCE_FCLK;
10085                 I915_WRITE(LCPLL_CTL, val);
10086
10087                 if (wait_for_us(I915_READ(LCPLL_CTL) &
10088                                 LCPLL_CD_SOURCE_FCLK_DONE, 1))
10089                         DRM_ERROR("Switching to FCLK failed\n");
10090
10091                 val = I915_READ(LCPLL_CTL);
10092         }
10093
10094         val |= LCPLL_PLL_DISABLE;
10095         I915_WRITE(LCPLL_CTL, val);
10096         POSTING_READ(LCPLL_CTL);
10097
10098         if (intel_wait_for_register(dev_priv, LCPLL_CTL, LCPLL_PLL_LOCK, 0, 1))
10099                 DRM_ERROR("LCPLL still locked\n");
10100
10101         val = hsw_read_dcomp(dev_priv);
10102         val |= D_COMP_COMP_DISABLE;
10103         hsw_write_dcomp(dev_priv, val);
10104         ndelay(100);
10105
10106         if (wait_for((hsw_read_dcomp(dev_priv) & D_COMP_RCOMP_IN_PROGRESS) == 0,
10107                      1))
10108                 DRM_ERROR("D_COMP RCOMP still in progress\n");
10109
10110         if (allow_power_down) {
10111                 val = I915_READ(LCPLL_CTL);
10112                 val |= LCPLL_POWER_DOWN_ALLOW;
10113                 I915_WRITE(LCPLL_CTL, val);
10114                 POSTING_READ(LCPLL_CTL);
10115         }
10116 }
10117
10118 /*
10119  * Fully restores LCPLL, disallowing power down and switching back to LCPLL
10120  * source.
10121  */
10122 static void hsw_restore_lcpll(struct drm_i915_private *dev_priv)
10123 {
10124         uint32_t val;
10125
10126         val = I915_READ(LCPLL_CTL);
10127
10128         if ((val & (LCPLL_PLL_LOCK | LCPLL_PLL_DISABLE | LCPLL_CD_SOURCE_FCLK |
10129                     LCPLL_POWER_DOWN_ALLOW)) == LCPLL_PLL_LOCK)
10130                 return;
10131
10132         /*
10133          * Make sure we're not on PC8 state before disabling PC8, otherwise
10134          * we'll hang the machine. To prevent PC8 state, just enable force_wake.
10135          */
10136         intel_uncore_forcewake_get(dev_priv, FORCEWAKE_ALL);
10137
10138         if (val & LCPLL_POWER_DOWN_ALLOW) {
10139                 val &= ~LCPLL_POWER_DOWN_ALLOW;
10140                 I915_WRITE(LCPLL_CTL, val);
10141                 POSTING_READ(LCPLL_CTL);
10142         }
10143
10144         val = hsw_read_dcomp(dev_priv);
10145         val |= D_COMP_COMP_FORCE;
10146         val &= ~D_COMP_COMP_DISABLE;
10147         hsw_write_dcomp(dev_priv, val);
10148
10149         val = I915_READ(LCPLL_CTL);
10150         val &= ~LCPLL_PLL_DISABLE;
10151         I915_WRITE(LCPLL_CTL, val);
10152
10153         if (intel_wait_for_register(dev_priv,
10154                                     LCPLL_CTL, LCPLL_PLL_LOCK, LCPLL_PLL_LOCK,
10155                                     5))
10156                 DRM_ERROR("LCPLL not locked yet\n");
10157
10158         if (val & LCPLL_CD_SOURCE_FCLK) {
10159                 val = I915_READ(LCPLL_CTL);
10160                 val &= ~LCPLL_CD_SOURCE_FCLK;
10161                 I915_WRITE(LCPLL_CTL, val);
10162
10163                 if (wait_for_us((I915_READ(LCPLL_CTL) &
10164                                  LCPLL_CD_SOURCE_FCLK_DONE) == 0, 1))
10165                         DRM_ERROR("Switching back to LCPLL failed\n");
10166         }
10167
10168         intel_uncore_forcewake_put(dev_priv, FORCEWAKE_ALL);
10169         intel_update_cdclk(dev_priv);
10170 }
10171
10172 /*
10173  * Package states C8 and deeper are really deep PC states that can only be
10174  * reached when all the devices on the system allow it, so even if the graphics
10175  * device allows PC8+, it doesn't mean the system will actually get to these
10176  * states. Our driver only allows PC8+ when going into runtime PM.
10177  *
10178  * The requirements for PC8+ are that all the outputs are disabled, the power
10179  * well is disabled and most interrupts are disabled, and these are also
10180  * requirements for runtime PM. When these conditions are met, we manually do
10181  * the other conditions: disable the interrupts, clocks and switch LCPLL refclk
10182  * to Fclk. If we're in PC8+ and we get an non-hotplug interrupt, we can hard
10183  * hang the machine.
10184  *
10185  * When we really reach PC8 or deeper states (not just when we allow it) we lose
10186  * the state of some registers, so when we come back from PC8+ we need to
10187  * restore this state. We don't get into PC8+ if we're not in RC6, so we don't
10188  * need to take care of the registers kept by RC6. Notice that this happens even
10189  * if we don't put the device in PCI D3 state (which is what currently happens
10190  * because of the runtime PM support).
10191  *
10192  * For more, read "Display Sequences for Package C8" on the hardware
10193  * documentation.
10194  */
10195 void hsw_enable_pc8(struct drm_i915_private *dev_priv)
10196 {
10197         uint32_t val;
10198
10199         DRM_DEBUG_KMS("Enabling package C8+\n");
10200
10201         if (HAS_PCH_LPT_LP(dev_priv)) {
10202                 val = I915_READ(SOUTH_DSPCLK_GATE_D);
10203                 val &= ~PCH_LP_PARTITION_LEVEL_DISABLE;
10204                 I915_WRITE(SOUTH_DSPCLK_GATE_D, val);
10205         }
10206
10207         lpt_disable_clkout_dp(dev_priv);
10208         hsw_disable_lcpll(dev_priv, true, true);
10209 }
10210
10211 void hsw_disable_pc8(struct drm_i915_private *dev_priv)
10212 {
10213         uint32_t val;
10214
10215         DRM_DEBUG_KMS("Disabling package C8+\n");
10216
10217         hsw_restore_lcpll(dev_priv);
10218         lpt_init_pch_refclk(dev_priv);
10219
10220         if (HAS_PCH_LPT_LP(dev_priv)) {
10221                 val = I915_READ(SOUTH_DSPCLK_GATE_D);
10222                 val |= PCH_LP_PARTITION_LEVEL_DISABLE;
10223                 I915_WRITE(SOUTH_DSPCLK_GATE_D, val);
10224         }
10225 }
10226
10227 static void bxt_modeset_commit_cdclk(struct drm_atomic_state *old_state)
10228 {
10229         struct drm_device *dev = old_state->dev;
10230         struct intel_atomic_state *old_intel_state =
10231                 to_intel_atomic_state(old_state);
10232         unsigned int req_cdclk = old_intel_state->dev_cdclk;
10233
10234         bxt_set_cdclk(to_i915(dev), req_cdclk);
10235 }
10236
10237 static int bdw_adjust_min_pipe_pixel_rate(struct intel_crtc_state *crtc_state,
10238                                           int pixel_rate)
10239 {
10240         struct drm_i915_private *dev_priv = to_i915(crtc_state->base.crtc->dev);
10241
10242         /* pixel rate mustn't exceed 95% of cdclk with IPS on BDW */
10243         if (IS_BROADWELL(dev_priv) && crtc_state->ips_enabled)
10244                 pixel_rate = DIV_ROUND_UP(pixel_rate * 100, 95);
10245
10246         /* BSpec says "Do not use DisplayPort with CDCLK less than
10247          * 432 MHz, audio enabled, port width x4, and link rate
10248          * HBR2 (5.4 GHz), or else there may be audio corruption or
10249          * screen corruption."
10250          */
10251         if (intel_crtc_has_dp_encoder(crtc_state) &&
10252             crtc_state->has_audio &&
10253             crtc_state->port_clock >= 540000 &&
10254             crtc_state->lane_count == 4)
10255                 pixel_rate = max(432000, pixel_rate);
10256
10257         return pixel_rate;
10258 }
10259
10260 /* compute the max rate for new configuration */
10261 static int ilk_max_pixel_rate(struct drm_atomic_state *state)
10262 {
10263         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
10264         struct drm_i915_private *dev_priv = to_i915(state->dev);
10265         struct drm_crtc *crtc;
10266         struct drm_crtc_state *cstate;
10267         struct intel_crtc_state *crtc_state;
10268         unsigned max_pixel_rate = 0, i;
10269         enum pipe pipe;
10270
10271         memcpy(intel_state->min_pixclk, dev_priv->min_pixclk,
10272                sizeof(intel_state->min_pixclk));
10273
10274         for_each_crtc_in_state(state, crtc, cstate, i) {
10275                 int pixel_rate;
10276
10277                 crtc_state = to_intel_crtc_state(cstate);
10278                 if (!crtc_state->base.enable) {
10279                         intel_state->min_pixclk[i] = 0;
10280                         continue;
10281                 }
10282
10283                 pixel_rate = ilk_pipe_pixel_rate(crtc_state);
10284
10285                 if (IS_BROADWELL(dev_priv) || IS_GEN9(dev_priv))
10286                         pixel_rate = bdw_adjust_min_pipe_pixel_rate(crtc_state,
10287                                                                     pixel_rate);
10288
10289                 intel_state->min_pixclk[i] = pixel_rate;
10290         }
10291
10292         for_each_pipe(dev_priv, pipe)
10293                 max_pixel_rate = max(intel_state->min_pixclk[pipe], max_pixel_rate);
10294
10295         return max_pixel_rate;
10296 }
10297
10298 static void broadwell_set_cdclk(struct drm_device *dev, int cdclk)
10299 {
10300         struct drm_i915_private *dev_priv = to_i915(dev);
10301         uint32_t val, data;
10302         int ret;
10303
10304         if (WARN((I915_READ(LCPLL_CTL) &
10305                   (LCPLL_PLL_DISABLE | LCPLL_PLL_LOCK |
10306                    LCPLL_CD_CLOCK_DISABLE | LCPLL_ROOT_CD_CLOCK_DISABLE |
10307                    LCPLL_CD2X_CLOCK_DISABLE | LCPLL_POWER_DOWN_ALLOW |
10308                    LCPLL_CD_SOURCE_FCLK)) != LCPLL_PLL_LOCK,
10309                  "trying to change cdclk frequency with cdclk not enabled\n"))
10310                 return;
10311
10312         mutex_lock(&dev_priv->rps.hw_lock);
10313         ret = sandybridge_pcode_write(dev_priv,
10314                                       BDW_PCODE_DISPLAY_FREQ_CHANGE_REQ, 0x0);
10315         mutex_unlock(&dev_priv->rps.hw_lock);
10316         if (ret) {
10317                 DRM_ERROR("failed to inform pcode about cdclk change\n");
10318                 return;
10319         }
10320
10321         val = I915_READ(LCPLL_CTL);
10322         val |= LCPLL_CD_SOURCE_FCLK;
10323         I915_WRITE(LCPLL_CTL, val);
10324
10325         if (wait_for_us(I915_READ(LCPLL_CTL) &
10326                         LCPLL_CD_SOURCE_FCLK_DONE, 1))
10327                 DRM_ERROR("Switching to FCLK failed\n");
10328
10329         val = I915_READ(LCPLL_CTL);
10330         val &= ~LCPLL_CLK_FREQ_MASK;
10331
10332         switch (cdclk) {
10333         case 450000:
10334                 val |= LCPLL_CLK_FREQ_450;
10335                 data = 0;
10336                 break;
10337         case 540000:
10338                 val |= LCPLL_CLK_FREQ_54O_BDW;
10339                 data = 1;
10340                 break;
10341         case 337500:
10342                 val |= LCPLL_CLK_FREQ_337_5_BDW;
10343                 data = 2;
10344                 break;
10345         case 675000:
10346                 val |= LCPLL_CLK_FREQ_675_BDW;
10347                 data = 3;
10348                 break;
10349         default:
10350                 WARN(1, "invalid cdclk frequency\n");
10351                 return;
10352         }
10353
10354         I915_WRITE(LCPLL_CTL, val);
10355
10356         val = I915_READ(LCPLL_CTL);
10357         val &= ~LCPLL_CD_SOURCE_FCLK;
10358         I915_WRITE(LCPLL_CTL, val);
10359
10360         if (wait_for_us((I915_READ(LCPLL_CTL) &
10361                         LCPLL_CD_SOURCE_FCLK_DONE) == 0, 1))
10362                 DRM_ERROR("Switching back to LCPLL failed\n");
10363
10364         mutex_lock(&dev_priv->rps.hw_lock);
10365         sandybridge_pcode_write(dev_priv, HSW_PCODE_DE_WRITE_FREQ_REQ, data);
10366         mutex_unlock(&dev_priv->rps.hw_lock);
10367
10368         I915_WRITE(CDCLK_FREQ, DIV_ROUND_CLOSEST(cdclk, 1000) - 1);
10369
10370         intel_update_cdclk(dev_priv);
10371
10372         WARN(cdclk != dev_priv->cdclk_freq,
10373              "cdclk requested %d kHz but got %d kHz\n",
10374              cdclk, dev_priv->cdclk_freq);
10375 }
10376
10377 static int broadwell_calc_cdclk(int max_pixclk)
10378 {
10379         if (max_pixclk > 540000)
10380                 return 675000;
10381         else if (max_pixclk > 450000)
10382                 return 540000;
10383         else if (max_pixclk > 337500)
10384                 return 450000;
10385         else
10386                 return 337500;
10387 }
10388
10389 static int broadwell_modeset_calc_cdclk(struct drm_atomic_state *state)
10390 {
10391         struct drm_i915_private *dev_priv = to_i915(state->dev);
10392         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
10393         int max_pixclk = ilk_max_pixel_rate(state);
10394         int cdclk;
10395
10396         /*
10397          * FIXME should also account for plane ratio
10398          * once 64bpp pixel formats are supported.
10399          */
10400         cdclk = broadwell_calc_cdclk(max_pixclk);
10401
10402         if (cdclk > dev_priv->max_cdclk_freq) {
10403                 DRM_DEBUG_KMS("requested cdclk (%d kHz) exceeds max (%d kHz)\n",
10404                               cdclk, dev_priv->max_cdclk_freq);
10405                 return -EINVAL;
10406         }
10407
10408         intel_state->cdclk = intel_state->dev_cdclk = cdclk;
10409         if (!intel_state->active_crtcs)
10410                 intel_state->dev_cdclk = broadwell_calc_cdclk(0);
10411
10412         return 0;
10413 }
10414
10415 static void broadwell_modeset_commit_cdclk(struct drm_atomic_state *old_state)
10416 {
10417         struct drm_device *dev = old_state->dev;
10418         struct intel_atomic_state *old_intel_state =
10419                 to_intel_atomic_state(old_state);
10420         unsigned req_cdclk = old_intel_state->dev_cdclk;
10421
10422         broadwell_set_cdclk(dev, req_cdclk);
10423 }
10424
10425 static int skl_modeset_calc_cdclk(struct drm_atomic_state *state)
10426 {
10427         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
10428         struct drm_i915_private *dev_priv = to_i915(state->dev);
10429         const int max_pixclk = ilk_max_pixel_rate(state);
10430         int vco = intel_state->cdclk_pll_vco;
10431         int cdclk;
10432
10433         /*
10434          * FIXME should also account for plane ratio
10435          * once 64bpp pixel formats are supported.
10436          */
10437         cdclk = skl_calc_cdclk(max_pixclk, vco);
10438
10439         /*
10440          * FIXME move the cdclk caclulation to
10441          * compute_config() so we can fail gracegully.
10442          */
10443         if (cdclk > dev_priv->max_cdclk_freq) {
10444                 DRM_ERROR("requested cdclk (%d kHz) exceeds max (%d kHz)\n",
10445                           cdclk, dev_priv->max_cdclk_freq);
10446                 cdclk = dev_priv->max_cdclk_freq;
10447         }
10448
10449         intel_state->cdclk = intel_state->dev_cdclk = cdclk;
10450         if (!intel_state->active_crtcs)
10451                 intel_state->dev_cdclk = skl_calc_cdclk(0, vco);
10452
10453         return 0;
10454 }
10455
10456 static void skl_modeset_commit_cdclk(struct drm_atomic_state *old_state)
10457 {
10458         struct drm_i915_private *dev_priv = to_i915(old_state->dev);
10459         struct intel_atomic_state *intel_state = to_intel_atomic_state(old_state);
10460         unsigned int req_cdclk = intel_state->dev_cdclk;
10461         unsigned int req_vco = intel_state->cdclk_pll_vco;
10462
10463         skl_set_cdclk(dev_priv, req_cdclk, req_vco);
10464 }
10465
10466 static int haswell_crtc_compute_clock(struct intel_crtc *crtc,
10467                                       struct intel_crtc_state *crtc_state)
10468 {
10469         if (!intel_crtc_has_type(crtc_state, INTEL_OUTPUT_DSI)) {
10470                 if (!intel_ddi_pll_select(crtc, crtc_state))
10471                         return -EINVAL;
10472         }
10473
10474         crtc->lowfreq_avail = false;
10475
10476         return 0;
10477 }
10478
10479 static void bxt_get_ddi_pll(struct drm_i915_private *dev_priv,
10480                                 enum port port,
10481                                 struct intel_crtc_state *pipe_config)
10482 {
10483         enum intel_dpll_id id;
10484
10485         switch (port) {
10486         case PORT_A:
10487                 id = DPLL_ID_SKL_DPLL0;
10488                 break;
10489         case PORT_B:
10490                 id = DPLL_ID_SKL_DPLL1;
10491                 break;
10492         case PORT_C:
10493                 id = DPLL_ID_SKL_DPLL2;
10494                 break;
10495         default:
10496                 DRM_ERROR("Incorrect port type\n");
10497                 return;
10498         }
10499
10500         pipe_config->shared_dpll = intel_get_shared_dpll_by_id(dev_priv, id);
10501 }
10502
10503 static void skylake_get_ddi_pll(struct drm_i915_private *dev_priv,
10504                                 enum port port,
10505                                 struct intel_crtc_state *pipe_config)
10506 {
10507         enum intel_dpll_id id;
10508         u32 temp;
10509
10510         temp = I915_READ(DPLL_CTRL2) & DPLL_CTRL2_DDI_CLK_SEL_MASK(port);
10511         id = temp >> (port * 3 + 1);
10512
10513         if (WARN_ON(id < SKL_DPLL0 || id > SKL_DPLL3))
10514                 return;
10515
10516         pipe_config->shared_dpll = intel_get_shared_dpll_by_id(dev_priv, id);
10517 }
10518
10519 static void haswell_get_ddi_pll(struct drm_i915_private *dev_priv,
10520                                 enum port port,
10521                                 struct intel_crtc_state *pipe_config)
10522 {
10523         enum intel_dpll_id id;
10524         uint32_t ddi_pll_sel = I915_READ(PORT_CLK_SEL(port));
10525
10526         switch (ddi_pll_sel) {
10527         case PORT_CLK_SEL_WRPLL1:
10528                 id = DPLL_ID_WRPLL1;
10529                 break;
10530         case PORT_CLK_SEL_WRPLL2:
10531                 id = DPLL_ID_WRPLL2;
10532                 break;
10533         case PORT_CLK_SEL_SPLL:
10534                 id = DPLL_ID_SPLL;
10535                 break;
10536         case PORT_CLK_SEL_LCPLL_810:
10537                 id = DPLL_ID_LCPLL_810;
10538                 break;
10539         case PORT_CLK_SEL_LCPLL_1350:
10540                 id = DPLL_ID_LCPLL_1350;
10541                 break;
10542         case PORT_CLK_SEL_LCPLL_2700:
10543                 id = DPLL_ID_LCPLL_2700;
10544                 break;
10545         default:
10546                 MISSING_CASE(ddi_pll_sel);
10547                 /* fall through */
10548         case PORT_CLK_SEL_NONE:
10549                 return;
10550         }
10551
10552         pipe_config->shared_dpll = intel_get_shared_dpll_by_id(dev_priv, id);
10553 }
10554
10555 static bool hsw_get_transcoder_state(struct intel_crtc *crtc,
10556                                      struct intel_crtc_state *pipe_config,
10557                                      unsigned long *power_domain_mask)
10558 {
10559         struct drm_device *dev = crtc->base.dev;
10560         struct drm_i915_private *dev_priv = to_i915(dev);
10561         enum intel_display_power_domain power_domain;
10562         u32 tmp;
10563
10564         /*
10565          * The pipe->transcoder mapping is fixed with the exception of the eDP
10566          * transcoder handled below.
10567          */
10568         pipe_config->cpu_transcoder = (enum transcoder) crtc->pipe;
10569
10570         /*
10571          * XXX: Do intel_display_power_get_if_enabled before reading this (for
10572          * consistency and less surprising code; it's in always on power).
10573          */
10574         tmp = I915_READ(TRANS_DDI_FUNC_CTL(TRANSCODER_EDP));
10575         if (tmp & TRANS_DDI_FUNC_ENABLE) {
10576                 enum pipe trans_edp_pipe;
10577                 switch (tmp & TRANS_DDI_EDP_INPUT_MASK) {
10578                 default:
10579                         WARN(1, "unknown pipe linked to edp transcoder\n");
10580                 case TRANS_DDI_EDP_INPUT_A_ONOFF:
10581                 case TRANS_DDI_EDP_INPUT_A_ON:
10582                         trans_edp_pipe = PIPE_A;
10583                         break;
10584                 case TRANS_DDI_EDP_INPUT_B_ONOFF:
10585                         trans_edp_pipe = PIPE_B;
10586                         break;
10587                 case TRANS_DDI_EDP_INPUT_C_ONOFF:
10588                         trans_edp_pipe = PIPE_C;
10589                         break;
10590                 }
10591
10592                 if (trans_edp_pipe == crtc->pipe)
10593                         pipe_config->cpu_transcoder = TRANSCODER_EDP;
10594         }
10595
10596         power_domain = POWER_DOMAIN_TRANSCODER(pipe_config->cpu_transcoder);
10597         if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
10598                 return false;
10599         *power_domain_mask |= BIT(power_domain);
10600
10601         tmp = I915_READ(PIPECONF(pipe_config->cpu_transcoder));
10602
10603         return tmp & PIPECONF_ENABLE;
10604 }
10605
10606 static bool bxt_get_dsi_transcoder_state(struct intel_crtc *crtc,
10607                                          struct intel_crtc_state *pipe_config,
10608                                          unsigned long *power_domain_mask)
10609 {
10610         struct drm_device *dev = crtc->base.dev;
10611         struct drm_i915_private *dev_priv = to_i915(dev);
10612         enum intel_display_power_domain power_domain;
10613         enum port port;
10614         enum transcoder cpu_transcoder;
10615         u32 tmp;
10616
10617         for_each_port_masked(port, BIT(PORT_A) | BIT(PORT_C)) {
10618                 if (port == PORT_A)
10619                         cpu_transcoder = TRANSCODER_DSI_A;
10620                 else
10621                         cpu_transcoder = TRANSCODER_DSI_C;
10622
10623                 power_domain = POWER_DOMAIN_TRANSCODER(cpu_transcoder);
10624                 if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
10625                         continue;
10626                 *power_domain_mask |= BIT(power_domain);
10627
10628                 /*
10629                  * The PLL needs to be enabled with a valid divider
10630                  * configuration, otherwise accessing DSI registers will hang
10631                  * the machine. See BSpec North Display Engine
10632                  * registers/MIPI[BXT]. We can break out here early, since we
10633                  * need the same DSI PLL to be enabled for both DSI ports.
10634                  */
10635                 if (!intel_dsi_pll_is_enabled(dev_priv))
10636                         break;
10637
10638                 /* XXX: this works for video mode only */
10639                 tmp = I915_READ(BXT_MIPI_PORT_CTRL(port));
10640                 if (!(tmp & DPI_ENABLE))
10641                         continue;
10642
10643                 tmp = I915_READ(MIPI_CTRL(port));
10644                 if ((tmp & BXT_PIPE_SELECT_MASK) != BXT_PIPE_SELECT(crtc->pipe))
10645                         continue;
10646
10647                 pipe_config->cpu_transcoder = cpu_transcoder;
10648                 break;
10649         }
10650
10651         return transcoder_is_dsi(pipe_config->cpu_transcoder);
10652 }
10653
10654 static void haswell_get_ddi_port_state(struct intel_crtc *crtc,
10655                                        struct intel_crtc_state *pipe_config)
10656 {
10657         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
10658         struct intel_shared_dpll *pll;
10659         enum port port;
10660         uint32_t tmp;
10661
10662         tmp = I915_READ(TRANS_DDI_FUNC_CTL(pipe_config->cpu_transcoder));
10663
10664         port = (tmp & TRANS_DDI_PORT_MASK) >> TRANS_DDI_PORT_SHIFT;
10665
10666         if (IS_SKYLAKE(dev_priv) || IS_KABYLAKE(dev_priv))
10667                 skylake_get_ddi_pll(dev_priv, port, pipe_config);
10668         else if (IS_GEN9_LP(dev_priv))
10669                 bxt_get_ddi_pll(dev_priv, port, pipe_config);
10670         else
10671                 haswell_get_ddi_pll(dev_priv, port, pipe_config);
10672
10673         pll = pipe_config->shared_dpll;
10674         if (pll) {
10675                 WARN_ON(!pll->funcs.get_hw_state(dev_priv, pll,
10676                                                  &pipe_config->dpll_hw_state));
10677         }
10678
10679         /*
10680          * Haswell has only FDI/PCH transcoder A. It is which is connected to
10681          * DDI E. So just check whether this pipe is wired to DDI E and whether
10682          * the PCH transcoder is on.
10683          */
10684         if (INTEL_GEN(dev_priv) < 9 &&
10685             (port == PORT_E) && I915_READ(LPT_TRANSCONF) & TRANS_ENABLE) {
10686                 pipe_config->has_pch_encoder = true;
10687
10688                 tmp = I915_READ(FDI_RX_CTL(PIPE_A));
10689                 pipe_config->fdi_lanes = ((FDI_DP_PORT_WIDTH_MASK & tmp) >>
10690                                           FDI_DP_PORT_WIDTH_SHIFT) + 1;
10691
10692                 ironlake_get_fdi_m_n_config(crtc, pipe_config);
10693         }
10694 }
10695
10696 static bool haswell_get_pipe_config(struct intel_crtc *crtc,
10697                                     struct intel_crtc_state *pipe_config)
10698 {
10699         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
10700         enum intel_display_power_domain power_domain;
10701         unsigned long power_domain_mask;
10702         bool active;
10703
10704         power_domain = POWER_DOMAIN_PIPE(crtc->pipe);
10705         if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
10706                 return false;
10707         power_domain_mask = BIT(power_domain);
10708
10709         pipe_config->shared_dpll = NULL;
10710
10711         active = hsw_get_transcoder_state(crtc, pipe_config, &power_domain_mask);
10712
10713         if (IS_GEN9_LP(dev_priv) &&
10714             bxt_get_dsi_transcoder_state(crtc, pipe_config, &power_domain_mask)) {
10715                 WARN_ON(active);
10716                 active = true;
10717         }
10718
10719         if (!active)
10720                 goto out;
10721
10722         if (!transcoder_is_dsi(pipe_config->cpu_transcoder)) {
10723                 haswell_get_ddi_port_state(crtc, pipe_config);
10724                 intel_get_pipe_timings(crtc, pipe_config);
10725         }
10726
10727         intel_get_pipe_src_size(crtc, pipe_config);
10728
10729         pipe_config->gamma_mode =
10730                 I915_READ(GAMMA_MODE(crtc->pipe)) & GAMMA_MODE_MODE_MASK;
10731
10732         if (INTEL_GEN(dev_priv) >= 9) {
10733                 intel_crtc_init_scalers(crtc, pipe_config);
10734
10735                 pipe_config->scaler_state.scaler_id = -1;
10736                 pipe_config->scaler_state.scaler_users &= ~(1 << SKL_CRTC_INDEX);
10737         }
10738
10739         power_domain = POWER_DOMAIN_PIPE_PANEL_FITTER(crtc->pipe);
10740         if (intel_display_power_get_if_enabled(dev_priv, power_domain)) {
10741                 power_domain_mask |= BIT(power_domain);
10742                 if (INTEL_GEN(dev_priv) >= 9)
10743                         skylake_get_pfit_config(crtc, pipe_config);
10744                 else
10745                         ironlake_get_pfit_config(crtc, pipe_config);
10746         }
10747
10748         if (IS_HASWELL(dev_priv))
10749                 pipe_config->ips_enabled = hsw_crtc_supports_ips(crtc) &&
10750                         (I915_READ(IPS_CTL) & IPS_ENABLE);
10751
10752         if (pipe_config->cpu_transcoder != TRANSCODER_EDP &&
10753             !transcoder_is_dsi(pipe_config->cpu_transcoder)) {
10754                 pipe_config->pixel_multiplier =
10755                         I915_READ(PIPE_MULT(pipe_config->cpu_transcoder)) + 1;
10756         } else {
10757                 pipe_config->pixel_multiplier = 1;
10758         }
10759
10760 out:
10761         for_each_power_domain(power_domain, power_domain_mask)
10762                 intel_display_power_put(dev_priv, power_domain);
10763
10764         return active;
10765 }
10766
10767 static void i845_update_cursor(struct drm_crtc *crtc, u32 base,
10768                                const struct intel_plane_state *plane_state)
10769 {
10770         struct drm_device *dev = crtc->dev;
10771         struct drm_i915_private *dev_priv = to_i915(dev);
10772         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10773         uint32_t cntl = 0, size = 0;
10774
10775         if (plane_state && plane_state->base.visible) {
10776                 unsigned int width = plane_state->base.crtc_w;
10777                 unsigned int height = plane_state->base.crtc_h;
10778                 unsigned int stride = roundup_pow_of_two(width) * 4;
10779
10780                 switch (stride) {
10781                 default:
10782                         WARN_ONCE(1, "Invalid cursor width/stride, width=%u, stride=%u\n",
10783                                   width, stride);
10784                         stride = 256;
10785                         /* fallthrough */
10786                 case 256:
10787                 case 512:
10788                 case 1024:
10789                 case 2048:
10790                         break;
10791                 }
10792
10793                 cntl |= CURSOR_ENABLE |
10794                         CURSOR_GAMMA_ENABLE |
10795                         CURSOR_FORMAT_ARGB |
10796                         CURSOR_STRIDE(stride);
10797
10798                 size = (height << 12) | width;
10799         }
10800
10801         if (intel_crtc->cursor_cntl != 0 &&
10802             (intel_crtc->cursor_base != base ||
10803              intel_crtc->cursor_size != size ||
10804              intel_crtc->cursor_cntl != cntl)) {
10805                 /* On these chipsets we can only modify the base/size/stride
10806                  * whilst the cursor is disabled.
10807                  */
10808                 I915_WRITE(CURCNTR(PIPE_A), 0);
10809                 POSTING_READ(CURCNTR(PIPE_A));
10810                 intel_crtc->cursor_cntl = 0;
10811         }
10812
10813         if (intel_crtc->cursor_base != base) {
10814                 I915_WRITE(CURBASE(PIPE_A), base);
10815                 intel_crtc->cursor_base = base;
10816         }
10817
10818         if (intel_crtc->cursor_size != size) {
10819                 I915_WRITE(CURSIZE, size);
10820                 intel_crtc->cursor_size = size;
10821         }
10822
10823         if (intel_crtc->cursor_cntl != cntl) {
10824                 I915_WRITE(CURCNTR(PIPE_A), cntl);
10825                 POSTING_READ(CURCNTR(PIPE_A));
10826                 intel_crtc->cursor_cntl = cntl;
10827         }
10828 }
10829
10830 static void i9xx_update_cursor(struct drm_crtc *crtc, u32 base,
10831                                const struct intel_plane_state *plane_state)
10832 {
10833         struct drm_device *dev = crtc->dev;
10834         struct drm_i915_private *dev_priv = to_i915(dev);
10835         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10836         int pipe = intel_crtc->pipe;
10837         uint32_t cntl = 0;
10838
10839         if (plane_state && plane_state->base.visible) {
10840                 cntl = MCURSOR_GAMMA_ENABLE;
10841                 switch (plane_state->base.crtc_w) {
10842                         case 64:
10843                                 cntl |= CURSOR_MODE_64_ARGB_AX;
10844                                 break;
10845                         case 128:
10846                                 cntl |= CURSOR_MODE_128_ARGB_AX;
10847                                 break;
10848                         case 256:
10849                                 cntl |= CURSOR_MODE_256_ARGB_AX;
10850                                 break;
10851                         default:
10852                                 MISSING_CASE(plane_state->base.crtc_w);
10853                                 return;
10854                 }
10855                 cntl |= pipe << 28; /* Connect to correct pipe */
10856
10857                 if (HAS_DDI(dev_priv))
10858                         cntl |= CURSOR_PIPE_CSC_ENABLE;
10859
10860                 if (plane_state->base.rotation & DRM_ROTATE_180)
10861                         cntl |= CURSOR_ROTATE_180;
10862         }
10863
10864         if (intel_crtc->cursor_cntl != cntl) {
10865                 I915_WRITE(CURCNTR(pipe), cntl);
10866                 POSTING_READ(CURCNTR(pipe));
10867                 intel_crtc->cursor_cntl = cntl;
10868         }
10869
10870         /* and commit changes on next vblank */
10871         I915_WRITE(CURBASE(pipe), base);
10872         POSTING_READ(CURBASE(pipe));
10873
10874         intel_crtc->cursor_base = base;
10875 }
10876
10877 /* If no-part of the cursor is visible on the framebuffer, then the GPU may hang... */
10878 static void intel_crtc_update_cursor(struct drm_crtc *crtc,
10879                                      const struct intel_plane_state *plane_state)
10880 {
10881         struct drm_device *dev = crtc->dev;
10882         struct drm_i915_private *dev_priv = to_i915(dev);
10883         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10884         int pipe = intel_crtc->pipe;
10885         u32 base = intel_crtc->cursor_addr;
10886         u32 pos = 0;
10887
10888         if (plane_state) {
10889                 int x = plane_state->base.crtc_x;
10890                 int y = plane_state->base.crtc_y;
10891
10892                 if (x < 0) {
10893                         pos |= CURSOR_POS_SIGN << CURSOR_X_SHIFT;
10894                         x = -x;
10895                 }
10896                 pos |= x << CURSOR_X_SHIFT;
10897
10898                 if (y < 0) {
10899                         pos |= CURSOR_POS_SIGN << CURSOR_Y_SHIFT;
10900                         y = -y;
10901                 }
10902                 pos |= y << CURSOR_Y_SHIFT;
10903
10904                 /* ILK+ do this automagically */
10905                 if (HAS_GMCH_DISPLAY(dev_priv) &&
10906                     plane_state->base.rotation & DRM_ROTATE_180) {
10907                         base += (plane_state->base.crtc_h *
10908                                  plane_state->base.crtc_w - 1) * 4;
10909                 }
10910         }
10911
10912         I915_WRITE(CURPOS(pipe), pos);
10913
10914         if (IS_I845G(dev_priv) || IS_I865G(dev_priv))
10915                 i845_update_cursor(crtc, base, plane_state);
10916         else
10917                 i9xx_update_cursor(crtc, base, plane_state);
10918 }
10919
10920 static bool cursor_size_ok(struct drm_i915_private *dev_priv,
10921                            uint32_t width, uint32_t height)
10922 {
10923         if (width == 0 || height == 0)
10924                 return false;
10925
10926         /*
10927          * 845g/865g are special in that they are only limited by
10928          * the width of their cursors, the height is arbitrary up to
10929          * the precision of the register. Everything else requires
10930          * square cursors, limited to a few power-of-two sizes.
10931          */
10932         if (IS_I845G(dev_priv) || IS_I865G(dev_priv)) {
10933                 if ((width & 63) != 0)
10934                         return false;
10935
10936                 if (width > (IS_I845G(dev_priv) ? 64 : 512))
10937                         return false;
10938
10939                 if (height > 1023)
10940                         return false;
10941         } else {
10942                 switch (width | height) {
10943                 case 256:
10944                 case 128:
10945                         if (IS_GEN2(dev_priv))
10946                                 return false;
10947                 case 64:
10948                         break;
10949                 default:
10950                         return false;
10951                 }
10952         }
10953
10954         return true;
10955 }
10956
10957 /* VESA 640x480x72Hz mode to set on the pipe */
10958 static struct drm_display_mode load_detect_mode = {
10959         DRM_MODE("640x480", DRM_MODE_TYPE_DEFAULT, 31500, 640, 664,
10960                  704, 832, 0, 480, 489, 491, 520, 0, DRM_MODE_FLAG_NHSYNC | DRM_MODE_FLAG_NVSYNC),
10961 };
10962
10963 struct drm_framebuffer *
10964 __intel_framebuffer_create(struct drm_device *dev,
10965                            struct drm_mode_fb_cmd2 *mode_cmd,
10966                            struct drm_i915_gem_object *obj)
10967 {
10968         struct intel_framebuffer *intel_fb;
10969         int ret;
10970
10971         intel_fb = kzalloc(sizeof(*intel_fb), GFP_KERNEL);
10972         if (!intel_fb)
10973                 return ERR_PTR(-ENOMEM);
10974
10975         ret = intel_framebuffer_init(dev, intel_fb, mode_cmd, obj);
10976         if (ret)
10977                 goto err;
10978
10979         return &intel_fb->base;
10980
10981 err:
10982         kfree(intel_fb);
10983         return ERR_PTR(ret);
10984 }
10985
10986 static struct drm_framebuffer *
10987 intel_framebuffer_create(struct drm_device *dev,
10988                          struct drm_mode_fb_cmd2 *mode_cmd,
10989                          struct drm_i915_gem_object *obj)
10990 {
10991         struct drm_framebuffer *fb;
10992         int ret;
10993
10994         ret = i915_mutex_lock_interruptible(dev);
10995         if (ret)
10996                 return ERR_PTR(ret);
10997         fb = __intel_framebuffer_create(dev, mode_cmd, obj);
10998         mutex_unlock(&dev->struct_mutex);
10999
11000         return fb;
11001 }
11002
11003 static u32
11004 intel_framebuffer_pitch_for_width(int width, int bpp)
11005 {
11006         u32 pitch = DIV_ROUND_UP(width * bpp, 8);
11007         return ALIGN(pitch, 64);
11008 }
11009
11010 static u32
11011 intel_framebuffer_size_for_mode(struct drm_display_mode *mode, int bpp)
11012 {
11013         u32 pitch = intel_framebuffer_pitch_for_width(mode->hdisplay, bpp);
11014         return PAGE_ALIGN(pitch * mode->vdisplay);
11015 }
11016
11017 static struct drm_framebuffer *
11018 intel_framebuffer_create_for_mode(struct drm_device *dev,
11019                                   struct drm_display_mode *mode,
11020                                   int depth, int bpp)
11021 {
11022         struct drm_framebuffer *fb;
11023         struct drm_i915_gem_object *obj;
11024         struct drm_mode_fb_cmd2 mode_cmd = { 0 };
11025
11026         obj = i915_gem_object_create(to_i915(dev),
11027                                     intel_framebuffer_size_for_mode(mode, bpp));
11028         if (IS_ERR(obj))
11029                 return ERR_CAST(obj);
11030
11031         mode_cmd.width = mode->hdisplay;
11032         mode_cmd.height = mode->vdisplay;
11033         mode_cmd.pitches[0] = intel_framebuffer_pitch_for_width(mode_cmd.width,
11034                                                                 bpp);
11035         mode_cmd.pixel_format = drm_mode_legacy_fb_format(bpp, depth);
11036
11037         fb = intel_framebuffer_create(dev, &mode_cmd, obj);
11038         if (IS_ERR(fb))
11039                 i915_gem_object_put(obj);
11040
11041         return fb;
11042 }
11043
11044 static struct drm_framebuffer *
11045 mode_fits_in_fbdev(struct drm_device *dev,
11046                    struct drm_display_mode *mode)
11047 {
11048 #ifdef CONFIG_DRM_FBDEV_EMULATION
11049         struct drm_i915_private *dev_priv = to_i915(dev);
11050         struct drm_i915_gem_object *obj;
11051         struct drm_framebuffer *fb;
11052
11053         if (!dev_priv->fbdev)
11054                 return NULL;
11055
11056         if (!dev_priv->fbdev->fb)
11057                 return NULL;
11058
11059         obj = dev_priv->fbdev->fb->obj;
11060         BUG_ON(!obj);
11061
11062         fb = &dev_priv->fbdev->fb->base;
11063         if (fb->pitches[0] < intel_framebuffer_pitch_for_width(mode->hdisplay,
11064                                                                fb->format->cpp[0] * 8))
11065                 return NULL;
11066
11067         if (obj->base.size < mode->vdisplay * fb->pitches[0])
11068                 return NULL;
11069
11070         drm_framebuffer_reference(fb);
11071         return fb;
11072 #else
11073         return NULL;
11074 #endif
11075 }
11076
11077 static int intel_modeset_setup_plane_state(struct drm_atomic_state *state,
11078                                            struct drm_crtc *crtc,
11079                                            struct drm_display_mode *mode,
11080                                            struct drm_framebuffer *fb,
11081                                            int x, int y)
11082 {
11083         struct drm_plane_state *plane_state;
11084         int hdisplay, vdisplay;
11085         int ret;
11086
11087         plane_state = drm_atomic_get_plane_state(state, crtc->primary);
11088         if (IS_ERR(plane_state))
11089                 return PTR_ERR(plane_state);
11090
11091         if (mode)
11092                 drm_mode_get_hv_timing(mode, &hdisplay, &vdisplay);
11093         else
11094                 hdisplay = vdisplay = 0;
11095
11096         ret = drm_atomic_set_crtc_for_plane(plane_state, fb ? crtc : NULL);
11097         if (ret)
11098                 return ret;
11099         drm_atomic_set_fb_for_plane(plane_state, fb);
11100         plane_state->crtc_x = 0;
11101         plane_state->crtc_y = 0;
11102         plane_state->crtc_w = hdisplay;
11103         plane_state->crtc_h = vdisplay;
11104         plane_state->src_x = x << 16;
11105         plane_state->src_y = y << 16;
11106         plane_state->src_w = hdisplay << 16;
11107         plane_state->src_h = vdisplay << 16;
11108
11109         return 0;
11110 }
11111
11112 bool intel_get_load_detect_pipe(struct drm_connector *connector,
11113                                 struct drm_display_mode *mode,
11114                                 struct intel_load_detect_pipe *old,
11115                                 struct drm_modeset_acquire_ctx *ctx)
11116 {
11117         struct intel_crtc *intel_crtc;
11118         struct intel_encoder *intel_encoder =
11119                 intel_attached_encoder(connector);
11120         struct drm_crtc *possible_crtc;
11121         struct drm_encoder *encoder = &intel_encoder->base;
11122         struct drm_crtc *crtc = NULL;
11123         struct drm_device *dev = encoder->dev;
11124         struct drm_i915_private *dev_priv = to_i915(dev);
11125         struct drm_framebuffer *fb;
11126         struct drm_mode_config *config = &dev->mode_config;
11127         struct drm_atomic_state *state = NULL, *restore_state = NULL;
11128         struct drm_connector_state *connector_state;
11129         struct intel_crtc_state *crtc_state;
11130         int ret, i = -1;
11131
11132         DRM_DEBUG_KMS("[CONNECTOR:%d:%s], [ENCODER:%d:%s]\n",
11133                       connector->base.id, connector->name,
11134                       encoder->base.id, encoder->name);
11135
11136         old->restore_state = NULL;
11137
11138 retry:
11139         ret = drm_modeset_lock(&config->connection_mutex, ctx);
11140         if (ret)
11141                 goto fail;
11142
11143         /*
11144          * Algorithm gets a little messy:
11145          *
11146          *   - if the connector already has an assigned crtc, use it (but make
11147          *     sure it's on first)
11148          *
11149          *   - try to find the first unused crtc that can drive this connector,
11150          *     and use that if we find one
11151          */
11152
11153         /* See if we already have a CRTC for this connector */
11154         if (connector->state->crtc) {
11155                 crtc = connector->state->crtc;
11156
11157                 ret = drm_modeset_lock(&crtc->mutex, ctx);
11158                 if (ret)
11159                         goto fail;
11160
11161                 /* Make sure the crtc and connector are running */
11162                 goto found;
11163         }
11164
11165         /* Find an unused one (if possible) */
11166         for_each_crtc(dev, possible_crtc) {
11167                 i++;
11168                 if (!(encoder->possible_crtcs & (1 << i)))
11169                         continue;
11170
11171                 ret = drm_modeset_lock(&possible_crtc->mutex, ctx);
11172                 if (ret)
11173                         goto fail;
11174
11175                 if (possible_crtc->state->enable) {
11176                         drm_modeset_unlock(&possible_crtc->mutex);
11177                         continue;
11178                 }
11179
11180                 crtc = possible_crtc;
11181                 break;
11182         }
11183
11184         /*
11185          * If we didn't find an unused CRTC, don't use any.
11186          */
11187         if (!crtc) {
11188                 DRM_DEBUG_KMS("no pipe available for load-detect\n");
11189                 goto fail;
11190         }
11191
11192 found:
11193         intel_crtc = to_intel_crtc(crtc);
11194
11195         ret = drm_modeset_lock(&crtc->primary->mutex, ctx);
11196         if (ret)
11197                 goto fail;
11198
11199         state = drm_atomic_state_alloc(dev);
11200         restore_state = drm_atomic_state_alloc(dev);
11201         if (!state || !restore_state) {
11202                 ret = -ENOMEM;
11203                 goto fail;
11204         }
11205
11206         state->acquire_ctx = ctx;
11207         restore_state->acquire_ctx = ctx;
11208
11209         connector_state = drm_atomic_get_connector_state(state, connector);
11210         if (IS_ERR(connector_state)) {
11211                 ret = PTR_ERR(connector_state);
11212                 goto fail;
11213         }
11214
11215         ret = drm_atomic_set_crtc_for_connector(connector_state, crtc);
11216         if (ret)
11217                 goto fail;
11218
11219         crtc_state = intel_atomic_get_crtc_state(state, intel_crtc);
11220         if (IS_ERR(crtc_state)) {
11221                 ret = PTR_ERR(crtc_state);
11222                 goto fail;
11223         }
11224
11225         crtc_state->base.active = crtc_state->base.enable = true;
11226
11227         if (!mode)
11228                 mode = &load_detect_mode;
11229
11230         /* We need a framebuffer large enough to accommodate all accesses
11231          * that the plane may generate whilst we perform load detection.
11232          * We can not rely on the fbcon either being present (we get called
11233          * during its initialisation to detect all boot displays, or it may
11234          * not even exist) or that it is large enough to satisfy the
11235          * requested mode.
11236          */
11237         fb = mode_fits_in_fbdev(dev, mode);
11238         if (fb == NULL) {
11239                 DRM_DEBUG_KMS("creating tmp fb for load-detection\n");
11240                 fb = intel_framebuffer_create_for_mode(dev, mode, 24, 32);
11241         } else
11242                 DRM_DEBUG_KMS("reusing fbdev for load-detection framebuffer\n");
11243         if (IS_ERR(fb)) {
11244                 DRM_DEBUG_KMS("failed to allocate framebuffer for load-detection\n");
11245                 goto fail;
11246         }
11247
11248         ret = intel_modeset_setup_plane_state(state, crtc, mode, fb, 0, 0);
11249         if (ret)
11250                 goto fail;
11251
11252         drm_framebuffer_unreference(fb);
11253
11254         ret = drm_atomic_set_mode_for_crtc(&crtc_state->base, mode);
11255         if (ret)
11256                 goto fail;
11257
11258         ret = PTR_ERR_OR_ZERO(drm_atomic_get_connector_state(restore_state, connector));
11259         if (!ret)
11260                 ret = PTR_ERR_OR_ZERO(drm_atomic_get_crtc_state(restore_state, crtc));
11261         if (!ret)
11262                 ret = PTR_ERR_OR_ZERO(drm_atomic_get_plane_state(restore_state, crtc->primary));
11263         if (ret) {
11264                 DRM_DEBUG_KMS("Failed to create a copy of old state to restore: %i\n", ret);
11265                 goto fail;
11266         }
11267
11268         ret = drm_atomic_commit(state);
11269         if (ret) {
11270                 DRM_DEBUG_KMS("failed to set mode on load-detect pipe\n");
11271                 goto fail;
11272         }
11273
11274         old->restore_state = restore_state;
11275         drm_atomic_state_put(state);
11276
11277         /* let the connector get through one full cycle before testing */
11278         intel_wait_for_vblank(dev_priv, intel_crtc->pipe);
11279         return true;
11280
11281 fail:
11282         if (state) {
11283                 drm_atomic_state_put(state);
11284                 state = NULL;
11285         }
11286         if (restore_state) {
11287                 drm_atomic_state_put(restore_state);
11288                 restore_state = NULL;
11289         }
11290
11291         if (ret == -EDEADLK) {
11292                 drm_modeset_backoff(ctx);
11293                 goto retry;
11294         }
11295
11296         return false;
11297 }
11298
11299 void intel_release_load_detect_pipe(struct drm_connector *connector,
11300                                     struct intel_load_detect_pipe *old,
11301                                     struct drm_modeset_acquire_ctx *ctx)
11302 {
11303         struct intel_encoder *intel_encoder =
11304                 intel_attached_encoder(connector);
11305         struct drm_encoder *encoder = &intel_encoder->base;
11306         struct drm_atomic_state *state = old->restore_state;
11307         int ret;
11308
11309         DRM_DEBUG_KMS("[CONNECTOR:%d:%s], [ENCODER:%d:%s]\n",
11310                       connector->base.id, connector->name,
11311                       encoder->base.id, encoder->name);
11312
11313         if (!state)
11314                 return;
11315
11316         ret = drm_atomic_commit(state);
11317         if (ret)
11318                 DRM_DEBUG_KMS("Couldn't release load detect pipe: %i\n", ret);
11319         drm_atomic_state_put(state);
11320 }
11321
11322 static int i9xx_pll_refclk(struct drm_device *dev,
11323                            const struct intel_crtc_state *pipe_config)
11324 {
11325         struct drm_i915_private *dev_priv = to_i915(dev);
11326         u32 dpll = pipe_config->dpll_hw_state.dpll;
11327
11328         if ((dpll & PLL_REF_INPUT_MASK) == PLLB_REF_INPUT_SPREADSPECTRUMIN)
11329                 return dev_priv->vbt.lvds_ssc_freq;
11330         else if (HAS_PCH_SPLIT(dev_priv))
11331                 return 120000;
11332         else if (!IS_GEN2(dev_priv))
11333                 return 96000;
11334         else
11335                 return 48000;
11336 }
11337
11338 /* Returns the clock of the currently programmed mode of the given pipe. */
11339 static void i9xx_crtc_clock_get(struct intel_crtc *crtc,
11340                                 struct intel_crtc_state *pipe_config)
11341 {
11342         struct drm_device *dev = crtc->base.dev;
11343         struct drm_i915_private *dev_priv = to_i915(dev);
11344         int pipe = pipe_config->cpu_transcoder;
11345         u32 dpll = pipe_config->dpll_hw_state.dpll;
11346         u32 fp;
11347         struct dpll clock;
11348         int port_clock;
11349         int refclk = i9xx_pll_refclk(dev, pipe_config);
11350
11351         if ((dpll & DISPLAY_RATE_SELECT_FPA1) == 0)
11352                 fp = pipe_config->dpll_hw_state.fp0;
11353         else
11354                 fp = pipe_config->dpll_hw_state.fp1;
11355
11356         clock.m1 = (fp & FP_M1_DIV_MASK) >> FP_M1_DIV_SHIFT;
11357         if (IS_PINEVIEW(dev_priv)) {
11358                 clock.n = ffs((fp & FP_N_PINEVIEW_DIV_MASK) >> FP_N_DIV_SHIFT) - 1;
11359                 clock.m2 = (fp & FP_M2_PINEVIEW_DIV_MASK) >> FP_M2_DIV_SHIFT;
11360         } else {
11361                 clock.n = (fp & FP_N_DIV_MASK) >> FP_N_DIV_SHIFT;
11362                 clock.m2 = (fp & FP_M2_DIV_MASK) >> FP_M2_DIV_SHIFT;
11363         }
11364
11365         if (!IS_GEN2(dev_priv)) {
11366                 if (IS_PINEVIEW(dev_priv))
11367                         clock.p1 = ffs((dpll & DPLL_FPA01_P1_POST_DIV_MASK_PINEVIEW) >>
11368                                 DPLL_FPA01_P1_POST_DIV_SHIFT_PINEVIEW);
11369                 else
11370                         clock.p1 = ffs((dpll & DPLL_FPA01_P1_POST_DIV_MASK) >>
11371                                DPLL_FPA01_P1_POST_DIV_SHIFT);
11372
11373                 switch (dpll & DPLL_MODE_MASK) {
11374                 case DPLLB_MODE_DAC_SERIAL:
11375                         clock.p2 = dpll & DPLL_DAC_SERIAL_P2_CLOCK_DIV_5 ?
11376                                 5 : 10;
11377                         break;
11378                 case DPLLB_MODE_LVDS:
11379                         clock.p2 = dpll & DPLLB_LVDS_P2_CLOCK_DIV_7 ?
11380                                 7 : 14;
11381                         break;
11382                 default:
11383                         DRM_DEBUG_KMS("Unknown DPLL mode %08x in programmed "
11384                                   "mode\n", (int)(dpll & DPLL_MODE_MASK));
11385                         return;
11386                 }
11387
11388                 if (IS_PINEVIEW(dev_priv))
11389                         port_clock = pnv_calc_dpll_params(refclk, &clock);
11390                 else
11391                         port_clock = i9xx_calc_dpll_params(refclk, &clock);
11392         } else {
11393                 u32 lvds = IS_I830(dev_priv) ? 0 : I915_READ(LVDS);
11394                 bool is_lvds = (pipe == 1) && (lvds & LVDS_PORT_EN);
11395
11396                 if (is_lvds) {
11397                         clock.p1 = ffs((dpll & DPLL_FPA01_P1_POST_DIV_MASK_I830_LVDS) >>
11398                                        DPLL_FPA01_P1_POST_DIV_SHIFT);
11399
11400                         if (lvds & LVDS_CLKB_POWER_UP)
11401                                 clock.p2 = 7;
11402                         else
11403                                 clock.p2 = 14;
11404                 } else {
11405                         if (dpll & PLL_P1_DIVIDE_BY_TWO)
11406                                 clock.p1 = 2;
11407                         else {
11408                                 clock.p1 = ((dpll & DPLL_FPA01_P1_POST_DIV_MASK_I830) >>
11409                                             DPLL_FPA01_P1_POST_DIV_SHIFT) + 2;
11410                         }
11411                         if (dpll & PLL_P2_DIVIDE_BY_4)
11412                                 clock.p2 = 4;
11413                         else
11414                                 clock.p2 = 2;
11415                 }
11416
11417                 port_clock = i9xx_calc_dpll_params(refclk, &clock);
11418         }
11419
11420         /*
11421          * This value includes pixel_multiplier. We will use
11422          * port_clock to compute adjusted_mode.crtc_clock in the
11423          * encoder's get_config() function.
11424          */
11425         pipe_config->port_clock = port_clock;
11426 }
11427
11428 int intel_dotclock_calculate(int link_freq,
11429                              const struct intel_link_m_n *m_n)
11430 {
11431         /*
11432          * The calculation for the data clock is:
11433          * pixel_clock = ((m/n)*(link_clock * nr_lanes))/bpp
11434          * But we want to avoid losing precison if possible, so:
11435          * pixel_clock = ((m * link_clock * nr_lanes)/(n*bpp))
11436          *
11437          * and the link clock is simpler:
11438          * link_clock = (m * link_clock) / n
11439          */
11440
11441         if (!m_n->link_n)
11442                 return 0;
11443
11444         return div_u64((u64)m_n->link_m * link_freq, m_n->link_n);
11445 }
11446
11447 static void ironlake_pch_clock_get(struct intel_crtc *crtc,
11448                                    struct intel_crtc_state *pipe_config)
11449 {
11450         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
11451
11452         /* read out port_clock from the DPLL */
11453         i9xx_crtc_clock_get(crtc, pipe_config);
11454
11455         /*
11456          * In case there is an active pipe without active ports,
11457          * we may need some idea for the dotclock anyway.
11458          * Calculate one based on the FDI configuration.
11459          */
11460         pipe_config->base.adjusted_mode.crtc_clock =
11461                 intel_dotclock_calculate(intel_fdi_link_freq(dev_priv, pipe_config),
11462                                          &pipe_config->fdi_m_n);
11463 }
11464
11465 /** Returns the currently programmed mode of the given pipe. */
11466 struct drm_display_mode *intel_crtc_mode_get(struct drm_device *dev,
11467                                              struct drm_crtc *crtc)
11468 {
11469         struct drm_i915_private *dev_priv = to_i915(dev);
11470         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11471         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
11472         struct drm_display_mode *mode;
11473         struct intel_crtc_state *pipe_config;
11474         int htot = I915_READ(HTOTAL(cpu_transcoder));
11475         int hsync = I915_READ(HSYNC(cpu_transcoder));
11476         int vtot = I915_READ(VTOTAL(cpu_transcoder));
11477         int vsync = I915_READ(VSYNC(cpu_transcoder));
11478         enum pipe pipe = intel_crtc->pipe;
11479
11480         mode = kzalloc(sizeof(*mode), GFP_KERNEL);
11481         if (!mode)
11482                 return NULL;
11483
11484         pipe_config = kzalloc(sizeof(*pipe_config), GFP_KERNEL);
11485         if (!pipe_config) {
11486                 kfree(mode);
11487                 return NULL;
11488         }
11489
11490         /*
11491          * Construct a pipe_config sufficient for getting the clock info
11492          * back out of crtc_clock_get.
11493          *
11494          * Note, if LVDS ever uses a non-1 pixel multiplier, we'll need
11495          * to use a real value here instead.
11496          */
11497         pipe_config->cpu_transcoder = (enum transcoder) pipe;
11498         pipe_config->pixel_multiplier = 1;
11499         pipe_config->dpll_hw_state.dpll = I915_READ(DPLL(pipe));
11500         pipe_config->dpll_hw_state.fp0 = I915_READ(FP0(pipe));
11501         pipe_config->dpll_hw_state.fp1 = I915_READ(FP1(pipe));
11502         i9xx_crtc_clock_get(intel_crtc, pipe_config);
11503
11504         mode->clock = pipe_config->port_clock / pipe_config->pixel_multiplier;
11505         mode->hdisplay = (htot & 0xffff) + 1;
11506         mode->htotal = ((htot & 0xffff0000) >> 16) + 1;
11507         mode->hsync_start = (hsync & 0xffff) + 1;
11508         mode->hsync_end = ((hsync & 0xffff0000) >> 16) + 1;
11509         mode->vdisplay = (vtot & 0xffff) + 1;
11510         mode->vtotal = ((vtot & 0xffff0000) >> 16) + 1;
11511         mode->vsync_start = (vsync & 0xffff) + 1;
11512         mode->vsync_end = ((vsync & 0xffff0000) >> 16) + 1;
11513
11514         drm_mode_set_name(mode);
11515
11516         kfree(pipe_config);
11517
11518         return mode;
11519 }
11520
11521 static void intel_crtc_destroy(struct drm_crtc *crtc)
11522 {
11523         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11524         struct drm_device *dev = crtc->dev;
11525         struct intel_flip_work *work;
11526
11527         spin_lock_irq(&dev->event_lock);
11528         work = intel_crtc->flip_work;
11529         intel_crtc->flip_work = NULL;
11530         spin_unlock_irq(&dev->event_lock);
11531
11532         if (work) {
11533                 cancel_work_sync(&work->mmio_work);
11534                 cancel_work_sync(&work->unpin_work);
11535                 kfree(work);
11536         }
11537
11538         drm_crtc_cleanup(crtc);
11539
11540         kfree(intel_crtc);
11541 }
11542
11543 static void intel_unpin_work_fn(struct work_struct *__work)
11544 {
11545         struct intel_flip_work *work =
11546                 container_of(__work, struct intel_flip_work, unpin_work);
11547         struct intel_crtc *crtc = to_intel_crtc(work->crtc);
11548         struct drm_device *dev = crtc->base.dev;
11549         struct drm_plane *primary = crtc->base.primary;
11550
11551         if (is_mmio_work(work))
11552                 flush_work(&work->mmio_work);
11553
11554         mutex_lock(&dev->struct_mutex);
11555         intel_unpin_fb_vma(work->old_vma);
11556         i915_gem_object_put(work->pending_flip_obj);
11557         mutex_unlock(&dev->struct_mutex);
11558
11559         i915_gem_request_put(work->flip_queued_req);
11560
11561         intel_frontbuffer_flip_complete(to_i915(dev),
11562                                         to_intel_plane(primary)->frontbuffer_bit);
11563         intel_fbc_post_update(crtc);
11564         drm_framebuffer_unreference(work->old_fb);
11565
11566         BUG_ON(atomic_read(&crtc->unpin_work_count) == 0);
11567         atomic_dec(&crtc->unpin_work_count);
11568
11569         kfree(work);
11570 }
11571
11572 /* Is 'a' after or equal to 'b'? */
11573 static bool g4x_flip_count_after_eq(u32 a, u32 b)
11574 {
11575         return !((a - b) & 0x80000000);
11576 }
11577
11578 static bool __pageflip_finished_cs(struct intel_crtc *crtc,
11579                                    struct intel_flip_work *work)
11580 {
11581         struct drm_device *dev = crtc->base.dev;
11582         struct drm_i915_private *dev_priv = to_i915(dev);
11583
11584         if (abort_flip_on_reset(crtc))
11585                 return true;
11586
11587         /*
11588          * The relevant registers doen't exist on pre-ctg.
11589          * As the flip done interrupt doesn't trigger for mmio
11590          * flips on gmch platforms, a flip count check isn't
11591          * really needed there. But since ctg has the registers,
11592          * include it in the check anyway.
11593          */
11594         if (INTEL_GEN(dev_priv) < 5 && !IS_G4X(dev_priv))
11595                 return true;
11596
11597         /*
11598          * BDW signals flip done immediately if the plane
11599          * is disabled, even if the plane enable is already
11600          * armed to occur at the next vblank :(
11601          */
11602
11603         /*
11604          * A DSPSURFLIVE check isn't enough in case the mmio and CS flips
11605          * used the same base address. In that case the mmio flip might
11606          * have completed, but the CS hasn't even executed the flip yet.
11607          *
11608          * A flip count check isn't enough as the CS might have updated
11609          * the base address just after start of vblank, but before we
11610          * managed to process the interrupt. This means we'd complete the
11611          * CS flip too soon.
11612          *
11613          * Combining both checks should get us a good enough result. It may
11614          * still happen that the CS flip has been executed, but has not
11615          * yet actually completed. But in case the base address is the same
11616          * anyway, we don't really care.
11617          */
11618         return (I915_READ(DSPSURFLIVE(crtc->plane)) & ~0xfff) ==
11619                 crtc->flip_work->gtt_offset &&
11620                 g4x_flip_count_after_eq(I915_READ(PIPE_FLIPCOUNT_G4X(crtc->pipe)),
11621                                     crtc->flip_work->flip_count);
11622 }
11623
11624 static bool
11625 __pageflip_finished_mmio(struct intel_crtc *crtc,
11626                                struct intel_flip_work *work)
11627 {
11628         /*
11629          * MMIO work completes when vblank is different from
11630          * flip_queued_vblank.
11631          *
11632          * Reset counter value doesn't matter, this is handled by
11633          * i915_wait_request finishing early, so no need to handle
11634          * reset here.
11635          */
11636         return intel_crtc_get_vblank_counter(crtc) != work->flip_queued_vblank;
11637 }
11638
11639
11640 static bool pageflip_finished(struct intel_crtc *crtc,
11641                               struct intel_flip_work *work)
11642 {
11643         if (!atomic_read(&work->pending))
11644                 return false;
11645
11646         smp_rmb();
11647
11648         if (is_mmio_work(work))
11649                 return __pageflip_finished_mmio(crtc, work);
11650         else
11651                 return __pageflip_finished_cs(crtc, work);
11652 }
11653
11654 void intel_finish_page_flip_cs(struct drm_i915_private *dev_priv, int pipe)
11655 {
11656         struct drm_device *dev = &dev_priv->drm;
11657         struct intel_crtc *crtc = intel_get_crtc_for_pipe(dev_priv, pipe);
11658         struct intel_flip_work *work;
11659         unsigned long flags;
11660
11661         /* Ignore early vblank irqs */
11662         if (!crtc)
11663                 return;
11664
11665         /*
11666          * This is called both by irq handlers and the reset code (to complete
11667          * lost pageflips) so needs the full irqsave spinlocks.
11668          */
11669         spin_lock_irqsave(&dev->event_lock, flags);
11670         work = crtc->flip_work;
11671
11672         if (work != NULL &&
11673             !is_mmio_work(work) &&
11674             pageflip_finished(crtc, work))
11675                 page_flip_completed(crtc);
11676
11677         spin_unlock_irqrestore(&dev->event_lock, flags);
11678 }
11679
11680 void intel_finish_page_flip_mmio(struct drm_i915_private *dev_priv, int pipe)
11681 {
11682         struct drm_device *dev = &dev_priv->drm;
11683         struct intel_crtc *crtc = intel_get_crtc_for_pipe(dev_priv, pipe);
11684         struct intel_flip_work *work;
11685         unsigned long flags;
11686
11687         /* Ignore early vblank irqs */
11688         if (!crtc)
11689                 return;
11690
11691         /*
11692          * This is called both by irq handlers and the reset code (to complete
11693          * lost pageflips) so needs the full irqsave spinlocks.
11694          */
11695         spin_lock_irqsave(&dev->event_lock, flags);
11696         work = crtc->flip_work;
11697
11698         if (work != NULL &&
11699             is_mmio_work(work) &&
11700             pageflip_finished(crtc, work))
11701                 page_flip_completed(crtc);
11702
11703         spin_unlock_irqrestore(&dev->event_lock, flags);
11704 }
11705
11706 static inline void intel_mark_page_flip_active(struct intel_crtc *crtc,
11707                                                struct intel_flip_work *work)
11708 {
11709         work->flip_queued_vblank = intel_crtc_get_vblank_counter(crtc);
11710
11711         /* Ensure that the work item is consistent when activating it ... */
11712         smp_mb__before_atomic();
11713         atomic_set(&work->pending, 1);
11714 }
11715
11716 static int intel_gen2_queue_flip(struct drm_device *dev,
11717                                  struct drm_crtc *crtc,
11718                                  struct drm_framebuffer *fb,
11719                                  struct drm_i915_gem_object *obj,
11720                                  struct drm_i915_gem_request *req,
11721                                  uint32_t flags)
11722 {
11723         struct intel_ring *ring = req->ring;
11724         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11725         u32 flip_mask;
11726         int ret;
11727
11728         ret = intel_ring_begin(req, 6);
11729         if (ret)
11730                 return ret;
11731
11732         /* Can't queue multiple flips, so wait for the previous
11733          * one to finish before executing the next.
11734          */
11735         if (intel_crtc->plane)
11736                 flip_mask = MI_WAIT_FOR_PLANE_B_FLIP;
11737         else
11738                 flip_mask = MI_WAIT_FOR_PLANE_A_FLIP;
11739         intel_ring_emit(ring, MI_WAIT_FOR_EVENT | flip_mask);
11740         intel_ring_emit(ring, MI_NOOP);
11741         intel_ring_emit(ring, MI_DISPLAY_FLIP |
11742                         MI_DISPLAY_FLIP_PLANE(intel_crtc->plane));
11743         intel_ring_emit(ring, fb->pitches[0]);
11744         intel_ring_emit(ring, intel_crtc->flip_work->gtt_offset);
11745         intel_ring_emit(ring, 0); /* aux display base address, unused */
11746
11747         return 0;
11748 }
11749
11750 static int intel_gen3_queue_flip(struct drm_device *dev,
11751                                  struct drm_crtc *crtc,
11752                                  struct drm_framebuffer *fb,
11753                                  struct drm_i915_gem_object *obj,
11754                                  struct drm_i915_gem_request *req,
11755                                  uint32_t flags)
11756 {
11757         struct intel_ring *ring = req->ring;
11758         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11759         u32 flip_mask;
11760         int ret;
11761
11762         ret = intel_ring_begin(req, 6);
11763         if (ret)
11764                 return ret;
11765
11766         if (intel_crtc->plane)
11767                 flip_mask = MI_WAIT_FOR_PLANE_B_FLIP;
11768         else
11769                 flip_mask = MI_WAIT_FOR_PLANE_A_FLIP;
11770         intel_ring_emit(ring, MI_WAIT_FOR_EVENT | flip_mask);
11771         intel_ring_emit(ring, MI_NOOP);
11772         intel_ring_emit(ring, MI_DISPLAY_FLIP_I915 |
11773                         MI_DISPLAY_FLIP_PLANE(intel_crtc->plane));
11774         intel_ring_emit(ring, fb->pitches[0]);
11775         intel_ring_emit(ring, intel_crtc->flip_work->gtt_offset);
11776         intel_ring_emit(ring, MI_NOOP);
11777
11778         return 0;
11779 }
11780
11781 static int intel_gen4_queue_flip(struct drm_device *dev,
11782                                  struct drm_crtc *crtc,
11783                                  struct drm_framebuffer *fb,
11784                                  struct drm_i915_gem_object *obj,
11785                                  struct drm_i915_gem_request *req,
11786                                  uint32_t flags)
11787 {
11788         struct intel_ring *ring = req->ring;
11789         struct drm_i915_private *dev_priv = to_i915(dev);
11790         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11791         uint32_t pf, pipesrc;
11792         int ret;
11793
11794         ret = intel_ring_begin(req, 4);
11795         if (ret)
11796                 return ret;
11797
11798         /* i965+ uses the linear or tiled offsets from the
11799          * Display Registers (which do not change across a page-flip)
11800          * so we need only reprogram the base address.
11801          */
11802         intel_ring_emit(ring, MI_DISPLAY_FLIP |
11803                         MI_DISPLAY_FLIP_PLANE(intel_crtc->plane));
11804         intel_ring_emit(ring, fb->pitches[0]);
11805         intel_ring_emit(ring, intel_crtc->flip_work->gtt_offset |
11806                         intel_fb_modifier_to_tiling(fb->modifier));
11807
11808         /* XXX Enabling the panel-fitter across page-flip is so far
11809          * untested on non-native modes, so ignore it for now.
11810          * pf = I915_READ(pipe == 0 ? PFA_CTL_1 : PFB_CTL_1) & PF_ENABLE;
11811          */
11812         pf = 0;
11813         pipesrc = I915_READ(PIPESRC(intel_crtc->pipe)) & 0x0fff0fff;
11814         intel_ring_emit(ring, pf | pipesrc);
11815
11816         return 0;
11817 }
11818
11819 static int intel_gen6_queue_flip(struct drm_device *dev,
11820                                  struct drm_crtc *crtc,
11821                                  struct drm_framebuffer *fb,
11822                                  struct drm_i915_gem_object *obj,
11823                                  struct drm_i915_gem_request *req,
11824                                  uint32_t flags)
11825 {
11826         struct intel_ring *ring = req->ring;
11827         struct drm_i915_private *dev_priv = to_i915(dev);
11828         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11829         uint32_t pf, pipesrc;
11830         int ret;
11831
11832         ret = intel_ring_begin(req, 4);
11833         if (ret)
11834                 return ret;
11835
11836         intel_ring_emit(ring, MI_DISPLAY_FLIP |
11837                         MI_DISPLAY_FLIP_PLANE(intel_crtc->plane));
11838         intel_ring_emit(ring, fb->pitches[0] |
11839                         intel_fb_modifier_to_tiling(fb->modifier));
11840         intel_ring_emit(ring, intel_crtc->flip_work->gtt_offset);
11841
11842         /* Contrary to the suggestions in the documentation,
11843          * "Enable Panel Fitter" does not seem to be required when page
11844          * flipping with a non-native mode, and worse causes a normal
11845          * modeset to fail.
11846          * pf = I915_READ(PF_CTL(intel_crtc->pipe)) & PF_ENABLE;
11847          */
11848         pf = 0;
11849         pipesrc = I915_READ(PIPESRC(intel_crtc->pipe)) & 0x0fff0fff;
11850         intel_ring_emit(ring, pf | pipesrc);
11851
11852         return 0;
11853 }
11854
11855 static int intel_gen7_queue_flip(struct drm_device *dev,
11856                                  struct drm_crtc *crtc,
11857                                  struct drm_framebuffer *fb,
11858                                  struct drm_i915_gem_object *obj,
11859                                  struct drm_i915_gem_request *req,
11860                                  uint32_t flags)
11861 {
11862         struct drm_i915_private *dev_priv = to_i915(dev);
11863         struct intel_ring *ring = req->ring;
11864         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11865         uint32_t plane_bit = 0;
11866         int len, ret;
11867
11868         switch (intel_crtc->plane) {
11869         case PLANE_A:
11870                 plane_bit = MI_DISPLAY_FLIP_IVB_PLANE_A;
11871                 break;
11872         case PLANE_B:
11873                 plane_bit = MI_DISPLAY_FLIP_IVB_PLANE_B;
11874                 break;
11875         case PLANE_C:
11876                 plane_bit = MI_DISPLAY_FLIP_IVB_PLANE_C;
11877                 break;
11878         default:
11879                 WARN_ONCE(1, "unknown plane in flip command\n");
11880                 return -ENODEV;
11881         }
11882
11883         len = 4;
11884         if (req->engine->id == RCS) {
11885                 len += 6;
11886                 /*
11887                  * On Gen 8, SRM is now taking an extra dword to accommodate
11888                  * 48bits addresses, and we need a NOOP for the batch size to
11889                  * stay even.
11890                  */
11891                 if (IS_GEN8(dev_priv))
11892                         len += 2;
11893         }
11894
11895         /*
11896          * BSpec MI_DISPLAY_FLIP for IVB:
11897          * "The full packet must be contained within the same cache line."
11898          *
11899          * Currently the LRI+SRM+MI_DISPLAY_FLIP all fit within the same
11900          * cacheline, if we ever start emitting more commands before
11901          * the MI_DISPLAY_FLIP we may need to first emit everything else,
11902          * then do the cacheline alignment, and finally emit the
11903          * MI_DISPLAY_FLIP.
11904          */
11905         ret = intel_ring_cacheline_align(req);
11906         if (ret)
11907                 return ret;
11908
11909         ret = intel_ring_begin(req, len);
11910         if (ret)
11911                 return ret;
11912
11913         /* Unmask the flip-done completion message. Note that the bspec says that
11914          * we should do this for both the BCS and RCS, and that we must not unmask
11915          * more than one flip event at any time (or ensure that one flip message
11916          * can be sent by waiting for flip-done prior to queueing new flips).
11917          * Experimentation says that BCS works despite DERRMR masking all
11918          * flip-done completion events and that unmasking all planes at once
11919          * for the RCS also doesn't appear to drop events. Setting the DERRMR
11920          * to zero does lead to lockups within MI_DISPLAY_FLIP.
11921          */
11922         if (req->engine->id == RCS) {
11923                 intel_ring_emit(ring, MI_LOAD_REGISTER_IMM(1));
11924                 intel_ring_emit_reg(ring, DERRMR);
11925                 intel_ring_emit(ring, ~(DERRMR_PIPEA_PRI_FLIP_DONE |
11926                                           DERRMR_PIPEB_PRI_FLIP_DONE |
11927                                           DERRMR_PIPEC_PRI_FLIP_DONE));
11928                 if (IS_GEN8(dev_priv))
11929                         intel_ring_emit(ring, MI_STORE_REGISTER_MEM_GEN8 |
11930                                               MI_SRM_LRM_GLOBAL_GTT);
11931                 else
11932                         intel_ring_emit(ring, MI_STORE_REGISTER_MEM |
11933                                               MI_SRM_LRM_GLOBAL_GTT);
11934                 intel_ring_emit_reg(ring, DERRMR);
11935                 intel_ring_emit(ring,
11936                                 i915_ggtt_offset(req->engine->scratch) + 256);
11937                 if (IS_GEN8(dev_priv)) {
11938                         intel_ring_emit(ring, 0);
11939                         intel_ring_emit(ring, MI_NOOP);
11940                 }
11941         }
11942
11943         intel_ring_emit(ring, MI_DISPLAY_FLIP_I915 | plane_bit);
11944         intel_ring_emit(ring, fb->pitches[0] |
11945                         intel_fb_modifier_to_tiling(fb->modifier));
11946         intel_ring_emit(ring, intel_crtc->flip_work->gtt_offset);
11947         intel_ring_emit(ring, (MI_NOOP));
11948
11949         return 0;
11950 }
11951
11952 static bool use_mmio_flip(struct intel_engine_cs *engine,
11953                           struct drm_i915_gem_object *obj)
11954 {
11955         /*
11956          * This is not being used for older platforms, because
11957          * non-availability of flip done interrupt forces us to use
11958          * CS flips. Older platforms derive flip done using some clever
11959          * tricks involving the flip_pending status bits and vblank irqs.
11960          * So using MMIO flips there would disrupt this mechanism.
11961          */
11962
11963         if (engine == NULL)
11964                 return true;
11965
11966         if (INTEL_GEN(engine->i915) < 5)
11967                 return false;
11968
11969         if (i915.use_mmio_flip < 0)
11970                 return false;
11971         else if (i915.use_mmio_flip > 0)
11972                 return true;
11973         else if (i915.enable_execlists)
11974                 return true;
11975
11976         return engine != i915_gem_object_last_write_engine(obj);
11977 }
11978
11979 static void skl_do_mmio_flip(struct intel_crtc *intel_crtc,
11980                              unsigned int rotation,
11981                              struct intel_flip_work *work)
11982 {
11983         struct drm_device *dev = intel_crtc->base.dev;
11984         struct drm_i915_private *dev_priv = to_i915(dev);
11985         struct drm_framebuffer *fb = intel_crtc->base.primary->fb;
11986         const enum pipe pipe = intel_crtc->pipe;
11987         u32 ctl, stride = skl_plane_stride(fb, 0, rotation);
11988
11989         ctl = I915_READ(PLANE_CTL(pipe, 0));
11990         ctl &= ~PLANE_CTL_TILED_MASK;
11991         switch (fb->modifier) {
11992         case DRM_FORMAT_MOD_NONE:
11993                 break;
11994         case I915_FORMAT_MOD_X_TILED:
11995                 ctl |= PLANE_CTL_TILED_X;
11996                 break;
11997         case I915_FORMAT_MOD_Y_TILED:
11998                 ctl |= PLANE_CTL_TILED_Y;
11999                 break;
12000         case I915_FORMAT_MOD_Yf_TILED:
12001                 ctl |= PLANE_CTL_TILED_YF;
12002                 break;
12003         default:
12004                 MISSING_CASE(fb->modifier);
12005         }
12006
12007         /*
12008          * Both PLANE_CTL and PLANE_STRIDE are not updated on vblank but on
12009          * PLANE_SURF updates, the update is then guaranteed to be atomic.
12010          */
12011         I915_WRITE(PLANE_CTL(pipe, 0), ctl);
12012         I915_WRITE(PLANE_STRIDE(pipe, 0), stride);
12013
12014         I915_WRITE(PLANE_SURF(pipe, 0), work->gtt_offset);
12015         POSTING_READ(PLANE_SURF(pipe, 0));
12016 }
12017
12018 static void ilk_do_mmio_flip(struct intel_crtc *intel_crtc,
12019                              struct intel_flip_work *work)
12020 {
12021         struct drm_device *dev = intel_crtc->base.dev;
12022         struct drm_i915_private *dev_priv = to_i915(dev);
12023         struct drm_framebuffer *fb = intel_crtc->base.primary->fb;
12024         i915_reg_t reg = DSPCNTR(intel_crtc->plane);
12025         u32 dspcntr;
12026
12027         dspcntr = I915_READ(reg);
12028
12029         if (fb->modifier == I915_FORMAT_MOD_X_TILED)
12030                 dspcntr |= DISPPLANE_TILED;
12031         else
12032                 dspcntr &= ~DISPPLANE_TILED;
12033
12034         I915_WRITE(reg, dspcntr);
12035
12036         I915_WRITE(DSPSURF(intel_crtc->plane), work->gtt_offset);
12037         POSTING_READ(DSPSURF(intel_crtc->plane));
12038 }
12039
12040 static void intel_mmio_flip_work_func(struct work_struct *w)
12041 {
12042         struct intel_flip_work *work =
12043                 container_of(w, struct intel_flip_work, mmio_work);
12044         struct intel_crtc *crtc = to_intel_crtc(work->crtc);
12045         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
12046         struct intel_framebuffer *intel_fb =
12047                 to_intel_framebuffer(crtc->base.primary->fb);
12048         struct drm_i915_gem_object *obj = intel_fb->obj;
12049
12050         WARN_ON(i915_gem_object_wait(obj, 0, MAX_SCHEDULE_TIMEOUT, NULL) < 0);
12051
12052         intel_pipe_update_start(crtc);
12053
12054         if (INTEL_GEN(dev_priv) >= 9)
12055                 skl_do_mmio_flip(crtc, work->rotation, work);
12056         else
12057                 /* use_mmio_flip() retricts MMIO flips to ilk+ */
12058                 ilk_do_mmio_flip(crtc, work);
12059
12060         intel_pipe_update_end(crtc, work);
12061 }
12062
12063 static int intel_default_queue_flip(struct drm_device *dev,
12064                                     struct drm_crtc *crtc,
12065                                     struct drm_framebuffer *fb,
12066                                     struct drm_i915_gem_object *obj,
12067                                     struct drm_i915_gem_request *req,
12068                                     uint32_t flags)
12069 {
12070         return -ENODEV;
12071 }
12072
12073 static bool __pageflip_stall_check_cs(struct drm_i915_private *dev_priv,
12074                                       struct intel_crtc *intel_crtc,
12075                                       struct intel_flip_work *work)
12076 {
12077         u32 addr, vblank;
12078
12079         if (!atomic_read(&work->pending))
12080                 return false;
12081
12082         smp_rmb();
12083
12084         vblank = intel_crtc_get_vblank_counter(intel_crtc);
12085         if (work->flip_ready_vblank == 0) {
12086                 if (work->flip_queued_req &&
12087                     !i915_gem_request_completed(work->flip_queued_req))
12088                         return false;
12089
12090                 work->flip_ready_vblank = vblank;
12091         }
12092
12093         if (vblank - work->flip_ready_vblank < 3)
12094                 return false;
12095
12096         /* Potential stall - if we see that the flip has happened,
12097          * assume a missed interrupt. */
12098         if (INTEL_GEN(dev_priv) >= 4)
12099                 addr = I915_HI_DISPBASE(I915_READ(DSPSURF(intel_crtc->plane)));
12100         else
12101                 addr = I915_READ(DSPADDR(intel_crtc->plane));
12102
12103         /* There is a potential issue here with a false positive after a flip
12104          * to the same address. We could address this by checking for a
12105          * non-incrementing frame counter.
12106          */
12107         return addr == work->gtt_offset;
12108 }
12109
12110 void intel_check_page_flip(struct drm_i915_private *dev_priv, int pipe)
12111 {
12112         struct drm_device *dev = &dev_priv->drm;
12113         struct intel_crtc *crtc = intel_get_crtc_for_pipe(dev_priv, pipe);
12114         struct intel_flip_work *work;
12115
12116         WARN_ON(!in_interrupt());
12117
12118         if (crtc == NULL)
12119                 return;
12120
12121         spin_lock(&dev->event_lock);
12122         work = crtc->flip_work;
12123
12124         if (work != NULL && !is_mmio_work(work) &&
12125             __pageflip_stall_check_cs(dev_priv, crtc, work)) {
12126                 WARN_ONCE(1,
12127                           "Kicking stuck page flip: queued at %d, now %d\n",
12128                         work->flip_queued_vblank, intel_crtc_get_vblank_counter(crtc));
12129                 page_flip_completed(crtc);
12130                 work = NULL;
12131         }
12132
12133         if (work != NULL && !is_mmio_work(work) &&
12134             intel_crtc_get_vblank_counter(crtc) - work->flip_queued_vblank > 1)
12135                 intel_queue_rps_boost_for_request(work->flip_queued_req);
12136         spin_unlock(&dev->event_lock);
12137 }
12138
12139 static int intel_crtc_page_flip(struct drm_crtc *crtc,
12140                                 struct drm_framebuffer *fb,
12141                                 struct drm_pending_vblank_event *event,
12142                                 uint32_t page_flip_flags)
12143 {
12144         struct drm_device *dev = crtc->dev;
12145         struct drm_i915_private *dev_priv = to_i915(dev);
12146         struct drm_framebuffer *old_fb = crtc->primary->fb;
12147         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
12148         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
12149         struct drm_plane *primary = crtc->primary;
12150         enum pipe pipe = intel_crtc->pipe;
12151         struct intel_flip_work *work;
12152         struct intel_engine_cs *engine;
12153         bool mmio_flip;
12154         struct drm_i915_gem_request *request;
12155         struct i915_vma *vma;
12156         int ret;
12157
12158         /*
12159          * drm_mode_page_flip_ioctl() should already catch this, but double
12160          * check to be safe.  In the future we may enable pageflipping from
12161          * a disabled primary plane.
12162          */
12163         if (WARN_ON(intel_fb_obj(old_fb) == NULL))
12164                 return -EBUSY;
12165
12166         /* Can't change pixel format via MI display flips. */
12167         if (fb->format != crtc->primary->fb->format)
12168                 return -EINVAL;
12169
12170         /*
12171          * TILEOFF/LINOFF registers can't be changed via MI display flips.
12172          * Note that pitch changes could also affect these register.
12173          */
12174         if (INTEL_GEN(dev_priv) > 3 &&
12175             (fb->offsets[0] != crtc->primary->fb->offsets[0] ||
12176              fb->pitches[0] != crtc->primary->fb->pitches[0]))
12177                 return -EINVAL;
12178
12179         if (i915_terminally_wedged(&dev_priv->gpu_error))
12180                 goto out_hang;
12181
12182         work = kzalloc(sizeof(*work), GFP_KERNEL);
12183         if (work == NULL)
12184                 return -ENOMEM;
12185
12186         work->event = event;
12187         work->crtc = crtc;
12188         work->old_fb = old_fb;
12189         INIT_WORK(&work->unpin_work, intel_unpin_work_fn);
12190
12191         ret = drm_crtc_vblank_get(crtc);
12192         if (ret)
12193                 goto free_work;
12194
12195         /* We borrow the event spin lock for protecting flip_work */
12196         spin_lock_irq(&dev->event_lock);
12197         if (intel_crtc->flip_work) {
12198                 /* Before declaring the flip queue wedged, check if
12199                  * the hardware completed the operation behind our backs.
12200                  */
12201                 if (pageflip_finished(intel_crtc, intel_crtc->flip_work)) {
12202                         DRM_DEBUG_DRIVER("flip queue: previous flip completed, continuing\n");
12203                         page_flip_completed(intel_crtc);
12204                 } else {
12205                         DRM_DEBUG_DRIVER("flip queue: crtc already busy\n");
12206                         spin_unlock_irq(&dev->event_lock);
12207
12208                         drm_crtc_vblank_put(crtc);
12209                         kfree(work);
12210                         return -EBUSY;
12211                 }
12212         }
12213         intel_crtc->flip_work = work;
12214         spin_unlock_irq(&dev->event_lock);
12215
12216         if (atomic_read(&intel_crtc->unpin_work_count) >= 2)
12217                 flush_workqueue(dev_priv->wq);
12218
12219         /* Reference the objects for the scheduled work. */
12220         drm_framebuffer_reference(work->old_fb);
12221
12222         crtc->primary->fb = fb;
12223         update_state_fb(crtc->primary);
12224
12225         work->pending_flip_obj = i915_gem_object_get(obj);
12226
12227         ret = i915_mutex_lock_interruptible(dev);
12228         if (ret)
12229                 goto cleanup;
12230
12231         intel_crtc->reset_count = i915_reset_count(&dev_priv->gpu_error);
12232         if (i915_reset_in_progress_or_wedged(&dev_priv->gpu_error)) {
12233                 ret = -EIO;
12234                 goto unlock;
12235         }
12236
12237         atomic_inc(&intel_crtc->unpin_work_count);
12238
12239         if (INTEL_GEN(dev_priv) >= 5 || IS_G4X(dev_priv))
12240                 work->flip_count = I915_READ(PIPE_FLIPCOUNT_G4X(pipe)) + 1;
12241
12242         if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv)) {
12243                 engine = dev_priv->engine[BCS];
12244                 if (fb->modifier != old_fb->modifier)
12245                         /* vlv: DISPLAY_FLIP fails to change tiling */
12246                         engine = NULL;
12247         } else if (IS_IVYBRIDGE(dev_priv) || IS_HASWELL(dev_priv)) {
12248                 engine = dev_priv->engine[BCS];
12249         } else if (INTEL_GEN(dev_priv) >= 7) {
12250                 engine = i915_gem_object_last_write_engine(obj);
12251                 if (engine == NULL || engine->id != RCS)
12252                         engine = dev_priv->engine[BCS];
12253         } else {
12254                 engine = dev_priv->engine[RCS];
12255         }
12256
12257         mmio_flip = use_mmio_flip(engine, obj);
12258
12259         vma = intel_pin_and_fence_fb_obj(fb, primary->state->rotation);
12260         if (IS_ERR(vma)) {
12261                 ret = PTR_ERR(vma);
12262                 goto cleanup_pending;
12263         }
12264
12265         work->old_vma = to_intel_plane_state(primary->state)->vma;
12266         to_intel_plane_state(primary->state)->vma = vma;
12267
12268         work->gtt_offset = i915_ggtt_offset(vma) + intel_crtc->dspaddr_offset;
12269         work->rotation = crtc->primary->state->rotation;
12270
12271         /*
12272          * There's the potential that the next frame will not be compatible with
12273          * FBC, so we want to call pre_update() before the actual page flip.
12274          * The problem is that pre_update() caches some information about the fb
12275          * object, so we want to do this only after the object is pinned. Let's
12276          * be on the safe side and do this immediately before scheduling the
12277          * flip.
12278          */
12279         intel_fbc_pre_update(intel_crtc, intel_crtc->config,
12280                              to_intel_plane_state(primary->state));
12281
12282         if (mmio_flip) {
12283                 INIT_WORK(&work->mmio_work, intel_mmio_flip_work_func);
12284                 queue_work(system_unbound_wq, &work->mmio_work);
12285         } else {
12286                 request = i915_gem_request_alloc(engine,
12287                                                  dev_priv->kernel_context);
12288                 if (IS_ERR(request)) {
12289                         ret = PTR_ERR(request);
12290                         goto cleanup_unpin;
12291                 }
12292
12293                 ret = i915_gem_request_await_object(request, obj, false);
12294                 if (ret)
12295                         goto cleanup_request;
12296
12297                 ret = dev_priv->display.queue_flip(dev, crtc, fb, obj, request,
12298                                                    page_flip_flags);
12299                 if (ret)
12300                         goto cleanup_request;
12301
12302                 intel_mark_page_flip_active(intel_crtc, work);
12303
12304                 work->flip_queued_req = i915_gem_request_get(request);
12305                 i915_add_request_no_flush(request);
12306         }
12307
12308         i915_gem_object_wait_priority(obj, 0, I915_PRIORITY_DISPLAY);
12309         i915_gem_track_fb(intel_fb_obj(old_fb), obj,
12310                           to_intel_plane(primary)->frontbuffer_bit);
12311         mutex_unlock(&dev->struct_mutex);
12312
12313         intel_frontbuffer_flip_prepare(to_i915(dev),
12314                                        to_intel_plane(primary)->frontbuffer_bit);
12315
12316         trace_i915_flip_request(intel_crtc->plane, obj);
12317
12318         return 0;
12319
12320 cleanup_request:
12321         i915_add_request_no_flush(request);
12322 cleanup_unpin:
12323         to_intel_plane_state(primary->state)->vma = work->old_vma;
12324         intel_unpin_fb_vma(vma);
12325 cleanup_pending:
12326         atomic_dec(&intel_crtc->unpin_work_count);
12327 unlock:
12328         mutex_unlock(&dev->struct_mutex);
12329 cleanup:
12330         crtc->primary->fb = old_fb;
12331         update_state_fb(crtc->primary);
12332
12333         i915_gem_object_put(obj);
12334         drm_framebuffer_unreference(work->old_fb);
12335
12336         spin_lock_irq(&dev->event_lock);
12337         intel_crtc->flip_work = NULL;
12338         spin_unlock_irq(&dev->event_lock);
12339
12340         drm_crtc_vblank_put(crtc);
12341 free_work:
12342         kfree(work);
12343
12344         if (ret == -EIO) {
12345                 struct drm_atomic_state *state;
12346                 struct drm_plane_state *plane_state;
12347
12348 out_hang:
12349                 state = drm_atomic_state_alloc(dev);
12350                 if (!state)
12351                         return -ENOMEM;
12352                 state->acquire_ctx = drm_modeset_legacy_acquire_ctx(crtc);
12353
12354 retry:
12355                 plane_state = drm_atomic_get_plane_state(state, primary);
12356                 ret = PTR_ERR_OR_ZERO(plane_state);
12357                 if (!ret) {
12358                         drm_atomic_set_fb_for_plane(plane_state, fb);
12359
12360                         ret = drm_atomic_set_crtc_for_plane(plane_state, crtc);
12361                         if (!ret)
12362                                 ret = drm_atomic_commit(state);
12363                 }
12364
12365                 if (ret == -EDEADLK) {
12366                         drm_modeset_backoff(state->acquire_ctx);
12367                         drm_atomic_state_clear(state);
12368                         goto retry;
12369                 }
12370
12371                 drm_atomic_state_put(state);
12372
12373                 if (ret == 0 && event) {
12374                         spin_lock_irq(&dev->event_lock);
12375                         drm_crtc_send_vblank_event(crtc, event);
12376                         spin_unlock_irq(&dev->event_lock);
12377                 }
12378         }
12379         return ret;
12380 }
12381
12382
12383 /**
12384  * intel_wm_need_update - Check whether watermarks need updating
12385  * @plane: drm plane
12386  * @state: new plane state
12387  *
12388  * Check current plane state versus the new one to determine whether
12389  * watermarks need to be recalculated.
12390  *
12391  * Returns true or false.
12392  */
12393 static bool intel_wm_need_update(struct drm_plane *plane,
12394                                  struct drm_plane_state *state)
12395 {
12396         struct intel_plane_state *new = to_intel_plane_state(state);
12397         struct intel_plane_state *cur = to_intel_plane_state(plane->state);
12398
12399         /* Update watermarks on tiling or size changes. */
12400         if (new->base.visible != cur->base.visible)
12401                 return true;
12402
12403         if (!cur->base.fb || !new->base.fb)
12404                 return false;
12405
12406         if (cur->base.fb->modifier != new->base.fb->modifier ||
12407             cur->base.rotation != new->base.rotation ||
12408             drm_rect_width(&new->base.src) != drm_rect_width(&cur->base.src) ||
12409             drm_rect_height(&new->base.src) != drm_rect_height(&cur->base.src) ||
12410             drm_rect_width(&new->base.dst) != drm_rect_width(&cur->base.dst) ||
12411             drm_rect_height(&new->base.dst) != drm_rect_height(&cur->base.dst))
12412                 return true;
12413
12414         return false;
12415 }
12416
12417 static bool needs_scaling(struct intel_plane_state *state)
12418 {
12419         int src_w = drm_rect_width(&state->base.src) >> 16;
12420         int src_h = drm_rect_height(&state->base.src) >> 16;
12421         int dst_w = drm_rect_width(&state->base.dst);
12422         int dst_h = drm_rect_height(&state->base.dst);
12423
12424         return (src_w != dst_w || src_h != dst_h);
12425 }
12426
12427 int intel_plane_atomic_calc_changes(struct drm_crtc_state *crtc_state,
12428                                     struct drm_plane_state *plane_state)
12429 {
12430         struct intel_crtc_state *pipe_config = to_intel_crtc_state(crtc_state);
12431         struct drm_crtc *crtc = crtc_state->crtc;
12432         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
12433         struct drm_plane *plane = plane_state->plane;
12434         struct drm_device *dev = crtc->dev;
12435         struct drm_i915_private *dev_priv = to_i915(dev);
12436         struct intel_plane_state *old_plane_state =
12437                 to_intel_plane_state(plane->state);
12438         bool mode_changed = needs_modeset(crtc_state);
12439         bool was_crtc_enabled = crtc->state->active;
12440         bool is_crtc_enabled = crtc_state->active;
12441         bool turn_off, turn_on, visible, was_visible;
12442         struct drm_framebuffer *fb = plane_state->fb;
12443         int ret;
12444
12445         if (INTEL_GEN(dev_priv) >= 9 && plane->type != DRM_PLANE_TYPE_CURSOR) {
12446                 ret = skl_update_scaler_plane(
12447                         to_intel_crtc_state(crtc_state),
12448                         to_intel_plane_state(plane_state));
12449                 if (ret)
12450                         return ret;
12451         }
12452
12453         was_visible = old_plane_state->base.visible;
12454         visible = plane_state->visible;
12455
12456         if (!was_crtc_enabled && WARN_ON(was_visible))
12457                 was_visible = false;
12458
12459         /*
12460          * Visibility is calculated as if the crtc was on, but
12461          * after scaler setup everything depends on it being off
12462          * when the crtc isn't active.
12463          *
12464          * FIXME this is wrong for watermarks. Watermarks should also
12465          * be computed as if the pipe would be active. Perhaps move
12466          * per-plane wm computation to the .check_plane() hook, and
12467          * only combine the results from all planes in the current place?
12468          */
12469         if (!is_crtc_enabled)
12470                 plane_state->visible = visible = false;
12471
12472         if (!was_visible && !visible)
12473                 return 0;
12474
12475         if (fb != old_plane_state->base.fb)
12476                 pipe_config->fb_changed = true;
12477
12478         turn_off = was_visible && (!visible || mode_changed);
12479         turn_on = visible && (!was_visible || mode_changed);
12480
12481         DRM_DEBUG_ATOMIC("[CRTC:%d:%s] has [PLANE:%d:%s] with fb %i\n",
12482                          intel_crtc->base.base.id,
12483                          intel_crtc->base.name,
12484                          plane->base.id, plane->name,
12485                          fb ? fb->base.id : -1);
12486
12487         DRM_DEBUG_ATOMIC("[PLANE:%d:%s] visible %i -> %i, off %i, on %i, ms %i\n",
12488                          plane->base.id, plane->name,
12489                          was_visible, visible,
12490                          turn_off, turn_on, mode_changed);
12491
12492         if (turn_on) {
12493                 pipe_config->update_wm_pre = true;
12494
12495                 /* must disable cxsr around plane enable/disable */
12496                 if (plane->type != DRM_PLANE_TYPE_CURSOR)
12497                         pipe_config->disable_cxsr = true;
12498         } else if (turn_off) {
12499                 pipe_config->update_wm_post = true;
12500
12501                 /* must disable cxsr around plane enable/disable */
12502                 if (plane->type != DRM_PLANE_TYPE_CURSOR)
12503                         pipe_config->disable_cxsr = true;
12504         } else if (intel_wm_need_update(plane, plane_state)) {
12505                 /* FIXME bollocks */
12506                 pipe_config->update_wm_pre = true;
12507                 pipe_config->update_wm_post = true;
12508         }
12509
12510         /* Pre-gen9 platforms need two-step watermark updates */
12511         if ((pipe_config->update_wm_pre || pipe_config->update_wm_post) &&
12512             INTEL_GEN(dev_priv) < 9 && dev_priv->display.optimize_watermarks)
12513                 to_intel_crtc_state(crtc_state)->wm.need_postvbl_update = true;
12514
12515         if (visible || was_visible)
12516                 pipe_config->fb_bits |= to_intel_plane(plane)->frontbuffer_bit;
12517
12518         /*
12519          * WaCxSRDisabledForSpriteScaling:ivb
12520          *
12521          * cstate->update_wm was already set above, so this flag will
12522          * take effect when we commit and program watermarks.
12523          */
12524         if (plane->type == DRM_PLANE_TYPE_OVERLAY && IS_IVYBRIDGE(dev_priv) &&
12525             needs_scaling(to_intel_plane_state(plane_state)) &&
12526             !needs_scaling(old_plane_state))
12527                 pipe_config->disable_lp_wm = true;
12528
12529         return 0;
12530 }
12531
12532 static bool encoders_cloneable(const struct intel_encoder *a,
12533                                const struct intel_encoder *b)
12534 {
12535         /* masks could be asymmetric, so check both ways */
12536         return a == b || (a->cloneable & (1 << b->type) &&
12537                           b->cloneable & (1 << a->type));
12538 }
12539
12540 static bool check_single_encoder_cloning(struct drm_atomic_state *state,
12541                                          struct intel_crtc *crtc,
12542                                          struct intel_encoder *encoder)
12543 {
12544         struct intel_encoder *source_encoder;
12545         struct drm_connector *connector;
12546         struct drm_connector_state *connector_state;
12547         int i;
12548
12549         for_each_connector_in_state(state, connector, connector_state, i) {
12550                 if (connector_state->crtc != &crtc->base)
12551                         continue;
12552
12553                 source_encoder =
12554                         to_intel_encoder(connector_state->best_encoder);
12555                 if (!encoders_cloneable(encoder, source_encoder))
12556                         return false;
12557         }
12558
12559         return true;
12560 }
12561
12562 static int intel_crtc_atomic_check(struct drm_crtc *crtc,
12563                                    struct drm_crtc_state *crtc_state)
12564 {
12565         struct drm_device *dev = crtc->dev;
12566         struct drm_i915_private *dev_priv = to_i915(dev);
12567         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
12568         struct intel_crtc_state *pipe_config =
12569                 to_intel_crtc_state(crtc_state);
12570         struct drm_atomic_state *state = crtc_state->state;
12571         int ret;
12572         bool mode_changed = needs_modeset(crtc_state);
12573
12574         if (mode_changed && !crtc_state->active)
12575                 pipe_config->update_wm_post = true;
12576
12577         if (mode_changed && crtc_state->enable &&
12578             dev_priv->display.crtc_compute_clock &&
12579             !WARN_ON(pipe_config->shared_dpll)) {
12580                 ret = dev_priv->display.crtc_compute_clock(intel_crtc,
12581                                                            pipe_config);
12582                 if (ret)
12583                         return ret;
12584         }
12585
12586         if (crtc_state->color_mgmt_changed) {
12587                 ret = intel_color_check(crtc, crtc_state);
12588                 if (ret)
12589                         return ret;
12590
12591                 /*
12592                  * Changing color management on Intel hardware is
12593                  * handled as part of planes update.
12594                  */
12595                 crtc_state->planes_changed = true;
12596         }
12597
12598         ret = 0;
12599         if (dev_priv->display.compute_pipe_wm) {
12600                 ret = dev_priv->display.compute_pipe_wm(pipe_config);
12601                 if (ret) {
12602                         DRM_DEBUG_KMS("Target pipe watermarks are invalid\n");
12603                         return ret;
12604                 }
12605         }
12606
12607         if (dev_priv->display.compute_intermediate_wm &&
12608             !to_intel_atomic_state(state)->skip_intermediate_wm) {
12609                 if (WARN_ON(!dev_priv->display.compute_pipe_wm))
12610                         return 0;
12611
12612                 /*
12613                  * Calculate 'intermediate' watermarks that satisfy both the
12614                  * old state and the new state.  We can program these
12615                  * immediately.
12616                  */
12617                 ret = dev_priv->display.compute_intermediate_wm(dev,
12618                                                                 intel_crtc,
12619                                                                 pipe_config);
12620                 if (ret) {
12621                         DRM_DEBUG_KMS("No valid intermediate pipe watermarks are possible\n");
12622                         return ret;
12623                 }
12624         } else if (dev_priv->display.compute_intermediate_wm) {
12625                 if (HAS_PCH_SPLIT(dev_priv) && INTEL_GEN(dev_priv) < 9)
12626                         pipe_config->wm.ilk.intermediate = pipe_config->wm.ilk.optimal;
12627         }
12628
12629         if (INTEL_GEN(dev_priv) >= 9) {
12630                 if (mode_changed)
12631                         ret = skl_update_scaler_crtc(pipe_config);
12632
12633                 if (!ret)
12634                         ret = intel_atomic_setup_scalers(dev, intel_crtc,
12635                                                          pipe_config);
12636         }
12637
12638         return ret;
12639 }
12640
12641 static const struct drm_crtc_helper_funcs intel_helper_funcs = {
12642         .mode_set_base_atomic = intel_pipe_set_base_atomic,
12643         .atomic_begin = intel_begin_crtc_commit,
12644         .atomic_flush = intel_finish_crtc_commit,
12645         .atomic_check = intel_crtc_atomic_check,
12646 };
12647
12648 static void intel_modeset_update_connector_atomic_state(struct drm_device *dev)
12649 {
12650         struct intel_connector *connector;
12651
12652         for_each_intel_connector(dev, connector) {
12653                 if (connector->base.state->crtc)
12654                         drm_connector_unreference(&connector->base);
12655
12656                 if (connector->base.encoder) {
12657                         connector->base.state->best_encoder =
12658                                 connector->base.encoder;
12659                         connector->base.state->crtc =
12660                                 connector->base.encoder->crtc;
12661
12662                         drm_connector_reference(&connector->base);
12663                 } else {
12664                         connector->base.state->best_encoder = NULL;
12665                         connector->base.state->crtc = NULL;
12666                 }
12667         }
12668 }
12669
12670 static void
12671 connected_sink_compute_bpp(struct intel_connector *connector,
12672                            struct intel_crtc_state *pipe_config)
12673 {
12674         const struct drm_display_info *info = &connector->base.display_info;
12675         int bpp = pipe_config->pipe_bpp;
12676
12677         DRM_DEBUG_KMS("[CONNECTOR:%d:%s] checking for sink bpp constrains\n",
12678                       connector->base.base.id,
12679                       connector->base.name);
12680
12681         /* Don't use an invalid EDID bpc value */
12682         if (info->bpc != 0 && info->bpc * 3 < bpp) {
12683                 DRM_DEBUG_KMS("clamping display bpp (was %d) to EDID reported max of %d\n",
12684                               bpp, info->bpc * 3);
12685                 pipe_config->pipe_bpp = info->bpc * 3;
12686         }
12687
12688         /* Clamp bpp to 8 on screens without EDID 1.4 */
12689         if (info->bpc == 0 && bpp > 24) {
12690                 DRM_DEBUG_KMS("clamping display bpp (was %d) to default limit of 24\n",
12691                               bpp);
12692                 pipe_config->pipe_bpp = 24;
12693         }
12694 }
12695
12696 static int
12697 compute_baseline_pipe_bpp(struct intel_crtc *crtc,
12698                           struct intel_crtc_state *pipe_config)
12699 {
12700         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
12701         struct drm_atomic_state *state;
12702         struct drm_connector *connector;
12703         struct drm_connector_state *connector_state;
12704         int bpp, i;
12705
12706         if ((IS_G4X(dev_priv) || IS_VALLEYVIEW(dev_priv) ||
12707             IS_CHERRYVIEW(dev_priv)))
12708                 bpp = 10*3;
12709         else if (INTEL_GEN(dev_priv) >= 5)
12710                 bpp = 12*3;
12711         else
12712                 bpp = 8*3;
12713
12714
12715         pipe_config->pipe_bpp = bpp;
12716
12717         state = pipe_config->base.state;
12718
12719         /* Clamp display bpp to EDID value */
12720         for_each_connector_in_state(state, connector, connector_state, i) {
12721                 if (connector_state->crtc != &crtc->base)
12722                         continue;
12723
12724                 connected_sink_compute_bpp(to_intel_connector(connector),
12725                                            pipe_config);
12726         }
12727
12728         return bpp;
12729 }
12730
12731 static void intel_dump_crtc_timings(const struct drm_display_mode *mode)
12732 {
12733         DRM_DEBUG_KMS("crtc timings: %d %d %d %d %d %d %d %d %d, "
12734                         "type: 0x%x flags: 0x%x\n",
12735                 mode->crtc_clock,
12736                 mode->crtc_hdisplay, mode->crtc_hsync_start,
12737                 mode->crtc_hsync_end, mode->crtc_htotal,
12738                 mode->crtc_vdisplay, mode->crtc_vsync_start,
12739                 mode->crtc_vsync_end, mode->crtc_vtotal, mode->type, mode->flags);
12740 }
12741
12742 static inline void
12743 intel_dump_m_n_config(struct intel_crtc_state *pipe_config, char *id,
12744                       unsigned int lane_count, struct intel_link_m_n *m_n)
12745 {
12746         DRM_DEBUG_KMS("%s: lanes: %i; gmch_m: %u, gmch_n: %u, link_m: %u, link_n: %u, tu: %u\n",
12747                       id, lane_count,
12748                       m_n->gmch_m, m_n->gmch_n,
12749                       m_n->link_m, m_n->link_n, m_n->tu);
12750 }
12751
12752 static void intel_dump_pipe_config(struct intel_crtc *crtc,
12753                                    struct intel_crtc_state *pipe_config,
12754                                    const char *context)
12755 {
12756         struct drm_device *dev = crtc->base.dev;
12757         struct drm_i915_private *dev_priv = to_i915(dev);
12758         struct drm_plane *plane;
12759         struct intel_plane *intel_plane;
12760         struct intel_plane_state *state;
12761         struct drm_framebuffer *fb;
12762
12763         DRM_DEBUG_KMS("[CRTC:%d:%s]%s\n",
12764                       crtc->base.base.id, crtc->base.name, context);
12765
12766         DRM_DEBUG_KMS("cpu_transcoder: %s, pipe bpp: %i, dithering: %i\n",
12767                       transcoder_name(pipe_config->cpu_transcoder),
12768                       pipe_config->pipe_bpp, pipe_config->dither);
12769
12770         if (pipe_config->has_pch_encoder)
12771                 intel_dump_m_n_config(pipe_config, "fdi",
12772                                       pipe_config->fdi_lanes,
12773                                       &pipe_config->fdi_m_n);
12774
12775         if (intel_crtc_has_dp_encoder(pipe_config)) {
12776                 intel_dump_m_n_config(pipe_config, "dp m_n",
12777                                 pipe_config->lane_count, &pipe_config->dp_m_n);
12778                 if (pipe_config->has_drrs)
12779                         intel_dump_m_n_config(pipe_config, "dp m2_n2",
12780                                               pipe_config->lane_count,
12781                                               &pipe_config->dp_m2_n2);
12782         }
12783
12784         DRM_DEBUG_KMS("audio: %i, infoframes: %i\n",
12785                       pipe_config->has_audio, pipe_config->has_infoframe);
12786
12787         DRM_DEBUG_KMS("requested mode:\n");
12788         drm_mode_debug_printmodeline(&pipe_config->base.mode);
12789         DRM_DEBUG_KMS("adjusted mode:\n");
12790         drm_mode_debug_printmodeline(&pipe_config->base.adjusted_mode);
12791         intel_dump_crtc_timings(&pipe_config->base.adjusted_mode);
12792         DRM_DEBUG_KMS("port clock: %d, pipe src size: %dx%d\n",
12793                       pipe_config->port_clock,
12794                       pipe_config->pipe_src_w, pipe_config->pipe_src_h);
12795
12796         if (INTEL_GEN(dev_priv) >= 9)
12797                 DRM_DEBUG_KMS("num_scalers: %d, scaler_users: 0x%x, scaler_id: %d\n",
12798                               crtc->num_scalers,
12799                               pipe_config->scaler_state.scaler_users,
12800                               pipe_config->scaler_state.scaler_id);
12801
12802         if (HAS_GMCH_DISPLAY(dev_priv))
12803                 DRM_DEBUG_KMS("gmch pfit: control: 0x%08x, ratios: 0x%08x, lvds border: 0x%08x\n",
12804                               pipe_config->gmch_pfit.control,
12805                               pipe_config->gmch_pfit.pgm_ratios,
12806                               pipe_config->gmch_pfit.lvds_border_bits);
12807         else
12808                 DRM_DEBUG_KMS("pch pfit: pos: 0x%08x, size: 0x%08x, %s\n",
12809                               pipe_config->pch_pfit.pos,
12810                               pipe_config->pch_pfit.size,
12811                               enableddisabled(pipe_config->pch_pfit.enabled));
12812
12813         DRM_DEBUG_KMS("ips: %i, double wide: %i\n",
12814                       pipe_config->ips_enabled, pipe_config->double_wide);
12815
12816         intel_dpll_dump_hw_state(dev_priv, &pipe_config->dpll_hw_state);
12817
12818         DRM_DEBUG_KMS("planes on this crtc\n");
12819         list_for_each_entry(plane, &dev->mode_config.plane_list, head) {
12820                 struct drm_format_name_buf format_name;
12821                 intel_plane = to_intel_plane(plane);
12822                 if (intel_plane->pipe != crtc->pipe)
12823                         continue;
12824
12825                 state = to_intel_plane_state(plane->state);
12826                 fb = state->base.fb;
12827                 if (!fb) {
12828                         DRM_DEBUG_KMS("[PLANE:%d:%s] disabled, scaler_id = %d\n",
12829                                       plane->base.id, plane->name, state->scaler_id);
12830                         continue;
12831                 }
12832
12833                 DRM_DEBUG_KMS("[PLANE:%d:%s] FB:%d, fb = %ux%u format = %s\n",
12834                               plane->base.id, plane->name,
12835                               fb->base.id, fb->width, fb->height,
12836                               drm_get_format_name(fb->format->format, &format_name));
12837                 if (INTEL_GEN(dev_priv) >= 9)
12838                         DRM_DEBUG_KMS("\tscaler:%d src %dx%d+%d+%d dst %dx%d+%d+%d\n",
12839                                       state->scaler_id,
12840                                       state->base.src.x1 >> 16,
12841                                       state->base.src.y1 >> 16,
12842                                       drm_rect_width(&state->base.src) >> 16,
12843                                       drm_rect_height(&state->base.src) >> 16,
12844                                       state->base.dst.x1, state->base.dst.y1,
12845                                       drm_rect_width(&state->base.dst),
12846                                       drm_rect_height(&state->base.dst));
12847         }
12848 }
12849
12850 static bool check_digital_port_conflicts(struct drm_atomic_state *state)
12851 {
12852         struct drm_device *dev = state->dev;
12853         struct drm_connector *connector;
12854         unsigned int used_ports = 0;
12855         unsigned int used_mst_ports = 0;
12856
12857         /*
12858          * Walk the connector list instead of the encoder
12859          * list to detect the problem on ddi platforms
12860          * where there's just one encoder per digital port.
12861          */
12862         drm_for_each_connector(connector, dev) {
12863                 struct drm_connector_state *connector_state;
12864                 struct intel_encoder *encoder;
12865
12866                 connector_state = drm_atomic_get_existing_connector_state(state, connector);
12867                 if (!connector_state)
12868                         connector_state = connector->state;
12869
12870                 if (!connector_state->best_encoder)
12871                         continue;
12872
12873                 encoder = to_intel_encoder(connector_state->best_encoder);
12874
12875                 WARN_ON(!connector_state->crtc);
12876
12877                 switch (encoder->type) {
12878                         unsigned int port_mask;
12879                 case INTEL_OUTPUT_UNKNOWN:
12880                         if (WARN_ON(!HAS_DDI(to_i915(dev))))
12881                                 break;
12882                 case INTEL_OUTPUT_DP:
12883                 case INTEL_OUTPUT_HDMI:
12884                 case INTEL_OUTPUT_EDP:
12885                         port_mask = 1 << enc_to_dig_port(&encoder->base)->port;
12886
12887                         /* the same port mustn't appear more than once */
12888                         if (used_ports & port_mask)
12889                                 return false;
12890
12891                         used_ports |= port_mask;
12892                         break;
12893                 case INTEL_OUTPUT_DP_MST:
12894                         used_mst_ports |=
12895                                 1 << enc_to_mst(&encoder->base)->primary->port;
12896                         break;
12897                 default:
12898                         break;
12899                 }
12900         }
12901
12902         /* can't mix MST and SST/HDMI on the same port */
12903         if (used_ports & used_mst_ports)
12904                 return false;
12905
12906         return true;
12907 }
12908
12909 static void
12910 clear_intel_crtc_state(struct intel_crtc_state *crtc_state)
12911 {
12912         struct drm_crtc_state tmp_state;
12913         struct intel_crtc_scaler_state scaler_state;
12914         struct intel_dpll_hw_state dpll_hw_state;
12915         struct intel_shared_dpll *shared_dpll;
12916         bool force_thru;
12917
12918         /* FIXME: before the switch to atomic started, a new pipe_config was
12919          * kzalloc'd. Code that depends on any field being zero should be
12920          * fixed, so that the crtc_state can be safely duplicated. For now,
12921          * only fields that are know to not cause problems are preserved. */
12922
12923         tmp_state = crtc_state->base;
12924         scaler_state = crtc_state->scaler_state;
12925         shared_dpll = crtc_state->shared_dpll;
12926         dpll_hw_state = crtc_state->dpll_hw_state;
12927         force_thru = crtc_state->pch_pfit.force_thru;
12928
12929         memset(crtc_state, 0, sizeof *crtc_state);
12930
12931         crtc_state->base = tmp_state;
12932         crtc_state->scaler_state = scaler_state;
12933         crtc_state->shared_dpll = shared_dpll;
12934         crtc_state->dpll_hw_state = dpll_hw_state;
12935         crtc_state->pch_pfit.force_thru = force_thru;
12936 }
12937
12938 static int
12939 intel_modeset_pipe_config(struct drm_crtc *crtc,
12940                           struct intel_crtc_state *pipe_config)
12941 {
12942         struct drm_atomic_state *state = pipe_config->base.state;
12943         struct intel_encoder *encoder;
12944         struct drm_connector *connector;
12945         struct drm_connector_state *connector_state;
12946         int base_bpp, ret = -EINVAL;
12947         int i;
12948         bool retry = true;
12949
12950         clear_intel_crtc_state(pipe_config);
12951
12952         pipe_config->cpu_transcoder =
12953                 (enum transcoder) to_intel_crtc(crtc)->pipe;
12954
12955         /*
12956          * Sanitize sync polarity flags based on requested ones. If neither
12957          * positive or negative polarity is requested, treat this as meaning
12958          * negative polarity.
12959          */
12960         if (!(pipe_config->base.adjusted_mode.flags &
12961               (DRM_MODE_FLAG_PHSYNC | DRM_MODE_FLAG_NHSYNC)))
12962                 pipe_config->base.adjusted_mode.flags |= DRM_MODE_FLAG_NHSYNC;
12963
12964         if (!(pipe_config->base.adjusted_mode.flags &
12965               (DRM_MODE_FLAG_PVSYNC | DRM_MODE_FLAG_NVSYNC)))
12966                 pipe_config->base.adjusted_mode.flags |= DRM_MODE_FLAG_NVSYNC;
12967
12968         base_bpp = compute_baseline_pipe_bpp(to_intel_crtc(crtc),
12969                                              pipe_config);
12970         if (base_bpp < 0)
12971                 goto fail;
12972
12973         /*
12974          * Determine the real pipe dimensions. Note that stereo modes can
12975          * increase the actual pipe size due to the frame doubling and
12976          * insertion of additional space for blanks between the frame. This
12977          * is stored in the crtc timings. We use the requested mode to do this
12978          * computation to clearly distinguish it from the adjusted mode, which
12979          * can be changed by the connectors in the below retry loop.
12980          */
12981         drm_mode_get_hv_timing(&pipe_config->base.mode,
12982                                &pipe_config->pipe_src_w,
12983                                &pipe_config->pipe_src_h);
12984
12985         for_each_connector_in_state(state, connector, connector_state, i) {
12986                 if (connector_state->crtc != crtc)
12987                         continue;
12988
12989                 encoder = to_intel_encoder(connector_state->best_encoder);
12990
12991                 if (!check_single_encoder_cloning(state, to_intel_crtc(crtc), encoder)) {
12992                         DRM_DEBUG_KMS("rejecting invalid cloning configuration\n");
12993                         goto fail;
12994                 }
12995
12996                 /*
12997                  * Determine output_types before calling the .compute_config()
12998                  * hooks so that the hooks can use this information safely.
12999                  */
13000                 pipe_config->output_types |= 1 << encoder->type;
13001         }
13002
13003 encoder_retry:
13004         /* Ensure the port clock defaults are reset when retrying. */
13005         pipe_config->port_clock = 0;
13006         pipe_config->pixel_multiplier = 1;
13007
13008         /* Fill in default crtc timings, allow encoders to overwrite them. */
13009         drm_mode_set_crtcinfo(&pipe_config->base.adjusted_mode,
13010                               CRTC_STEREO_DOUBLE);
13011
13012         /* Pass our mode to the connectors and the CRTC to give them a chance to
13013          * adjust it according to limitations or connector properties, and also
13014          * a chance to reject the mode entirely.
13015          */
13016         for_each_connector_in_state(state, connector, connector_state, i) {
13017                 if (connector_state->crtc != crtc)
13018                         continue;
13019
13020                 encoder = to_intel_encoder(connector_state->best_encoder);
13021
13022                 if (!(encoder->compute_config(encoder, pipe_config, connector_state))) {
13023                         DRM_DEBUG_KMS("Encoder config failure\n");
13024                         goto fail;
13025                 }
13026         }
13027
13028         /* Set default port clock if not overwritten by the encoder. Needs to be
13029          * done afterwards in case the encoder adjusts the mode. */
13030         if (!pipe_config->port_clock)
13031                 pipe_config->port_clock = pipe_config->base.adjusted_mode.crtc_clock
13032                         * pipe_config->pixel_multiplier;
13033
13034         ret = intel_crtc_compute_config(to_intel_crtc(crtc), pipe_config);
13035         if (ret < 0) {
13036                 DRM_DEBUG_KMS("CRTC fixup failed\n");
13037                 goto fail;
13038         }
13039
13040         if (ret == RETRY) {
13041                 if (WARN(!retry, "loop in pipe configuration computation\n")) {
13042                         ret = -EINVAL;
13043                         goto fail;
13044                 }
13045
13046                 DRM_DEBUG_KMS("CRTC bw constrained, retrying\n");
13047                 retry = false;
13048                 goto encoder_retry;
13049         }
13050
13051         /* Dithering seems to not pass-through bits correctly when it should, so
13052          * only enable it on 6bpc panels. */
13053         pipe_config->dither = pipe_config->pipe_bpp == 6*3;
13054         DRM_DEBUG_KMS("hw max bpp: %i, pipe bpp: %i, dithering: %i\n",
13055                       base_bpp, pipe_config->pipe_bpp, pipe_config->dither);
13056
13057 fail:
13058         return ret;
13059 }
13060
13061 static void
13062 intel_modeset_update_crtc_state(struct drm_atomic_state *state)
13063 {
13064         struct drm_crtc *crtc;
13065         struct drm_crtc_state *crtc_state;
13066         int i;
13067
13068         /* Double check state. */
13069         for_each_crtc_in_state(state, crtc, crtc_state, i) {
13070                 to_intel_crtc(crtc)->config = to_intel_crtc_state(crtc->state);
13071
13072                 /* Update hwmode for vblank functions */
13073                 if (crtc->state->active)
13074                         crtc->hwmode = crtc->state->adjusted_mode;
13075                 else
13076                         crtc->hwmode.crtc_clock = 0;
13077
13078                 /*
13079                  * Update legacy state to satisfy fbc code. This can
13080                  * be removed when fbc uses the atomic state.
13081                  */
13082                 if (drm_atomic_get_existing_plane_state(state, crtc->primary)) {
13083                         struct drm_plane_state *plane_state = crtc->primary->state;
13084
13085                         crtc->primary->fb = plane_state->fb;
13086                         crtc->x = plane_state->src_x >> 16;
13087                         crtc->y = plane_state->src_y >> 16;
13088                 }
13089         }
13090 }
13091
13092 static bool intel_fuzzy_clock_check(int clock1, int clock2)
13093 {
13094         int diff;
13095
13096         if (clock1 == clock2)
13097                 return true;
13098
13099         if (!clock1 || !clock2)
13100                 return false;
13101
13102         diff = abs(clock1 - clock2);
13103
13104         if (((((diff + clock1 + clock2) * 100)) / (clock1 + clock2)) < 105)
13105                 return true;
13106
13107         return false;
13108 }
13109
13110 static bool
13111 intel_compare_m_n(unsigned int m, unsigned int n,
13112                   unsigned int m2, unsigned int n2,
13113                   bool exact)
13114 {
13115         if (m == m2 && n == n2)
13116                 return true;
13117
13118         if (exact || !m || !n || !m2 || !n2)
13119                 return false;
13120
13121         BUILD_BUG_ON(DATA_LINK_M_N_MASK > INT_MAX);
13122
13123         if (n > n2) {
13124                 while (n > n2) {
13125                         m2 <<= 1;
13126                         n2 <<= 1;
13127                 }
13128         } else if (n < n2) {
13129                 while (n < n2) {
13130                         m <<= 1;
13131                         n <<= 1;
13132                 }
13133         }
13134
13135         if (n != n2)
13136                 return false;
13137
13138         return intel_fuzzy_clock_check(m, m2);
13139 }
13140
13141 static bool
13142 intel_compare_link_m_n(const struct intel_link_m_n *m_n,
13143                        struct intel_link_m_n *m2_n2,
13144                        bool adjust)
13145 {
13146         if (m_n->tu == m2_n2->tu &&
13147             intel_compare_m_n(m_n->gmch_m, m_n->gmch_n,
13148                               m2_n2->gmch_m, m2_n2->gmch_n, !adjust) &&
13149             intel_compare_m_n(m_n->link_m, m_n->link_n,
13150                               m2_n2->link_m, m2_n2->link_n, !adjust)) {
13151                 if (adjust)
13152                         *m2_n2 = *m_n;
13153
13154                 return true;
13155         }
13156
13157         return false;
13158 }
13159
13160 static void __printf(3, 4)
13161 pipe_config_err(bool adjust, const char *name, const char *format, ...)
13162 {
13163         char *level;
13164         unsigned int category;
13165         struct va_format vaf;
13166         va_list args;
13167
13168         if (adjust) {
13169                 level = KERN_DEBUG;
13170                 category = DRM_UT_KMS;
13171         } else {
13172                 level = KERN_ERR;
13173                 category = DRM_UT_NONE;
13174         }
13175
13176         va_start(args, format);
13177         vaf.fmt = format;
13178         vaf.va = &args;
13179
13180         drm_printk(level, category, "mismatch in %s %pV", name, &vaf);
13181
13182         va_end(args);
13183 }
13184
13185 static bool
13186 intel_pipe_config_compare(struct drm_i915_private *dev_priv,
13187                           struct intel_crtc_state *current_config,
13188                           struct intel_crtc_state *pipe_config,
13189                           bool adjust)
13190 {
13191         bool ret = true;
13192
13193 #define PIPE_CONF_CHECK_X(name) \
13194         if (current_config->name != pipe_config->name) { \
13195                 pipe_config_err(adjust, __stringify(name), \
13196                           "(expected 0x%08x, found 0x%08x)\n", \
13197                           current_config->name, \
13198                           pipe_config->name); \
13199                 ret = false; \
13200         }
13201
13202 #define PIPE_CONF_CHECK_I(name) \
13203         if (current_config->name != pipe_config->name) { \
13204                 pipe_config_err(adjust, __stringify(name), \
13205                           "(expected %i, found %i)\n", \
13206                           current_config->name, \
13207                           pipe_config->name); \
13208                 ret = false; \
13209         }
13210
13211 #define PIPE_CONF_CHECK_P(name) \
13212         if (current_config->name != pipe_config->name) { \
13213                 pipe_config_err(adjust, __stringify(name), \
13214                           "(expected %p, found %p)\n", \
13215                           current_config->name, \
13216                           pipe_config->name); \
13217                 ret = false; \
13218         }
13219
13220 #define PIPE_CONF_CHECK_M_N(name) \
13221         if (!intel_compare_link_m_n(&current_config->name, \
13222                                     &pipe_config->name,\
13223                                     adjust)) { \
13224                 pipe_config_err(adjust, __stringify(name), \
13225                           "(expected tu %i gmch %i/%i link %i/%i, " \
13226                           "found tu %i, gmch %i/%i link %i/%i)\n", \
13227                           current_config->name.tu, \
13228                           current_config->name.gmch_m, \
13229                           current_config->name.gmch_n, \
13230                           current_config->name.link_m, \
13231                           current_config->name.link_n, \
13232                           pipe_config->name.tu, \
13233                           pipe_config->name.gmch_m, \
13234                           pipe_config->name.gmch_n, \
13235                           pipe_config->name.link_m, \
13236                           pipe_config->name.link_n); \
13237                 ret = false; \
13238         }
13239
13240 /* This is required for BDW+ where there is only one set of registers for
13241  * switching between high and low RR.
13242  * This macro can be used whenever a comparison has to be made between one
13243  * hw state and multiple sw state variables.
13244  */
13245 #define PIPE_CONF_CHECK_M_N_ALT(name, alt_name) \
13246         if (!intel_compare_link_m_n(&current_config->name, \
13247                                     &pipe_config->name, adjust) && \
13248             !intel_compare_link_m_n(&current_config->alt_name, \
13249                                     &pipe_config->name, adjust)) { \
13250                 pipe_config_err(adjust, __stringify(name), \
13251                           "(expected tu %i gmch %i/%i link %i/%i, " \
13252                           "or tu %i gmch %i/%i link %i/%i, " \
13253                           "found tu %i, gmch %i/%i link %i/%i)\n", \
13254                           current_config->name.tu, \
13255                           current_config->name.gmch_m, \
13256                           current_config->name.gmch_n, \
13257                           current_config->name.link_m, \
13258                           current_config->name.link_n, \
13259                           current_config->alt_name.tu, \
13260                           current_config->alt_name.gmch_m, \
13261                           current_config->alt_name.gmch_n, \
13262                           current_config->alt_name.link_m, \
13263                           current_config->alt_name.link_n, \
13264                           pipe_config->name.tu, \
13265                           pipe_config->name.gmch_m, \
13266                           pipe_config->name.gmch_n, \
13267                           pipe_config->name.link_m, \
13268                           pipe_config->name.link_n); \
13269                 ret = false; \
13270         }
13271
13272 #define PIPE_CONF_CHECK_FLAGS(name, mask)       \
13273         if ((current_config->name ^ pipe_config->name) & (mask)) { \
13274                 pipe_config_err(adjust, __stringify(name), \
13275                           "(%x) (expected %i, found %i)\n", \
13276                           (mask), \
13277                           current_config->name & (mask), \
13278                           pipe_config->name & (mask)); \
13279                 ret = false; \
13280         }
13281
13282 #define PIPE_CONF_CHECK_CLOCK_FUZZY(name) \
13283         if (!intel_fuzzy_clock_check(current_config->name, pipe_config->name)) { \
13284                 pipe_config_err(adjust, __stringify(name), \
13285                           "(expected %i, found %i)\n", \
13286                           current_config->name, \
13287                           pipe_config->name); \
13288                 ret = false; \
13289         }
13290
13291 #define PIPE_CONF_QUIRK(quirk)  \
13292         ((current_config->quirks | pipe_config->quirks) & (quirk))
13293
13294         PIPE_CONF_CHECK_I(cpu_transcoder);
13295
13296         PIPE_CONF_CHECK_I(has_pch_encoder);
13297         PIPE_CONF_CHECK_I(fdi_lanes);
13298         PIPE_CONF_CHECK_M_N(fdi_m_n);
13299
13300         PIPE_CONF_CHECK_I(lane_count);
13301         PIPE_CONF_CHECK_X(lane_lat_optim_mask);
13302
13303         if (INTEL_GEN(dev_priv) < 8) {
13304                 PIPE_CONF_CHECK_M_N(dp_m_n);
13305
13306                 if (current_config->has_drrs)
13307                         PIPE_CONF_CHECK_M_N(dp_m2_n2);
13308         } else
13309                 PIPE_CONF_CHECK_M_N_ALT(dp_m_n, dp_m2_n2);
13310
13311         PIPE_CONF_CHECK_X(output_types);
13312
13313         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hdisplay);
13314         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_htotal);
13315         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hblank_start);
13316         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hblank_end);
13317         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hsync_start);
13318         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hsync_end);
13319
13320         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vdisplay);
13321         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vtotal);
13322         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vblank_start);
13323         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vblank_end);
13324         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vsync_start);
13325         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vsync_end);
13326
13327         PIPE_CONF_CHECK_I(pixel_multiplier);
13328         PIPE_CONF_CHECK_I(has_hdmi_sink);
13329         if ((INTEL_GEN(dev_priv) < 8 && !IS_HASWELL(dev_priv)) ||
13330             IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
13331                 PIPE_CONF_CHECK_I(limited_color_range);
13332         PIPE_CONF_CHECK_I(has_infoframe);
13333
13334         PIPE_CONF_CHECK_I(has_audio);
13335
13336         PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
13337                               DRM_MODE_FLAG_INTERLACE);
13338
13339         if (!PIPE_CONF_QUIRK(PIPE_CONFIG_QUIRK_MODE_SYNC_FLAGS)) {
13340                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
13341                                       DRM_MODE_FLAG_PHSYNC);
13342                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
13343                                       DRM_MODE_FLAG_NHSYNC);
13344                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
13345                                       DRM_MODE_FLAG_PVSYNC);
13346                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
13347                                       DRM_MODE_FLAG_NVSYNC);
13348         }
13349
13350         PIPE_CONF_CHECK_X(gmch_pfit.control);
13351         /* pfit ratios are autocomputed by the hw on gen4+ */
13352         if (INTEL_GEN(dev_priv) < 4)
13353                 PIPE_CONF_CHECK_X(gmch_pfit.pgm_ratios);
13354         PIPE_CONF_CHECK_X(gmch_pfit.lvds_border_bits);
13355
13356         if (!adjust) {
13357                 PIPE_CONF_CHECK_I(pipe_src_w);
13358                 PIPE_CONF_CHECK_I(pipe_src_h);
13359
13360                 PIPE_CONF_CHECK_I(pch_pfit.enabled);
13361                 if (current_config->pch_pfit.enabled) {
13362                         PIPE_CONF_CHECK_X(pch_pfit.pos);
13363                         PIPE_CONF_CHECK_X(pch_pfit.size);
13364                 }
13365
13366                 PIPE_CONF_CHECK_I(scaler_state.scaler_id);
13367         }
13368
13369         /* BDW+ don't expose a synchronous way to read the state */
13370         if (IS_HASWELL(dev_priv))
13371                 PIPE_CONF_CHECK_I(ips_enabled);
13372
13373         PIPE_CONF_CHECK_I(double_wide);
13374
13375         PIPE_CONF_CHECK_P(shared_dpll);
13376         PIPE_CONF_CHECK_X(dpll_hw_state.dpll);
13377         PIPE_CONF_CHECK_X(dpll_hw_state.dpll_md);
13378         PIPE_CONF_CHECK_X(dpll_hw_state.fp0);
13379         PIPE_CONF_CHECK_X(dpll_hw_state.fp1);
13380         PIPE_CONF_CHECK_X(dpll_hw_state.wrpll);
13381         PIPE_CONF_CHECK_X(dpll_hw_state.spll);
13382         PIPE_CONF_CHECK_X(dpll_hw_state.ctrl1);
13383         PIPE_CONF_CHECK_X(dpll_hw_state.cfgcr1);
13384         PIPE_CONF_CHECK_X(dpll_hw_state.cfgcr2);
13385
13386         PIPE_CONF_CHECK_X(dsi_pll.ctrl);
13387         PIPE_CONF_CHECK_X(dsi_pll.div);
13388
13389         if (IS_G4X(dev_priv) || INTEL_GEN(dev_priv) >= 5)
13390                 PIPE_CONF_CHECK_I(pipe_bpp);
13391
13392         PIPE_CONF_CHECK_CLOCK_FUZZY(base.adjusted_mode.crtc_clock);
13393         PIPE_CONF_CHECK_CLOCK_FUZZY(port_clock);
13394
13395 #undef PIPE_CONF_CHECK_X
13396 #undef PIPE_CONF_CHECK_I
13397 #undef PIPE_CONF_CHECK_P
13398 #undef PIPE_CONF_CHECK_FLAGS
13399 #undef PIPE_CONF_CHECK_CLOCK_FUZZY
13400 #undef PIPE_CONF_QUIRK
13401
13402         return ret;
13403 }
13404
13405 static void intel_pipe_config_sanity_check(struct drm_i915_private *dev_priv,
13406                                            const struct intel_crtc_state *pipe_config)
13407 {
13408         if (pipe_config->has_pch_encoder) {
13409                 int fdi_dotclock = intel_dotclock_calculate(intel_fdi_link_freq(dev_priv, pipe_config),
13410                                                             &pipe_config->fdi_m_n);
13411                 int dotclock = pipe_config->base.adjusted_mode.crtc_clock;
13412
13413                 /*
13414                  * FDI already provided one idea for the dotclock.
13415                  * Yell if the encoder disagrees.
13416                  */
13417                 WARN(!intel_fuzzy_clock_check(fdi_dotclock, dotclock),
13418                      "FDI dotclock and encoder dotclock mismatch, fdi: %i, encoder: %i\n",
13419                      fdi_dotclock, dotclock);
13420         }
13421 }
13422
13423 static void verify_wm_state(struct drm_crtc *crtc,
13424                             struct drm_crtc_state *new_state)
13425 {
13426         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
13427         struct skl_ddb_allocation hw_ddb, *sw_ddb;
13428         struct skl_pipe_wm hw_wm, *sw_wm;
13429         struct skl_plane_wm *hw_plane_wm, *sw_plane_wm;
13430         struct skl_ddb_entry *hw_ddb_entry, *sw_ddb_entry;
13431         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
13432         const enum pipe pipe = intel_crtc->pipe;
13433         int plane, level, max_level = ilk_wm_max_level(dev_priv);
13434
13435         if (INTEL_GEN(dev_priv) < 9 || !new_state->active)
13436                 return;
13437
13438         skl_pipe_wm_get_hw_state(crtc, &hw_wm);
13439         sw_wm = &to_intel_crtc_state(new_state)->wm.skl.optimal;
13440
13441         skl_ddb_get_hw_state(dev_priv, &hw_ddb);
13442         sw_ddb = &dev_priv->wm.skl_hw.ddb;
13443
13444         /* planes */
13445         for_each_universal_plane(dev_priv, pipe, plane) {
13446                 hw_plane_wm = &hw_wm.planes[plane];
13447                 sw_plane_wm = &sw_wm->planes[plane];
13448
13449                 /* Watermarks */
13450                 for (level = 0; level <= max_level; level++) {
13451                         if (skl_wm_level_equals(&hw_plane_wm->wm[level],
13452                                                 &sw_plane_wm->wm[level]))
13453                                 continue;
13454
13455                         DRM_ERROR("mismatch in WM pipe %c plane %d level %d (expected e=%d b=%u l=%u, got e=%d b=%u l=%u)\n",
13456                                   pipe_name(pipe), plane + 1, level,
13457                                   sw_plane_wm->wm[level].plane_en,
13458                                   sw_plane_wm->wm[level].plane_res_b,
13459                                   sw_plane_wm->wm[level].plane_res_l,
13460                                   hw_plane_wm->wm[level].plane_en,
13461                                   hw_plane_wm->wm[level].plane_res_b,
13462                                   hw_plane_wm->wm[level].plane_res_l);
13463                 }
13464
13465                 if (!skl_wm_level_equals(&hw_plane_wm->trans_wm,
13466                                          &sw_plane_wm->trans_wm)) {
13467                         DRM_ERROR("mismatch in trans WM pipe %c plane %d (expected e=%d b=%u l=%u, got e=%d b=%u l=%u)\n",
13468                                   pipe_name(pipe), plane + 1,
13469                                   sw_plane_wm->trans_wm.plane_en,
13470                                   sw_plane_wm->trans_wm.plane_res_b,
13471                                   sw_plane_wm->trans_wm.plane_res_l,
13472                                   hw_plane_wm->trans_wm.plane_en,
13473                                   hw_plane_wm->trans_wm.plane_res_b,
13474                                   hw_plane_wm->trans_wm.plane_res_l);
13475                 }
13476
13477                 /* DDB */
13478                 hw_ddb_entry = &hw_ddb.plane[pipe][plane];
13479                 sw_ddb_entry = &sw_ddb->plane[pipe][plane];
13480
13481                 if (!skl_ddb_entry_equal(hw_ddb_entry, sw_ddb_entry)) {
13482                         DRM_ERROR("mismatch in DDB state pipe %c plane %d (expected (%u,%u), found (%u,%u))\n",
13483                                   pipe_name(pipe), plane + 1,
13484                                   sw_ddb_entry->start, sw_ddb_entry->end,
13485                                   hw_ddb_entry->start, hw_ddb_entry->end);
13486                 }
13487         }
13488
13489         /*
13490          * cursor
13491          * If the cursor plane isn't active, we may not have updated it's ddb
13492          * allocation. In that case since the ddb allocation will be updated
13493          * once the plane becomes visible, we can skip this check
13494          */
13495         if (intel_crtc->cursor_addr) {
13496                 hw_plane_wm = &hw_wm.planes[PLANE_CURSOR];
13497                 sw_plane_wm = &sw_wm->planes[PLANE_CURSOR];
13498
13499                 /* Watermarks */
13500                 for (level = 0; level <= max_level; level++) {
13501                         if (skl_wm_level_equals(&hw_plane_wm->wm[level],
13502                                                 &sw_plane_wm->wm[level]))
13503                                 continue;
13504
13505                         DRM_ERROR("mismatch in WM pipe %c cursor level %d (expected e=%d b=%u l=%u, got e=%d b=%u l=%u)\n",
13506                                   pipe_name(pipe), level,
13507                                   sw_plane_wm->wm[level].plane_en,
13508                                   sw_plane_wm->wm[level].plane_res_b,
13509                                   sw_plane_wm->wm[level].plane_res_l,
13510                                   hw_plane_wm->wm[level].plane_en,
13511                                   hw_plane_wm->wm[level].plane_res_b,
13512                                   hw_plane_wm->wm[level].plane_res_l);
13513                 }
13514
13515                 if (!skl_wm_level_equals(&hw_plane_wm->trans_wm,
13516                                          &sw_plane_wm->trans_wm)) {
13517                         DRM_ERROR("mismatch in trans WM pipe %c cursor (expected e=%d b=%u l=%u, got e=%d b=%u l=%u)\n",
13518                                   pipe_name(pipe),
13519                                   sw_plane_wm->trans_wm.plane_en,
13520                                   sw_plane_wm->trans_wm.plane_res_b,
13521                                   sw_plane_wm->trans_wm.plane_res_l,
13522                                   hw_plane_wm->trans_wm.plane_en,
13523                                   hw_plane_wm->trans_wm.plane_res_b,
13524                                   hw_plane_wm->trans_wm.plane_res_l);
13525                 }
13526
13527                 /* DDB */
13528                 hw_ddb_entry = &hw_ddb.plane[pipe][PLANE_CURSOR];
13529                 sw_ddb_entry = &sw_ddb->plane[pipe][PLANE_CURSOR];
13530
13531                 if (!skl_ddb_entry_equal(hw_ddb_entry, sw_ddb_entry)) {
13532                         DRM_ERROR("mismatch in DDB state pipe %c cursor (expected (%u,%u), found (%u,%u))\n",
13533                                   pipe_name(pipe),
13534                                   sw_ddb_entry->start, sw_ddb_entry->end,
13535                                   hw_ddb_entry->start, hw_ddb_entry->end);
13536                 }
13537         }
13538 }
13539
13540 static void
13541 verify_connector_state(struct drm_device *dev,
13542                        struct drm_atomic_state *state,
13543                        struct drm_crtc *crtc)
13544 {
13545         struct drm_connector *connector;
13546         struct drm_connector_state *old_conn_state;
13547         int i;
13548
13549         for_each_connector_in_state(state, connector, old_conn_state, i) {
13550                 struct drm_encoder *encoder = connector->encoder;
13551                 struct drm_connector_state *state = connector->state;
13552
13553                 if (state->crtc != crtc)
13554                         continue;
13555
13556                 intel_connector_verify_state(to_intel_connector(connector));
13557
13558                 I915_STATE_WARN(state->best_encoder != encoder,
13559                      "connector's atomic encoder doesn't match legacy encoder\n");
13560         }
13561 }
13562
13563 static void
13564 verify_encoder_state(struct drm_device *dev)
13565 {
13566         struct intel_encoder *encoder;
13567         struct intel_connector *connector;
13568
13569         for_each_intel_encoder(dev, encoder) {
13570                 bool enabled = false;
13571                 enum pipe pipe;
13572
13573                 DRM_DEBUG_KMS("[ENCODER:%d:%s]\n",
13574                               encoder->base.base.id,
13575                               encoder->base.name);
13576
13577                 for_each_intel_connector(dev, connector) {
13578                         if (connector->base.state->best_encoder != &encoder->base)
13579                                 continue;
13580                         enabled = true;
13581
13582                         I915_STATE_WARN(connector->base.state->crtc !=
13583                                         encoder->base.crtc,
13584                              "connector's crtc doesn't match encoder crtc\n");
13585                 }
13586
13587                 I915_STATE_WARN(!!encoder->base.crtc != enabled,
13588                      "encoder's enabled state mismatch "
13589                      "(expected %i, found %i)\n",
13590                      !!encoder->base.crtc, enabled);
13591
13592                 if (!encoder->base.crtc) {
13593                         bool active;
13594
13595                         active = encoder->get_hw_state(encoder, &pipe);
13596                         I915_STATE_WARN(active,
13597                              "encoder detached but still enabled on pipe %c.\n",
13598                              pipe_name(pipe));
13599                 }
13600         }
13601 }
13602
13603 static void
13604 verify_crtc_state(struct drm_crtc *crtc,
13605                   struct drm_crtc_state *old_crtc_state,
13606                   struct drm_crtc_state *new_crtc_state)
13607 {
13608         struct drm_device *dev = crtc->dev;
13609         struct drm_i915_private *dev_priv = to_i915(dev);
13610         struct intel_encoder *encoder;
13611         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
13612         struct intel_crtc_state *pipe_config, *sw_config;
13613         struct drm_atomic_state *old_state;
13614         bool active;
13615
13616         old_state = old_crtc_state->state;
13617         __drm_atomic_helper_crtc_destroy_state(old_crtc_state);
13618         pipe_config = to_intel_crtc_state(old_crtc_state);
13619         memset(pipe_config, 0, sizeof(*pipe_config));
13620         pipe_config->base.crtc = crtc;
13621         pipe_config->base.state = old_state;
13622
13623         DRM_DEBUG_KMS("[CRTC:%d:%s]\n", crtc->base.id, crtc->name);
13624
13625         active = dev_priv->display.get_pipe_config(intel_crtc, pipe_config);
13626
13627         /* hw state is inconsistent with the pipe quirk */
13628         if ((intel_crtc->pipe == PIPE_A && dev_priv->quirks & QUIRK_PIPEA_FORCE) ||
13629             (intel_crtc->pipe == PIPE_B && dev_priv->quirks & QUIRK_PIPEB_FORCE))
13630                 active = new_crtc_state->active;
13631
13632         I915_STATE_WARN(new_crtc_state->active != active,
13633              "crtc active state doesn't match with hw state "
13634              "(expected %i, found %i)\n", new_crtc_state->active, active);
13635
13636         I915_STATE_WARN(intel_crtc->active != new_crtc_state->active,
13637              "transitional active state does not match atomic hw state "
13638              "(expected %i, found %i)\n", new_crtc_state->active, intel_crtc->active);
13639
13640         for_each_encoder_on_crtc(dev, crtc, encoder) {
13641                 enum pipe pipe;
13642
13643                 active = encoder->get_hw_state(encoder, &pipe);
13644                 I915_STATE_WARN(active != new_crtc_state->active,
13645                         "[ENCODER:%i] active %i with crtc active %i\n",
13646                         encoder->base.base.id, active, new_crtc_state->active);
13647
13648                 I915_STATE_WARN(active && intel_crtc->pipe != pipe,
13649                                 "Encoder connected to wrong pipe %c\n",
13650                                 pipe_name(pipe));
13651
13652                 if (active) {
13653                         pipe_config->output_types |= 1 << encoder->type;
13654                         encoder->get_config(encoder, pipe_config);
13655                 }
13656         }
13657
13658         if (!new_crtc_state->active)
13659                 return;
13660
13661         intel_pipe_config_sanity_check(dev_priv, pipe_config);
13662
13663         sw_config = to_intel_crtc_state(crtc->state);
13664         if (!intel_pipe_config_compare(dev_priv, sw_config,
13665                                        pipe_config, false)) {
13666                 I915_STATE_WARN(1, "pipe state doesn't match!\n");
13667                 intel_dump_pipe_config(intel_crtc, pipe_config,
13668                                        "[hw state]");
13669                 intel_dump_pipe_config(intel_crtc, sw_config,
13670                                        "[sw state]");
13671         }
13672 }
13673
13674 static void
13675 verify_single_dpll_state(struct drm_i915_private *dev_priv,
13676                          struct intel_shared_dpll *pll,
13677                          struct drm_crtc *crtc,
13678                          struct drm_crtc_state *new_state)
13679 {
13680         struct intel_dpll_hw_state dpll_hw_state;
13681         unsigned crtc_mask;
13682         bool active;
13683
13684         memset(&dpll_hw_state, 0, sizeof(dpll_hw_state));
13685
13686         DRM_DEBUG_KMS("%s\n", pll->name);
13687
13688         active = pll->funcs.get_hw_state(dev_priv, pll, &dpll_hw_state);
13689
13690         if (!(pll->flags & INTEL_DPLL_ALWAYS_ON)) {
13691                 I915_STATE_WARN(!pll->on && pll->active_mask,
13692                      "pll in active use but not on in sw tracking\n");
13693                 I915_STATE_WARN(pll->on && !pll->active_mask,
13694                      "pll is on but not used by any active crtc\n");
13695                 I915_STATE_WARN(pll->on != active,
13696                      "pll on state mismatch (expected %i, found %i)\n",
13697                      pll->on, active);
13698         }
13699
13700         if (!crtc) {
13701                 I915_STATE_WARN(pll->active_mask & ~pll->state.crtc_mask,
13702                                 "more active pll users than references: %x vs %x\n",
13703                                 pll->active_mask, pll->state.crtc_mask);
13704
13705                 return;
13706         }
13707
13708         crtc_mask = 1 << drm_crtc_index(crtc);
13709
13710         if (new_state->active)
13711                 I915_STATE_WARN(!(pll->active_mask & crtc_mask),
13712                                 "pll active mismatch (expected pipe %c in active mask 0x%02x)\n",
13713                                 pipe_name(drm_crtc_index(crtc)), pll->active_mask);
13714         else
13715                 I915_STATE_WARN(pll->active_mask & crtc_mask,
13716                                 "pll active mismatch (didn't expect pipe %c in active mask 0x%02x)\n",
13717                                 pipe_name(drm_crtc_index(crtc)), pll->active_mask);
13718
13719         I915_STATE_WARN(!(pll->state.crtc_mask & crtc_mask),
13720                         "pll enabled crtcs mismatch (expected 0x%x in 0x%02x)\n",
13721                         crtc_mask, pll->state.crtc_mask);
13722
13723         I915_STATE_WARN(pll->on && memcmp(&pll->state.hw_state,
13724                                           &dpll_hw_state,
13725                                           sizeof(dpll_hw_state)),
13726                         "pll hw state mismatch\n");
13727 }
13728
13729 static void
13730 verify_shared_dpll_state(struct drm_device *dev, struct drm_crtc *crtc,
13731                          struct drm_crtc_state *old_crtc_state,
13732                          struct drm_crtc_state *new_crtc_state)
13733 {
13734         struct drm_i915_private *dev_priv = to_i915(dev);
13735         struct intel_crtc_state *old_state = to_intel_crtc_state(old_crtc_state);
13736         struct intel_crtc_state *new_state = to_intel_crtc_state(new_crtc_state);
13737
13738         if (new_state->shared_dpll)
13739                 verify_single_dpll_state(dev_priv, new_state->shared_dpll, crtc, new_crtc_state);
13740
13741         if (old_state->shared_dpll &&
13742             old_state->shared_dpll != new_state->shared_dpll) {
13743                 unsigned crtc_mask = 1 << drm_crtc_index(crtc);
13744                 struct intel_shared_dpll *pll = old_state->shared_dpll;
13745
13746                 I915_STATE_WARN(pll->active_mask & crtc_mask,
13747                                 "pll active mismatch (didn't expect pipe %c in active mask)\n",
13748                                 pipe_name(drm_crtc_index(crtc)));
13749                 I915_STATE_WARN(pll->state.crtc_mask & crtc_mask,
13750                                 "pll enabled crtcs mismatch (found %x in enabled mask)\n",
13751                                 pipe_name(drm_crtc_index(crtc)));
13752         }
13753 }
13754
13755 static void
13756 intel_modeset_verify_crtc(struct drm_crtc *crtc,
13757                           struct drm_atomic_state *state,
13758                           struct drm_crtc_state *old_state,
13759                           struct drm_crtc_state *new_state)
13760 {
13761         if (!needs_modeset(new_state) &&
13762             !to_intel_crtc_state(new_state)->update_pipe)
13763                 return;
13764
13765         verify_wm_state(crtc, new_state);
13766         verify_connector_state(crtc->dev, state, crtc);
13767         verify_crtc_state(crtc, old_state, new_state);
13768         verify_shared_dpll_state(crtc->dev, crtc, old_state, new_state);
13769 }
13770
13771 static void
13772 verify_disabled_dpll_state(struct drm_device *dev)
13773 {
13774         struct drm_i915_private *dev_priv = to_i915(dev);
13775         int i;
13776
13777         for (i = 0; i < dev_priv->num_shared_dpll; i++)
13778                 verify_single_dpll_state(dev_priv, &dev_priv->shared_dplls[i], NULL, NULL);
13779 }
13780
13781 static void
13782 intel_modeset_verify_disabled(struct drm_device *dev,
13783                               struct drm_atomic_state *state)
13784 {
13785         verify_encoder_state(dev);
13786         verify_connector_state(dev, state, NULL);
13787         verify_disabled_dpll_state(dev);
13788 }
13789
13790 static void update_scanline_offset(struct intel_crtc *crtc)
13791 {
13792         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
13793
13794         /*
13795          * The scanline counter increments at the leading edge of hsync.
13796          *
13797          * On most platforms it starts counting from vtotal-1 on the
13798          * first active line. That means the scanline counter value is
13799          * always one less than what we would expect. Ie. just after
13800          * start of vblank, which also occurs at start of hsync (on the
13801          * last active line), the scanline counter will read vblank_start-1.
13802          *
13803          * On gen2 the scanline counter starts counting from 1 instead
13804          * of vtotal-1, so we have to subtract one (or rather add vtotal-1
13805          * to keep the value positive), instead of adding one.
13806          *
13807          * On HSW+ the behaviour of the scanline counter depends on the output
13808          * type. For DP ports it behaves like most other platforms, but on HDMI
13809          * there's an extra 1 line difference. So we need to add two instead of
13810          * one to the value.
13811          */
13812         if (IS_GEN2(dev_priv)) {
13813                 const struct drm_display_mode *adjusted_mode = &crtc->config->base.adjusted_mode;
13814                 int vtotal;
13815
13816                 vtotal = adjusted_mode->crtc_vtotal;
13817                 if (adjusted_mode->flags & DRM_MODE_FLAG_INTERLACE)
13818                         vtotal /= 2;
13819
13820                 crtc->scanline_offset = vtotal - 1;
13821         } else if (HAS_DDI(dev_priv) &&
13822                    intel_crtc_has_type(crtc->config, INTEL_OUTPUT_HDMI)) {
13823                 crtc->scanline_offset = 2;
13824         } else
13825                 crtc->scanline_offset = 1;
13826 }
13827
13828 static void intel_modeset_clear_plls(struct drm_atomic_state *state)
13829 {
13830         struct drm_device *dev = state->dev;
13831         struct drm_i915_private *dev_priv = to_i915(dev);
13832         struct drm_crtc *crtc;
13833         struct drm_crtc_state *crtc_state;
13834         int i;
13835
13836         if (!dev_priv->display.crtc_compute_clock)
13837                 return;
13838
13839         for_each_crtc_in_state(state, crtc, crtc_state, i) {
13840                 struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
13841                 struct intel_shared_dpll *old_dpll =
13842                         to_intel_crtc_state(crtc->state)->shared_dpll;
13843
13844                 if (!needs_modeset(crtc_state))
13845                         continue;
13846
13847                 to_intel_crtc_state(crtc_state)->shared_dpll = NULL;
13848
13849                 if (!old_dpll)
13850                         continue;
13851
13852                 intel_release_shared_dpll(old_dpll, intel_crtc, state);
13853         }
13854 }
13855
13856 /*
13857  * This implements the workaround described in the "notes" section of the mode
13858  * set sequence documentation. When going from no pipes or single pipe to
13859  * multiple pipes, and planes are enabled after the pipe, we need to wait at
13860  * least 2 vblanks on the first pipe before enabling planes on the second pipe.
13861  */
13862 static int haswell_mode_set_planes_workaround(struct drm_atomic_state *state)
13863 {
13864         struct drm_crtc_state *crtc_state;
13865         struct intel_crtc *intel_crtc;
13866         struct drm_crtc *crtc;
13867         struct intel_crtc_state *first_crtc_state = NULL;
13868         struct intel_crtc_state *other_crtc_state = NULL;
13869         enum pipe first_pipe = INVALID_PIPE, enabled_pipe = INVALID_PIPE;
13870         int i;
13871
13872         /* look at all crtc's that are going to be enabled in during modeset */
13873         for_each_crtc_in_state(state, crtc, crtc_state, i) {
13874                 intel_crtc = to_intel_crtc(crtc);
13875
13876                 if (!crtc_state->active || !needs_modeset(crtc_state))
13877                         continue;
13878
13879                 if (first_crtc_state) {
13880                         other_crtc_state = to_intel_crtc_state(crtc_state);
13881                         break;
13882                 } else {
13883                         first_crtc_state = to_intel_crtc_state(crtc_state);
13884                         first_pipe = intel_crtc->pipe;
13885                 }
13886         }
13887
13888         /* No workaround needed? */
13889         if (!first_crtc_state)
13890                 return 0;
13891
13892         /* w/a possibly needed, check how many crtc's are already enabled. */
13893         for_each_intel_crtc(state->dev, intel_crtc) {
13894                 struct intel_crtc_state *pipe_config;
13895
13896                 pipe_config = intel_atomic_get_crtc_state(state, intel_crtc);
13897                 if (IS_ERR(pipe_config))
13898                         return PTR_ERR(pipe_config);
13899
13900                 pipe_config->hsw_workaround_pipe = INVALID_PIPE;
13901
13902                 if (!pipe_config->base.active ||
13903                     needs_modeset(&pipe_config->base))
13904                         continue;
13905
13906                 /* 2 or more enabled crtcs means no need for w/a */
13907                 if (enabled_pipe != INVALID_PIPE)
13908                         return 0;
13909
13910                 enabled_pipe = intel_crtc->pipe;
13911         }
13912
13913         if (enabled_pipe != INVALID_PIPE)
13914                 first_crtc_state->hsw_workaround_pipe = enabled_pipe;
13915         else if (other_crtc_state)
13916                 other_crtc_state->hsw_workaround_pipe = first_pipe;
13917
13918         return 0;
13919 }
13920
13921 static int intel_lock_all_pipes(struct drm_atomic_state *state)
13922 {
13923         struct drm_crtc *crtc;
13924
13925         /* Add all pipes to the state */
13926         for_each_crtc(state->dev, crtc) {
13927                 struct drm_crtc_state *crtc_state;
13928
13929                 crtc_state = drm_atomic_get_crtc_state(state, crtc);
13930                 if (IS_ERR(crtc_state))
13931                         return PTR_ERR(crtc_state);
13932         }
13933
13934         return 0;
13935 }
13936
13937 static int intel_modeset_all_pipes(struct drm_atomic_state *state)
13938 {
13939         struct drm_crtc *crtc;
13940
13941         /*
13942          * Add all pipes to the state, and force
13943          * a modeset on all the active ones.
13944          */
13945         for_each_crtc(state->dev, crtc) {
13946                 struct drm_crtc_state *crtc_state;
13947                 int ret;
13948
13949                 crtc_state = drm_atomic_get_crtc_state(state, crtc);
13950                 if (IS_ERR(crtc_state))
13951                         return PTR_ERR(crtc_state);
13952
13953                 if (!crtc_state->active || needs_modeset(crtc_state))
13954                         continue;
13955
13956                 crtc_state->mode_changed = true;
13957
13958                 ret = drm_atomic_add_affected_connectors(state, crtc);
13959                 if (ret)
13960                         return ret;
13961
13962                 ret = drm_atomic_add_affected_planes(state, crtc);
13963                 if (ret)
13964                         return ret;
13965         }
13966
13967         return 0;
13968 }
13969
13970 static int intel_modeset_checks(struct drm_atomic_state *state)
13971 {
13972         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
13973         struct drm_i915_private *dev_priv = to_i915(state->dev);
13974         struct drm_crtc *crtc;
13975         struct drm_crtc_state *crtc_state;
13976         int ret = 0, i;
13977
13978         if (!check_digital_port_conflicts(state)) {
13979                 DRM_DEBUG_KMS("rejecting conflicting digital port configuration\n");
13980                 return -EINVAL;
13981         }
13982
13983         intel_state->modeset = true;
13984         intel_state->active_crtcs = dev_priv->active_crtcs;
13985
13986         for_each_crtc_in_state(state, crtc, crtc_state, i) {
13987                 if (crtc_state->active)
13988                         intel_state->active_crtcs |= 1 << i;
13989                 else
13990                         intel_state->active_crtcs &= ~(1 << i);
13991
13992                 if (crtc_state->active != crtc->state->active)
13993                         intel_state->active_pipe_changes |= drm_crtc_mask(crtc);
13994         }
13995
13996         /*
13997          * See if the config requires any additional preparation, e.g.
13998          * to adjust global state with pipes off.  We need to do this
13999          * here so we can get the modeset_pipe updated config for the new
14000          * mode set on this crtc.  For other crtcs we need to use the
14001          * adjusted_mode bits in the crtc directly.
14002          */
14003         if (dev_priv->display.modeset_calc_cdclk) {
14004                 if (!intel_state->cdclk_pll_vco)
14005                         intel_state->cdclk_pll_vco = dev_priv->cdclk_pll.vco;
14006                 if (!intel_state->cdclk_pll_vco)
14007                         intel_state->cdclk_pll_vco = dev_priv->skl_preferred_vco_freq;
14008
14009                 ret = dev_priv->display.modeset_calc_cdclk(state);
14010                 if (ret < 0)
14011                         return ret;
14012
14013                 /*
14014                  * Writes to dev_priv->atomic_cdclk_freq must protected by
14015                  * holding all the crtc locks, even if we don't end up
14016                  * touching the hardware
14017                  */
14018                 if (intel_state->cdclk != dev_priv->atomic_cdclk_freq) {
14019                         ret = intel_lock_all_pipes(state);
14020                         if (ret < 0)
14021                                 return ret;
14022                 }
14023
14024                 /* All pipes must be switched off while we change the cdclk. */
14025                 if (intel_state->dev_cdclk != dev_priv->cdclk_freq ||
14026                     intel_state->cdclk_pll_vco != dev_priv->cdclk_pll.vco) {
14027                         ret = intel_modeset_all_pipes(state);
14028                         if (ret < 0)
14029                                 return ret;
14030                 }
14031
14032                 DRM_DEBUG_KMS("New cdclk calculated to be atomic %u, actual %u\n",
14033                               intel_state->cdclk, intel_state->dev_cdclk);
14034         } else {
14035                 to_intel_atomic_state(state)->cdclk = dev_priv->atomic_cdclk_freq;
14036         }
14037
14038         intel_modeset_clear_plls(state);
14039
14040         if (IS_HASWELL(dev_priv))
14041                 return haswell_mode_set_planes_workaround(state);
14042
14043         return 0;
14044 }
14045
14046 /*
14047  * Handle calculation of various watermark data at the end of the atomic check
14048  * phase.  The code here should be run after the per-crtc and per-plane 'check'
14049  * handlers to ensure that all derived state has been updated.
14050  */
14051 static int calc_watermark_data(struct drm_atomic_state *state)
14052 {
14053         struct drm_device *dev = state->dev;
14054         struct drm_i915_private *dev_priv = to_i915(dev);
14055
14056         /* Is there platform-specific watermark information to calculate? */
14057         if (dev_priv->display.compute_global_watermarks)
14058                 return dev_priv->display.compute_global_watermarks(state);
14059
14060         return 0;
14061 }
14062
14063 /**
14064  * intel_atomic_check - validate state object
14065  * @dev: drm device
14066  * @state: state to validate
14067  */
14068 static int intel_atomic_check(struct drm_device *dev,
14069                               struct drm_atomic_state *state)
14070 {
14071         struct drm_i915_private *dev_priv = to_i915(dev);
14072         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
14073         struct drm_crtc *crtc;
14074         struct drm_crtc_state *crtc_state;
14075         int ret, i;
14076         bool any_ms = false;
14077
14078         ret = drm_atomic_helper_check_modeset(dev, state);
14079         if (ret)
14080                 return ret;
14081
14082         for_each_crtc_in_state(state, crtc, crtc_state, i) {
14083                 struct intel_crtc_state *pipe_config =
14084                         to_intel_crtc_state(crtc_state);
14085
14086                 /* Catch I915_MODE_FLAG_INHERITED */
14087                 if (crtc_state->mode.private_flags != crtc->state->mode.private_flags)
14088                         crtc_state->mode_changed = true;
14089
14090                 if (!needs_modeset(crtc_state))
14091                         continue;
14092
14093                 if (!crtc_state->enable) {
14094                         any_ms = true;
14095                         continue;
14096                 }
14097
14098                 /* FIXME: For only active_changed we shouldn't need to do any
14099                  * state recomputation at all. */
14100
14101                 ret = drm_atomic_add_affected_connectors(state, crtc);
14102                 if (ret)
14103                         return ret;
14104
14105                 ret = intel_modeset_pipe_config(crtc, pipe_config);
14106                 if (ret) {
14107                         intel_dump_pipe_config(to_intel_crtc(crtc),
14108                                                pipe_config, "[failed]");
14109                         return ret;
14110                 }
14111
14112                 if (i915.fastboot &&
14113                     intel_pipe_config_compare(dev_priv,
14114                                         to_intel_crtc_state(crtc->state),
14115                                         pipe_config, true)) {
14116                         crtc_state->mode_changed = false;
14117                         to_intel_crtc_state(crtc_state)->update_pipe = true;
14118                 }
14119
14120                 if (needs_modeset(crtc_state))
14121                         any_ms = true;
14122
14123                 ret = drm_atomic_add_affected_planes(state, crtc);
14124                 if (ret)
14125                         return ret;
14126
14127                 intel_dump_pipe_config(to_intel_crtc(crtc), pipe_config,
14128                                        needs_modeset(crtc_state) ?
14129                                        "[modeset]" : "[fastset]");
14130         }
14131
14132         if (any_ms) {
14133                 ret = intel_modeset_checks(state);
14134
14135                 if (ret)
14136                         return ret;
14137         } else {
14138                 intel_state->cdclk = dev_priv->atomic_cdclk_freq;
14139         }
14140
14141         ret = drm_atomic_helper_check_planes(dev, state);
14142         if (ret)
14143                 return ret;
14144
14145         intel_fbc_choose_crtc(dev_priv, state);
14146         return calc_watermark_data(state);
14147 }
14148
14149 static int intel_atomic_prepare_commit(struct drm_device *dev,
14150                                        struct drm_atomic_state *state)
14151 {
14152         struct drm_i915_private *dev_priv = to_i915(dev);
14153         struct drm_crtc_state *crtc_state;
14154         struct drm_crtc *crtc;
14155         int i, ret;
14156
14157         for_each_crtc_in_state(state, crtc, crtc_state, i) {
14158                 if (state->legacy_cursor_update)
14159                         continue;
14160
14161                 ret = intel_crtc_wait_for_pending_flips(crtc);
14162                 if (ret)
14163                         return ret;
14164
14165                 if (atomic_read(&to_intel_crtc(crtc)->unpin_work_count) >= 2)
14166                         flush_workqueue(dev_priv->wq);
14167         }
14168
14169         ret = mutex_lock_interruptible(&dev->struct_mutex);
14170         if (ret)
14171                 return ret;
14172
14173         ret = drm_atomic_helper_prepare_planes(dev, state);
14174         mutex_unlock(&dev->struct_mutex);
14175
14176         return ret;
14177 }
14178
14179 u32 intel_crtc_get_vblank_counter(struct intel_crtc *crtc)
14180 {
14181         struct drm_device *dev = crtc->base.dev;
14182
14183         if (!dev->max_vblank_count)
14184                 return drm_accurate_vblank_count(&crtc->base);
14185
14186         return dev->driver->get_vblank_counter(dev, crtc->pipe);
14187 }
14188
14189 static void intel_atomic_wait_for_vblanks(struct drm_device *dev,
14190                                           struct drm_i915_private *dev_priv,
14191                                           unsigned crtc_mask)
14192 {
14193         unsigned last_vblank_count[I915_MAX_PIPES];
14194         enum pipe pipe;
14195         int ret;
14196
14197         if (!crtc_mask)
14198                 return;
14199
14200         for_each_pipe(dev_priv, pipe) {
14201                 struct intel_crtc *crtc = intel_get_crtc_for_pipe(dev_priv,
14202                                                                   pipe);
14203
14204                 if (!((1 << pipe) & crtc_mask))
14205                         continue;
14206
14207                 ret = drm_crtc_vblank_get(&crtc->base);
14208                 if (WARN_ON(ret != 0)) {
14209                         crtc_mask &= ~(1 << pipe);
14210                         continue;
14211                 }
14212
14213                 last_vblank_count[pipe] = drm_crtc_vblank_count(&crtc->base);
14214         }
14215
14216         for_each_pipe(dev_priv, pipe) {
14217                 struct intel_crtc *crtc = intel_get_crtc_for_pipe(dev_priv,
14218                                                                   pipe);
14219                 long lret;
14220
14221                 if (!((1 << pipe) & crtc_mask))
14222                         continue;
14223
14224                 lret = wait_event_timeout(dev->vblank[pipe].queue,
14225                                 last_vblank_count[pipe] !=
14226                                         drm_crtc_vblank_count(&crtc->base),
14227                                 msecs_to_jiffies(50));
14228
14229                 WARN(!lret, "pipe %c vblank wait timed out\n", pipe_name(pipe));
14230
14231                 drm_crtc_vblank_put(&crtc->base);
14232         }
14233 }
14234
14235 static bool needs_vblank_wait(struct intel_crtc_state *crtc_state)
14236 {
14237         /* fb updated, need to unpin old fb */
14238         if (crtc_state->fb_changed)
14239                 return true;
14240
14241         /* wm changes, need vblank before final wm's */
14242         if (crtc_state->update_wm_post)
14243                 return true;
14244
14245         /*
14246          * cxsr is re-enabled after vblank.
14247          * This is already handled by crtc_state->update_wm_post,
14248          * but added for clarity.
14249          */
14250         if (crtc_state->disable_cxsr)
14251                 return true;
14252
14253         return false;
14254 }
14255
14256 static void intel_update_crtc(struct drm_crtc *crtc,
14257                               struct drm_atomic_state *state,
14258                               struct drm_crtc_state *old_crtc_state,
14259                               unsigned int *crtc_vblank_mask)
14260 {
14261         struct drm_device *dev = crtc->dev;
14262         struct drm_i915_private *dev_priv = to_i915(dev);
14263         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
14264         struct intel_crtc_state *pipe_config = to_intel_crtc_state(crtc->state);
14265         bool modeset = needs_modeset(crtc->state);
14266
14267         if (modeset) {
14268                 update_scanline_offset(intel_crtc);
14269                 dev_priv->display.crtc_enable(pipe_config, state);
14270         } else {
14271                 intel_pre_plane_update(to_intel_crtc_state(old_crtc_state));
14272         }
14273
14274         if (drm_atomic_get_existing_plane_state(state, crtc->primary)) {
14275                 intel_fbc_enable(
14276                     intel_crtc, pipe_config,
14277                     to_intel_plane_state(crtc->primary->state));
14278         }
14279
14280         drm_atomic_helper_commit_planes_on_crtc(old_crtc_state);
14281
14282         if (needs_vblank_wait(pipe_config))
14283                 *crtc_vblank_mask |= drm_crtc_mask(crtc);
14284 }
14285
14286 static void intel_update_crtcs(struct drm_atomic_state *state,
14287                                unsigned int *crtc_vblank_mask)
14288 {
14289         struct drm_crtc *crtc;
14290         struct drm_crtc_state *old_crtc_state;
14291         int i;
14292
14293         for_each_crtc_in_state(state, crtc, old_crtc_state, i) {
14294                 if (!crtc->state->active)
14295                         continue;
14296
14297                 intel_update_crtc(crtc, state, old_crtc_state,
14298                                   crtc_vblank_mask);
14299         }
14300 }
14301
14302 static void skl_update_crtcs(struct drm_atomic_state *state,
14303                              unsigned int *crtc_vblank_mask)
14304 {
14305         struct drm_i915_private *dev_priv = to_i915(state->dev);
14306         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
14307         struct drm_crtc *crtc;
14308         struct intel_crtc *intel_crtc;
14309         struct drm_crtc_state *old_crtc_state;
14310         struct intel_crtc_state *cstate;
14311         unsigned int updated = 0;
14312         bool progress;
14313         enum pipe pipe;
14314         int i;
14315
14316         const struct skl_ddb_entry *entries[I915_MAX_PIPES] = {};
14317
14318         for_each_crtc_in_state(state, crtc, old_crtc_state, i)
14319                 /* ignore allocations for crtc's that have been turned off. */
14320                 if (crtc->state->active)
14321                         entries[i] = &to_intel_crtc_state(old_crtc_state)->wm.skl.ddb;
14322
14323         /*
14324          * Whenever the number of active pipes changes, we need to make sure we
14325          * update the pipes in the right order so that their ddb allocations
14326          * never overlap with eachother inbetween CRTC updates. Otherwise we'll
14327          * cause pipe underruns and other bad stuff.
14328          */
14329         do {
14330                 progress = false;
14331
14332                 for_each_crtc_in_state(state, crtc, old_crtc_state, i) {
14333                         bool vbl_wait = false;
14334                         unsigned int cmask = drm_crtc_mask(crtc);
14335
14336                         intel_crtc = to_intel_crtc(crtc);
14337                         cstate = to_intel_crtc_state(crtc->state);
14338                         pipe = intel_crtc->pipe;
14339
14340                         if (updated & cmask || !cstate->base.active)
14341                                 continue;
14342
14343                         if (skl_ddb_allocation_overlaps(entries, &cstate->wm.skl.ddb, i))
14344                                 continue;
14345
14346                         updated |= cmask;
14347                         entries[i] = &cstate->wm.skl.ddb;
14348
14349                         /*
14350                          * If this is an already active pipe, it's DDB changed,
14351                          * and this isn't the last pipe that needs updating
14352                          * then we need to wait for a vblank to pass for the
14353                          * new ddb allocation to take effect.
14354                          */
14355                         if (!skl_ddb_entry_equal(&cstate->wm.skl.ddb,
14356                                                  &to_intel_crtc_state(old_crtc_state)->wm.skl.ddb) &&
14357                             !crtc->state->active_changed &&
14358                             intel_state->wm_results.dirty_pipes != updated)
14359                                 vbl_wait = true;
14360
14361                         intel_update_crtc(crtc, state, old_crtc_state,
14362                                           crtc_vblank_mask);
14363
14364                         if (vbl_wait)
14365                                 intel_wait_for_vblank(dev_priv, pipe);
14366
14367                         progress = true;
14368                 }
14369         } while (progress);
14370 }
14371
14372 static void intel_atomic_helper_free_state(struct drm_i915_private *dev_priv)
14373 {
14374         struct intel_atomic_state *state, *next;
14375         struct llist_node *freed;
14376
14377         freed = llist_del_all(&dev_priv->atomic_helper.free_list);
14378         llist_for_each_entry_safe(state, next, freed, freed)
14379                 drm_atomic_state_put(&state->base);
14380 }
14381
14382 static void intel_atomic_helper_free_state_worker(struct work_struct *work)
14383 {
14384         struct drm_i915_private *dev_priv =
14385                 container_of(work, typeof(*dev_priv), atomic_helper.free_work);
14386
14387         intel_atomic_helper_free_state(dev_priv);
14388 }
14389
14390 static void intel_atomic_commit_tail(struct drm_atomic_state *state)
14391 {
14392         struct drm_device *dev = state->dev;
14393         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
14394         struct drm_i915_private *dev_priv = to_i915(dev);
14395         struct drm_crtc_state *old_crtc_state;
14396         struct drm_crtc *crtc;
14397         struct intel_crtc_state *intel_cstate;
14398         bool hw_check = intel_state->modeset;
14399         unsigned long put_domains[I915_MAX_PIPES] = {};
14400         unsigned crtc_vblank_mask = 0;
14401         int i;
14402
14403         drm_atomic_helper_wait_for_dependencies(state);
14404
14405         if (intel_state->modeset)
14406                 intel_display_power_get(dev_priv, POWER_DOMAIN_MODESET);
14407
14408         for_each_crtc_in_state(state, crtc, old_crtc_state, i) {
14409                 struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
14410
14411                 if (needs_modeset(crtc->state) ||
14412                     to_intel_crtc_state(crtc->state)->update_pipe) {
14413                         hw_check = true;
14414
14415                         put_domains[to_intel_crtc(crtc)->pipe] =
14416                                 modeset_get_crtc_power_domains(crtc,
14417                                         to_intel_crtc_state(crtc->state));
14418                 }
14419
14420                 if (!needs_modeset(crtc->state))
14421                         continue;
14422
14423                 intel_pre_plane_update(to_intel_crtc_state(old_crtc_state));
14424
14425                 if (old_crtc_state->active) {
14426                         intel_crtc_disable_planes(crtc, old_crtc_state->plane_mask);
14427                         dev_priv->display.crtc_disable(to_intel_crtc_state(old_crtc_state), state);
14428                         intel_crtc->active = false;
14429                         intel_fbc_disable(intel_crtc);
14430                         intel_disable_shared_dpll(intel_crtc);
14431
14432                         /*
14433                          * Underruns don't always raise
14434                          * interrupts, so check manually.
14435                          */
14436                         intel_check_cpu_fifo_underruns(dev_priv);
14437                         intel_check_pch_fifo_underruns(dev_priv);
14438
14439                         if (!crtc->state->active) {
14440                                 /*
14441                                  * Make sure we don't call initial_watermarks
14442                                  * for ILK-style watermark updates.
14443                                  */
14444                                 if (dev_priv->display.atomic_update_watermarks)
14445                                         dev_priv->display.initial_watermarks(intel_state,
14446                                                                              to_intel_crtc_state(crtc->state));
14447                                 else
14448                                         intel_update_watermarks(intel_crtc);
14449                         }
14450                 }
14451         }
14452
14453         /* Only after disabling all output pipelines that will be changed can we
14454          * update the the output configuration. */
14455         intel_modeset_update_crtc_state(state);
14456
14457         if (intel_state->modeset) {
14458                 drm_atomic_helper_update_legacy_modeset_state(state->dev, state);
14459
14460                 if (dev_priv->display.modeset_commit_cdclk &&
14461                     (intel_state->dev_cdclk != dev_priv->cdclk_freq ||
14462                      intel_state->cdclk_pll_vco != dev_priv->cdclk_pll.vco))
14463                         dev_priv->display.modeset_commit_cdclk(state);
14464
14465                 /*
14466                  * SKL workaround: bspec recommends we disable the SAGV when we
14467                  * have more then one pipe enabled
14468                  */
14469                 if (!intel_can_enable_sagv(state))
14470                         intel_disable_sagv(dev_priv);
14471
14472                 intel_modeset_verify_disabled(dev, state);
14473         }
14474
14475         /* Complete the events for pipes that have now been disabled */
14476         for_each_crtc_in_state(state, crtc, old_crtc_state, i) {
14477                 bool modeset = needs_modeset(crtc->state);
14478
14479                 /* Complete events for now disable pipes here. */
14480                 if (modeset && !crtc->state->active && crtc->state->event) {
14481                         spin_lock_irq(&dev->event_lock);
14482                         drm_crtc_send_vblank_event(crtc, crtc->state->event);
14483                         spin_unlock_irq(&dev->event_lock);
14484
14485                         crtc->state->event = NULL;
14486                 }
14487         }
14488
14489         /* Now enable the clocks, plane, pipe, and connectors that we set up. */
14490         dev_priv->display.update_crtcs(state, &crtc_vblank_mask);
14491
14492         /* FIXME: We should call drm_atomic_helper_commit_hw_done() here
14493          * already, but still need the state for the delayed optimization. To
14494          * fix this:
14495          * - wrap the optimization/post_plane_update stuff into a per-crtc work.
14496          * - schedule that vblank worker _before_ calling hw_done
14497          * - at the start of commit_tail, cancel it _synchrously
14498          * - switch over to the vblank wait helper in the core after that since
14499          *   we don't need out special handling any more.
14500          */
14501         if (!state->legacy_cursor_update)
14502                 intel_atomic_wait_for_vblanks(dev, dev_priv, crtc_vblank_mask);
14503
14504         /*
14505          * Now that the vblank has passed, we can go ahead and program the
14506          * optimal watermarks on platforms that need two-step watermark
14507          * programming.
14508          *
14509          * TODO: Move this (and other cleanup) to an async worker eventually.
14510          */
14511         for_each_crtc_in_state(state, crtc, old_crtc_state, i) {
14512                 intel_cstate = to_intel_crtc_state(crtc->state);
14513
14514                 if (dev_priv->display.optimize_watermarks)
14515                         dev_priv->display.optimize_watermarks(intel_state,
14516                                                               intel_cstate);
14517         }
14518
14519         for_each_crtc_in_state(state, crtc, old_crtc_state, i) {
14520                 intel_post_plane_update(to_intel_crtc_state(old_crtc_state));
14521
14522                 if (put_domains[i])
14523                         modeset_put_power_domains(dev_priv, put_domains[i]);
14524
14525                 intel_modeset_verify_crtc(crtc, state, old_crtc_state, crtc->state);
14526         }
14527
14528         if (intel_state->modeset && intel_can_enable_sagv(state))
14529                 intel_enable_sagv(dev_priv);
14530
14531         drm_atomic_helper_commit_hw_done(state);
14532
14533         if (intel_state->modeset)
14534                 intel_display_power_put(dev_priv, POWER_DOMAIN_MODESET);
14535
14536         mutex_lock(&dev->struct_mutex);
14537         drm_atomic_helper_cleanup_planes(dev, state);
14538         mutex_unlock(&dev->struct_mutex);
14539
14540         drm_atomic_helper_commit_cleanup_done(state);
14541
14542         drm_atomic_state_put(state);
14543
14544         /* As one of the primary mmio accessors, KMS has a high likelihood
14545          * of triggering bugs in unclaimed access. After we finish
14546          * modesetting, see if an error has been flagged, and if so
14547          * enable debugging for the next modeset - and hope we catch
14548          * the culprit.
14549          *
14550          * XXX note that we assume display power is on at this point.
14551          * This might hold true now but we need to add pm helper to check
14552          * unclaimed only when the hardware is on, as atomic commits
14553          * can happen also when the device is completely off.
14554          */
14555         intel_uncore_arm_unclaimed_mmio_detection(dev_priv);
14556
14557         intel_atomic_helper_free_state(dev_priv);
14558 }
14559
14560 static void intel_atomic_commit_work(struct work_struct *work)
14561 {
14562         struct drm_atomic_state *state =
14563                 container_of(work, struct drm_atomic_state, commit_work);
14564
14565         intel_atomic_commit_tail(state);
14566 }
14567
14568 static int __i915_sw_fence_call
14569 intel_atomic_commit_ready(struct i915_sw_fence *fence,
14570                           enum i915_sw_fence_notify notify)
14571 {
14572         struct intel_atomic_state *state =
14573                 container_of(fence, struct intel_atomic_state, commit_ready);
14574
14575         switch (notify) {
14576         case FENCE_COMPLETE:
14577                 if (state->base.commit_work.func)
14578                         queue_work(system_unbound_wq, &state->base.commit_work);
14579                 break;
14580
14581         case FENCE_FREE:
14582                 {
14583                         struct intel_atomic_helper *helper =
14584                                 &to_i915(state->base.dev)->atomic_helper;
14585
14586                         if (llist_add(&state->freed, &helper->free_list))
14587                                 schedule_work(&helper->free_work);
14588                         break;
14589                 }
14590         }
14591
14592         return NOTIFY_DONE;
14593 }
14594
14595 static void intel_atomic_track_fbs(struct drm_atomic_state *state)
14596 {
14597         struct drm_plane_state *old_plane_state;
14598         struct drm_plane *plane;
14599         int i;
14600
14601         for_each_plane_in_state(state, plane, old_plane_state, i)
14602                 i915_gem_track_fb(intel_fb_obj(old_plane_state->fb),
14603                                   intel_fb_obj(plane->state->fb),
14604                                   to_intel_plane(plane)->frontbuffer_bit);
14605 }
14606
14607 /**
14608  * intel_atomic_commit - commit validated state object
14609  * @dev: DRM device
14610  * @state: the top-level driver state object
14611  * @nonblock: nonblocking commit
14612  *
14613  * This function commits a top-level state object that has been validated
14614  * with drm_atomic_helper_check().
14615  *
14616  * RETURNS
14617  * Zero for success or -errno.
14618  */
14619 static int intel_atomic_commit(struct drm_device *dev,
14620                                struct drm_atomic_state *state,
14621                                bool nonblock)
14622 {
14623         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
14624         struct drm_i915_private *dev_priv = to_i915(dev);
14625         int ret = 0;
14626
14627         ret = drm_atomic_helper_setup_commit(state, nonblock);
14628         if (ret)
14629                 return ret;
14630
14631         drm_atomic_state_get(state);
14632         i915_sw_fence_init(&intel_state->commit_ready,
14633                            intel_atomic_commit_ready);
14634
14635         ret = intel_atomic_prepare_commit(dev, state);
14636         if (ret) {
14637                 DRM_DEBUG_ATOMIC("Preparing state failed with %i\n", ret);
14638                 i915_sw_fence_commit(&intel_state->commit_ready);
14639                 return ret;
14640         }
14641
14642         drm_atomic_helper_swap_state(state, true);
14643         dev_priv->wm.distrust_bios_wm = false;
14644         intel_shared_dpll_swap_state(state);
14645         intel_atomic_track_fbs(state);
14646
14647         if (intel_state->modeset) {
14648                 memcpy(dev_priv->min_pixclk, intel_state->min_pixclk,
14649                        sizeof(intel_state->min_pixclk));
14650                 dev_priv->active_crtcs = intel_state->active_crtcs;
14651                 dev_priv->atomic_cdclk_freq = intel_state->cdclk;
14652         }
14653
14654         drm_atomic_state_get(state);
14655         INIT_WORK(&state->commit_work,
14656                   nonblock ? intel_atomic_commit_work : NULL);
14657
14658         i915_sw_fence_commit(&intel_state->commit_ready);
14659         if (!nonblock) {
14660                 i915_sw_fence_wait(&intel_state->commit_ready);
14661                 intel_atomic_commit_tail(state);
14662         }
14663
14664         return 0;
14665 }
14666
14667 void intel_crtc_restore_mode(struct drm_crtc *crtc)
14668 {
14669         struct drm_device *dev = crtc->dev;
14670         struct drm_atomic_state *state;
14671         struct drm_crtc_state *crtc_state;
14672         int ret;
14673
14674         state = drm_atomic_state_alloc(dev);
14675         if (!state) {
14676                 DRM_DEBUG_KMS("[CRTC:%d:%s] crtc restore failed, out of memory",
14677                               crtc->base.id, crtc->name);
14678                 return;
14679         }
14680
14681         state->acquire_ctx = drm_modeset_legacy_acquire_ctx(crtc);
14682
14683 retry:
14684         crtc_state = drm_atomic_get_crtc_state(state, crtc);
14685         ret = PTR_ERR_OR_ZERO(crtc_state);
14686         if (!ret) {
14687                 if (!crtc_state->active)
14688                         goto out;
14689
14690                 crtc_state->mode_changed = true;
14691                 ret = drm_atomic_commit(state);
14692         }
14693
14694         if (ret == -EDEADLK) {
14695                 drm_atomic_state_clear(state);
14696                 drm_modeset_backoff(state->acquire_ctx);
14697                 goto retry;
14698         }
14699
14700 out:
14701         drm_atomic_state_put(state);
14702 }
14703
14704 /*
14705  * FIXME: Remove this once i915 is fully DRIVER_ATOMIC by calling
14706  *        drm_atomic_helper_legacy_gamma_set() directly.
14707  */
14708 static int intel_atomic_legacy_gamma_set(struct drm_crtc *crtc,
14709                                          u16 *red, u16 *green, u16 *blue,
14710                                          uint32_t size)
14711 {
14712         struct drm_device *dev = crtc->dev;
14713         struct drm_mode_config *config = &dev->mode_config;
14714         struct drm_crtc_state *state;
14715         int ret;
14716
14717         ret = drm_atomic_helper_legacy_gamma_set(crtc, red, green, blue, size);
14718         if (ret)
14719                 return ret;
14720
14721         /*
14722          * Make sure we update the legacy properties so this works when
14723          * atomic is not enabled.
14724          */
14725
14726         state = crtc->state;
14727
14728         drm_object_property_set_value(&crtc->base,
14729                                       config->degamma_lut_property,
14730                                       (state->degamma_lut) ?
14731                                       state->degamma_lut->base.id : 0);
14732
14733         drm_object_property_set_value(&crtc->base,
14734                                       config->ctm_property,
14735                                       (state->ctm) ?
14736                                       state->ctm->base.id : 0);
14737
14738         drm_object_property_set_value(&crtc->base,
14739                                       config->gamma_lut_property,
14740                                       (state->gamma_lut) ?
14741                                       state->gamma_lut->base.id : 0);
14742
14743         return 0;
14744 }
14745
14746 static const struct drm_crtc_funcs intel_crtc_funcs = {
14747         .gamma_set = intel_atomic_legacy_gamma_set,
14748         .set_config = drm_atomic_helper_set_config,
14749         .set_property = drm_atomic_helper_crtc_set_property,
14750         .destroy = intel_crtc_destroy,
14751         .page_flip = intel_crtc_page_flip,
14752         .atomic_duplicate_state = intel_crtc_duplicate_state,
14753         .atomic_destroy_state = intel_crtc_destroy_state,
14754         .set_crc_source = intel_crtc_set_crc_source,
14755 };
14756
14757 /**
14758  * intel_prepare_plane_fb - Prepare fb for usage on plane
14759  * @plane: drm plane to prepare for
14760  * @fb: framebuffer to prepare for presentation
14761  *
14762  * Prepares a framebuffer for usage on a display plane.  Generally this
14763  * involves pinning the underlying object and updating the frontbuffer tracking
14764  * bits.  Some older platforms need special physical address handling for
14765  * cursor planes.
14766  *
14767  * Must be called with struct_mutex held.
14768  *
14769  * Returns 0 on success, negative error code on failure.
14770  */
14771 int
14772 intel_prepare_plane_fb(struct drm_plane *plane,
14773                        struct drm_plane_state *new_state)
14774 {
14775         struct intel_atomic_state *intel_state =
14776                 to_intel_atomic_state(new_state->state);
14777         struct drm_i915_private *dev_priv = to_i915(plane->dev);
14778         struct drm_framebuffer *fb = new_state->fb;
14779         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
14780         struct drm_i915_gem_object *old_obj = intel_fb_obj(plane->state->fb);
14781         int ret;
14782
14783         if (!obj && !old_obj)
14784                 return 0;
14785
14786         if (old_obj) {
14787                 struct drm_crtc_state *crtc_state =
14788                         drm_atomic_get_existing_crtc_state(new_state->state,
14789                                                            plane->state->crtc);
14790
14791                 /* Big Hammer, we also need to ensure that any pending
14792                  * MI_WAIT_FOR_EVENT inside a user batch buffer on the
14793                  * current scanout is retired before unpinning the old
14794                  * framebuffer. Note that we rely on userspace rendering
14795                  * into the buffer attached to the pipe they are waiting
14796                  * on. If not, userspace generates a GPU hang with IPEHR
14797                  * point to the MI_WAIT_FOR_EVENT.
14798                  *
14799                  * This should only fail upon a hung GPU, in which case we
14800                  * can safely continue.
14801                  */
14802                 if (needs_modeset(crtc_state)) {
14803                         ret = i915_sw_fence_await_reservation(&intel_state->commit_ready,
14804                                                               old_obj->resv, NULL,
14805                                                               false, 0,
14806                                                               GFP_KERNEL);
14807                         if (ret < 0)
14808                                 return ret;
14809                 }
14810         }
14811
14812         if (new_state->fence) { /* explicit fencing */
14813                 ret = i915_sw_fence_await_dma_fence(&intel_state->commit_ready,
14814                                                     new_state->fence,
14815                                                     I915_FENCE_TIMEOUT,
14816                                                     GFP_KERNEL);
14817                 if (ret < 0)
14818                         return ret;
14819         }
14820
14821         if (!obj)
14822                 return 0;
14823
14824         if (!new_state->fence) { /* implicit fencing */
14825                 ret = i915_sw_fence_await_reservation(&intel_state->commit_ready,
14826                                                       obj->resv, NULL,
14827                                                       false, I915_FENCE_TIMEOUT,
14828                                                       GFP_KERNEL);
14829                 if (ret < 0)
14830                         return ret;
14831
14832                 i915_gem_object_wait_priority(obj, 0, I915_PRIORITY_DISPLAY);
14833         }
14834
14835         if (plane->type == DRM_PLANE_TYPE_CURSOR &&
14836             INTEL_INFO(dev_priv)->cursor_needs_physical) {
14837                 int align = IS_I830(dev_priv) ? 16 * 1024 : 256;
14838                 ret = i915_gem_object_attach_phys(obj, align);
14839                 if (ret) {
14840                         DRM_DEBUG_KMS("failed to attach phys object\n");
14841                         return ret;
14842                 }
14843         } else {
14844                 struct i915_vma *vma;
14845
14846                 vma = intel_pin_and_fence_fb_obj(fb, new_state->rotation);
14847                 if (IS_ERR(vma)) {
14848                         DRM_DEBUG_KMS("failed to pin object\n");
14849                         return PTR_ERR(vma);
14850                 }
14851
14852                 to_intel_plane_state(new_state)->vma = vma;
14853         }
14854
14855         return 0;
14856 }
14857
14858 /**
14859  * intel_cleanup_plane_fb - Cleans up an fb after plane use
14860  * @plane: drm plane to clean up for
14861  * @fb: old framebuffer that was on plane
14862  *
14863  * Cleans up a framebuffer that has just been removed from a plane.
14864  *
14865  * Must be called with struct_mutex held.
14866  */
14867 void
14868 intel_cleanup_plane_fb(struct drm_plane *plane,
14869                        struct drm_plane_state *old_state)
14870 {
14871         struct i915_vma *vma;
14872
14873         /* Should only be called after a successful intel_prepare_plane_fb()! */
14874         vma = fetch_and_zero(&to_intel_plane_state(old_state)->vma);
14875         if (vma)
14876                 intel_unpin_fb_vma(vma);
14877 }
14878
14879 int
14880 skl_max_scale(struct intel_crtc *intel_crtc, struct intel_crtc_state *crtc_state)
14881 {
14882         int max_scale;
14883         int crtc_clock, cdclk;
14884
14885         if (!intel_crtc || !crtc_state->base.enable)
14886                 return DRM_PLANE_HELPER_NO_SCALING;
14887
14888         crtc_clock = crtc_state->base.adjusted_mode.crtc_clock;
14889         cdclk = to_intel_atomic_state(crtc_state->base.state)->cdclk;
14890
14891         if (WARN_ON_ONCE(!crtc_clock || cdclk < crtc_clock))
14892                 return DRM_PLANE_HELPER_NO_SCALING;
14893
14894         /*
14895          * skl max scale is lower of:
14896          *    close to 3 but not 3, -1 is for that purpose
14897          *            or
14898          *    cdclk/crtc_clock
14899          */
14900         max_scale = min((1 << 16) * 3 - 1, (1 << 8) * ((cdclk << 8) / crtc_clock));
14901
14902         return max_scale;
14903 }
14904
14905 static int
14906 intel_check_primary_plane(struct drm_plane *plane,
14907                           struct intel_crtc_state *crtc_state,
14908                           struct intel_plane_state *state)
14909 {
14910         struct drm_i915_private *dev_priv = to_i915(plane->dev);
14911         struct drm_crtc *crtc = state->base.crtc;
14912         int min_scale = DRM_PLANE_HELPER_NO_SCALING;
14913         int max_scale = DRM_PLANE_HELPER_NO_SCALING;
14914         bool can_position = false;
14915         int ret;
14916
14917         if (INTEL_GEN(dev_priv) >= 9) {
14918                 /* use scaler when colorkey is not required */
14919                 if (state->ckey.flags == I915_SET_COLORKEY_NONE) {
14920                         min_scale = 1;
14921                         max_scale = skl_max_scale(to_intel_crtc(crtc), crtc_state);
14922                 }
14923                 can_position = true;
14924         }
14925
14926         ret = drm_plane_helper_check_state(&state->base,
14927                                            &state->clip,
14928                                            min_scale, max_scale,
14929                                            can_position, true);
14930         if (ret)
14931                 return ret;
14932
14933         if (!state->base.fb)
14934                 return 0;
14935
14936         if (INTEL_GEN(dev_priv) >= 9) {
14937                 ret = skl_check_plane_surface(state);
14938                 if (ret)
14939                         return ret;
14940         }
14941
14942         return 0;
14943 }
14944
14945 static void intel_begin_crtc_commit(struct drm_crtc *crtc,
14946                                     struct drm_crtc_state *old_crtc_state)
14947 {
14948         struct drm_device *dev = crtc->dev;
14949         struct drm_i915_private *dev_priv = to_i915(dev);
14950         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
14951         struct intel_crtc_state *intel_cstate =
14952                 to_intel_crtc_state(crtc->state);
14953         struct intel_crtc_state *old_intel_cstate =
14954                 to_intel_crtc_state(old_crtc_state);
14955         struct intel_atomic_state *old_intel_state =
14956                 to_intel_atomic_state(old_crtc_state->state);
14957         bool modeset = needs_modeset(crtc->state);
14958
14959         if (!modeset &&
14960             (intel_cstate->base.color_mgmt_changed ||
14961              intel_cstate->update_pipe)) {
14962                 intel_color_set_csc(crtc->state);
14963                 intel_color_load_luts(crtc->state);
14964         }
14965
14966         /* Perform vblank evasion around commit operation */
14967         intel_pipe_update_start(intel_crtc);
14968
14969         if (modeset)
14970                 goto out;
14971
14972         if (intel_cstate->update_pipe)
14973                 intel_update_pipe_config(intel_crtc, old_intel_cstate);
14974         else if (INTEL_GEN(dev_priv) >= 9)
14975                 skl_detach_scalers(intel_crtc);
14976
14977 out:
14978         if (dev_priv->display.atomic_update_watermarks)
14979                 dev_priv->display.atomic_update_watermarks(old_intel_state,
14980                                                            intel_cstate);
14981 }
14982
14983 static void intel_finish_crtc_commit(struct drm_crtc *crtc,
14984                                      struct drm_crtc_state *old_crtc_state)
14985 {
14986         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
14987
14988         intel_pipe_update_end(intel_crtc, NULL);
14989 }
14990
14991 /**
14992  * intel_plane_destroy - destroy a plane
14993  * @plane: plane to destroy
14994  *
14995  * Common destruction function for all types of planes (primary, cursor,
14996  * sprite).
14997  */
14998 void intel_plane_destroy(struct drm_plane *plane)
14999 {
15000         drm_plane_cleanup(plane);
15001         kfree(to_intel_plane(plane));
15002 }
15003
15004 const struct drm_plane_funcs intel_plane_funcs = {
15005         .update_plane = drm_atomic_helper_update_plane,
15006         .disable_plane = drm_atomic_helper_disable_plane,
15007         .destroy = intel_plane_destroy,
15008         .set_property = drm_atomic_helper_plane_set_property,
15009         .atomic_get_property = intel_plane_atomic_get_property,
15010         .atomic_set_property = intel_plane_atomic_set_property,
15011         .atomic_duplicate_state = intel_plane_duplicate_state,
15012         .atomic_destroy_state = intel_plane_destroy_state,
15013 };
15014
15015 static int
15016 intel_legacy_cursor_update(struct drm_plane *plane,
15017                            struct drm_crtc *crtc,
15018                            struct drm_framebuffer *fb,
15019                            int crtc_x, int crtc_y,
15020                            unsigned int crtc_w, unsigned int crtc_h,
15021                            uint32_t src_x, uint32_t src_y,
15022                            uint32_t src_w, uint32_t src_h)
15023 {
15024         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
15025         int ret;
15026         struct drm_plane_state *old_plane_state, *new_plane_state;
15027         struct intel_plane *intel_plane = to_intel_plane(plane);
15028         struct drm_framebuffer *old_fb;
15029         struct drm_crtc_state *crtc_state = crtc->state;
15030         struct i915_vma *old_vma;
15031
15032         /*
15033          * When crtc is inactive or there is a modeset pending,
15034          * wait for it to complete in the slowpath
15035          */
15036         if (!crtc_state->active || needs_modeset(crtc_state) ||
15037             to_intel_crtc_state(crtc_state)->update_pipe)
15038                 goto slow;
15039
15040         old_plane_state = plane->state;
15041
15042         /*
15043          * If any parameters change that may affect watermarks,
15044          * take the slowpath. Only changing fb or position should be
15045          * in the fastpath.
15046          */
15047         if (old_plane_state->crtc != crtc ||
15048             old_plane_state->src_w != src_w ||
15049             old_plane_state->src_h != src_h ||
15050             old_plane_state->crtc_w != crtc_w ||
15051             old_plane_state->crtc_h != crtc_h ||
15052             !old_plane_state->visible ||
15053             old_plane_state->fb->modifier != fb->modifier)
15054                 goto slow;
15055
15056         new_plane_state = intel_plane_duplicate_state(plane);
15057         if (!new_plane_state)
15058                 return -ENOMEM;
15059
15060         drm_atomic_set_fb_for_plane(new_plane_state, fb);
15061
15062         new_plane_state->src_x = src_x;
15063         new_plane_state->src_y = src_y;
15064         new_plane_state->src_w = src_w;
15065         new_plane_state->src_h = src_h;
15066         new_plane_state->crtc_x = crtc_x;
15067         new_plane_state->crtc_y = crtc_y;
15068         new_plane_state->crtc_w = crtc_w;
15069         new_plane_state->crtc_h = crtc_h;
15070
15071         ret = intel_plane_atomic_check_with_state(to_intel_crtc_state(crtc->state),
15072                                                   to_intel_plane_state(new_plane_state));
15073         if (ret)
15074                 goto out_free;
15075
15076         /* Visibility changed, must take slowpath. */
15077         if (!new_plane_state->visible)
15078                 goto slow_free;
15079
15080         ret = mutex_lock_interruptible(&dev_priv->drm.struct_mutex);
15081         if (ret)
15082                 goto out_free;
15083
15084         if (INTEL_INFO(dev_priv)->cursor_needs_physical) {
15085                 int align = IS_I830(dev_priv) ? 16 * 1024 : 256;
15086
15087                 ret = i915_gem_object_attach_phys(intel_fb_obj(fb), align);
15088                 if (ret) {
15089                         DRM_DEBUG_KMS("failed to attach phys object\n");
15090                         goto out_unlock;
15091                 }
15092         } else {
15093                 struct i915_vma *vma;
15094
15095                 vma = intel_pin_and_fence_fb_obj(fb, new_plane_state->rotation);
15096                 if (IS_ERR(vma)) {
15097                         DRM_DEBUG_KMS("failed to pin object\n");
15098
15099                         ret = PTR_ERR(vma);
15100                         goto out_unlock;
15101                 }
15102
15103                 to_intel_plane_state(new_plane_state)->vma = vma;
15104         }
15105
15106         old_fb = old_plane_state->fb;
15107         old_vma = to_intel_plane_state(old_plane_state)->vma;
15108
15109         i915_gem_track_fb(intel_fb_obj(old_fb), intel_fb_obj(fb),
15110                           intel_plane->frontbuffer_bit);
15111
15112         /* Swap plane state */
15113         new_plane_state->fence = old_plane_state->fence;
15114         *to_intel_plane_state(old_plane_state) = *to_intel_plane_state(new_plane_state);
15115         new_plane_state->fence = NULL;
15116         new_plane_state->fb = old_fb;
15117         to_intel_plane_state(new_plane_state)->vma = old_vma;
15118
15119         intel_plane->update_plane(plane,
15120                                   to_intel_crtc_state(crtc->state),
15121                                   to_intel_plane_state(plane->state));
15122
15123         intel_cleanup_plane_fb(plane, new_plane_state);
15124
15125 out_unlock:
15126         mutex_unlock(&dev_priv->drm.struct_mutex);
15127 out_free:
15128         intel_plane_destroy_state(plane, new_plane_state);
15129         return ret;
15130
15131 slow_free:
15132         intel_plane_destroy_state(plane, new_plane_state);
15133 slow:
15134         return drm_atomic_helper_update_plane(plane, crtc, fb,
15135                                               crtc_x, crtc_y, crtc_w, crtc_h,
15136                                               src_x, src_y, src_w, src_h);
15137 }
15138
15139 static const struct drm_plane_funcs intel_cursor_plane_funcs = {
15140         .update_plane = intel_legacy_cursor_update,
15141         .disable_plane = drm_atomic_helper_disable_plane,
15142         .destroy = intel_plane_destroy,
15143         .set_property = drm_atomic_helper_plane_set_property,
15144         .atomic_get_property = intel_plane_atomic_get_property,
15145         .atomic_set_property = intel_plane_atomic_set_property,
15146         .atomic_duplicate_state = intel_plane_duplicate_state,
15147         .atomic_destroy_state = intel_plane_destroy_state,
15148 };
15149
15150 static struct intel_plane *
15151 intel_primary_plane_create(struct drm_i915_private *dev_priv, enum pipe pipe)
15152 {
15153         struct intel_plane *primary = NULL;
15154         struct intel_plane_state *state = NULL;
15155         const uint32_t *intel_primary_formats;
15156         unsigned int supported_rotations;
15157         unsigned int num_formats;
15158         int ret;
15159
15160         primary = kzalloc(sizeof(*primary), GFP_KERNEL);
15161         if (!primary) {
15162                 ret = -ENOMEM;
15163                 goto fail;
15164         }
15165
15166         state = intel_create_plane_state(&primary->base);
15167         if (!state) {
15168                 ret = -ENOMEM;
15169                 goto fail;
15170         }
15171
15172         primary->base.state = &state->base;
15173
15174         primary->can_scale = false;
15175         primary->max_downscale = 1;
15176         if (INTEL_GEN(dev_priv) >= 9) {
15177                 primary->can_scale = true;
15178                 state->scaler_id = -1;
15179         }
15180         primary->pipe = pipe;
15181         /*
15182          * On gen2/3 only plane A can do FBC, but the panel fitter and LVDS
15183          * port is hooked to pipe B. Hence we want plane A feeding pipe B.
15184          */
15185         if (HAS_FBC(dev_priv) && INTEL_GEN(dev_priv) < 4)
15186                 primary->plane = (enum plane) !pipe;
15187         else
15188                 primary->plane = (enum plane) pipe;
15189         primary->id = PLANE_PRIMARY;
15190         primary->frontbuffer_bit = INTEL_FRONTBUFFER_PRIMARY(pipe);
15191         primary->check_plane = intel_check_primary_plane;
15192
15193         if (INTEL_GEN(dev_priv) >= 9) {
15194                 intel_primary_formats = skl_primary_formats;
15195                 num_formats = ARRAY_SIZE(skl_primary_formats);
15196
15197                 primary->update_plane = skylake_update_primary_plane;
15198                 primary->disable_plane = skylake_disable_primary_plane;
15199         } else if (HAS_PCH_SPLIT(dev_priv)) {
15200                 intel_primary_formats = i965_primary_formats;
15201                 num_formats = ARRAY_SIZE(i965_primary_formats);
15202
15203                 primary->update_plane = ironlake_update_primary_plane;
15204                 primary->disable_plane = i9xx_disable_primary_plane;
15205         } else if (INTEL_GEN(dev_priv) >= 4) {
15206                 intel_primary_formats = i965_primary_formats;
15207                 num_formats = ARRAY_SIZE(i965_primary_formats);
15208
15209                 primary->update_plane = i9xx_update_primary_plane;
15210                 primary->disable_plane = i9xx_disable_primary_plane;
15211         } else {
15212                 intel_primary_formats = i8xx_primary_formats;
15213                 num_formats = ARRAY_SIZE(i8xx_primary_formats);
15214
15215                 primary->update_plane = i9xx_update_primary_plane;
15216                 primary->disable_plane = i9xx_disable_primary_plane;
15217         }
15218
15219         if (INTEL_GEN(dev_priv) >= 9)
15220                 ret = drm_universal_plane_init(&dev_priv->drm, &primary->base,
15221                                                0, &intel_plane_funcs,
15222                                                intel_primary_formats, num_formats,
15223                                                DRM_PLANE_TYPE_PRIMARY,
15224                                                "plane 1%c", pipe_name(pipe));
15225         else if (INTEL_GEN(dev_priv) >= 5 || IS_G4X(dev_priv))
15226                 ret = drm_universal_plane_init(&dev_priv->drm, &primary->base,
15227                                                0, &intel_plane_funcs,
15228                                                intel_primary_formats, num_formats,
15229                                                DRM_PLANE_TYPE_PRIMARY,
15230                                                "primary %c", pipe_name(pipe));
15231         else
15232                 ret = drm_universal_plane_init(&dev_priv->drm, &primary->base,
15233                                                0, &intel_plane_funcs,
15234                                                intel_primary_formats, num_formats,
15235                                                DRM_PLANE_TYPE_PRIMARY,
15236                                                "plane %c", plane_name(primary->plane));
15237         if (ret)
15238                 goto fail;
15239
15240         if (INTEL_GEN(dev_priv) >= 9) {
15241                 supported_rotations =
15242                         DRM_ROTATE_0 | DRM_ROTATE_90 |
15243                         DRM_ROTATE_180 | DRM_ROTATE_270;
15244         } else if (IS_CHERRYVIEW(dev_priv) && pipe == PIPE_B) {
15245                 supported_rotations =
15246                         DRM_ROTATE_0 | DRM_ROTATE_180 |
15247                         DRM_REFLECT_X;
15248         } else if (INTEL_GEN(dev_priv) >= 4) {
15249                 supported_rotations =
15250                         DRM_ROTATE_0 | DRM_ROTATE_180;
15251         } else {
15252                 supported_rotations = DRM_ROTATE_0;
15253         }
15254
15255         if (INTEL_GEN(dev_priv) >= 4)
15256                 drm_plane_create_rotation_property(&primary->base,
15257                                                    DRM_ROTATE_0,
15258                                                    supported_rotations);
15259
15260         drm_plane_helper_add(&primary->base, &intel_plane_helper_funcs);
15261
15262         return primary;
15263
15264 fail:
15265         kfree(state);
15266         kfree(primary);
15267
15268         return ERR_PTR(ret);
15269 }
15270
15271 static int
15272 intel_check_cursor_plane(struct drm_plane *plane,
15273                          struct intel_crtc_state *crtc_state,
15274                          struct intel_plane_state *state)
15275 {
15276         struct drm_framebuffer *fb = state->base.fb;
15277         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
15278         enum pipe pipe = to_intel_plane(plane)->pipe;
15279         unsigned stride;
15280         int ret;
15281
15282         ret = drm_plane_helper_check_state(&state->base,
15283                                            &state->clip,
15284                                            DRM_PLANE_HELPER_NO_SCALING,
15285                                            DRM_PLANE_HELPER_NO_SCALING,
15286                                            true, true);
15287         if (ret)
15288                 return ret;
15289
15290         /* if we want to turn off the cursor ignore width and height */
15291         if (!obj)
15292                 return 0;
15293
15294         /* Check for which cursor types we support */
15295         if (!cursor_size_ok(to_i915(plane->dev), state->base.crtc_w,
15296                             state->base.crtc_h)) {
15297                 DRM_DEBUG("Cursor dimension %dx%d not supported\n",
15298                           state->base.crtc_w, state->base.crtc_h);
15299                 return -EINVAL;
15300         }
15301
15302         stride = roundup_pow_of_two(state->base.crtc_w) * 4;
15303         if (obj->base.size < stride * state->base.crtc_h) {
15304                 DRM_DEBUG_KMS("buffer is too small\n");
15305                 return -ENOMEM;
15306         }
15307
15308         if (fb->modifier != DRM_FORMAT_MOD_NONE) {
15309                 DRM_DEBUG_KMS("cursor cannot be tiled\n");
15310                 return -EINVAL;
15311         }
15312
15313         /*
15314          * There's something wrong with the cursor on CHV pipe C.
15315          * If it straddles the left edge of the screen then
15316          * moving it away from the edge or disabling it often
15317          * results in a pipe underrun, and often that can lead to
15318          * dead pipe (constant underrun reported, and it scans
15319          * out just a solid color). To recover from that, the
15320          * display power well must be turned off and on again.
15321          * Refuse the put the cursor into that compromised position.
15322          */
15323         if (IS_CHERRYVIEW(to_i915(plane->dev)) && pipe == PIPE_C &&
15324             state->base.visible && state->base.crtc_x < 0) {
15325                 DRM_DEBUG_KMS("CHV cursor C not allowed to straddle the left screen edge\n");
15326                 return -EINVAL;
15327         }
15328
15329         return 0;
15330 }
15331
15332 static void
15333 intel_disable_cursor_plane(struct drm_plane *plane,
15334                            struct drm_crtc *crtc)
15335 {
15336         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
15337
15338         intel_crtc->cursor_addr = 0;
15339         intel_crtc_update_cursor(crtc, NULL);
15340 }
15341
15342 static void
15343 intel_update_cursor_plane(struct drm_plane *plane,
15344                           const struct intel_crtc_state *crtc_state,
15345                           const struct intel_plane_state *state)
15346 {
15347         struct drm_crtc *crtc = crtc_state->base.crtc;
15348         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
15349         struct drm_i915_private *dev_priv = to_i915(plane->dev);
15350         struct drm_i915_gem_object *obj = intel_fb_obj(state->base.fb);
15351         uint32_t addr;
15352
15353         if (!obj)
15354                 addr = 0;
15355         else if (!INTEL_INFO(dev_priv)->cursor_needs_physical)
15356                 addr = intel_plane_ggtt_offset(state);
15357         else
15358                 addr = obj->phys_handle->busaddr;
15359
15360         intel_crtc->cursor_addr = addr;
15361         intel_crtc_update_cursor(crtc, state);
15362 }
15363
15364 static struct intel_plane *
15365 intel_cursor_plane_create(struct drm_i915_private *dev_priv, enum pipe pipe)
15366 {
15367         struct intel_plane *cursor = NULL;
15368         struct intel_plane_state *state = NULL;
15369         int ret;
15370
15371         cursor = kzalloc(sizeof(*cursor), GFP_KERNEL);
15372         if (!cursor) {
15373                 ret = -ENOMEM;
15374                 goto fail;
15375         }
15376
15377         state = intel_create_plane_state(&cursor->base);
15378         if (!state) {
15379                 ret = -ENOMEM;
15380                 goto fail;
15381         }
15382
15383         cursor->base.state = &state->base;
15384
15385         cursor->can_scale = false;
15386         cursor->max_downscale = 1;
15387         cursor->pipe = pipe;
15388         cursor->plane = pipe;
15389         cursor->id = PLANE_CURSOR;
15390         cursor->frontbuffer_bit = INTEL_FRONTBUFFER_CURSOR(pipe);
15391         cursor->check_plane = intel_check_cursor_plane;
15392         cursor->update_plane = intel_update_cursor_plane;
15393         cursor->disable_plane = intel_disable_cursor_plane;
15394
15395         ret = drm_universal_plane_init(&dev_priv->drm, &cursor->base,
15396                                        0, &intel_cursor_plane_funcs,
15397                                        intel_cursor_formats,
15398                                        ARRAY_SIZE(intel_cursor_formats),
15399                                        DRM_PLANE_TYPE_CURSOR,
15400                                        "cursor %c", pipe_name(pipe));
15401         if (ret)
15402                 goto fail;
15403
15404         if (INTEL_GEN(dev_priv) >= 4)
15405                 drm_plane_create_rotation_property(&cursor->base,
15406                                                    DRM_ROTATE_0,
15407                                                    DRM_ROTATE_0 |
15408                                                    DRM_ROTATE_180);
15409
15410         if (INTEL_GEN(dev_priv) >= 9)
15411                 state->scaler_id = -1;
15412
15413         drm_plane_helper_add(&cursor->base, &intel_plane_helper_funcs);
15414
15415         return cursor;
15416
15417 fail:
15418         kfree(state);
15419         kfree(cursor);
15420
15421         return ERR_PTR(ret);
15422 }
15423
15424 static void intel_crtc_init_scalers(struct intel_crtc *crtc,
15425                                     struct intel_crtc_state *crtc_state)
15426 {
15427         struct intel_crtc_scaler_state *scaler_state =
15428                 &crtc_state->scaler_state;
15429         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
15430         int i;
15431
15432         crtc->num_scalers = dev_priv->info.num_scalers[crtc->pipe];
15433         if (!crtc->num_scalers)
15434                 return;
15435
15436         for (i = 0; i < crtc->num_scalers; i++) {
15437                 struct intel_scaler *scaler = &scaler_state->scalers[i];
15438
15439                 scaler->in_use = 0;
15440                 scaler->mode = PS_SCALER_MODE_DYN;
15441         }
15442
15443         scaler_state->scaler_id = -1;
15444 }
15445
15446 static int intel_crtc_init(struct drm_i915_private *dev_priv, enum pipe pipe)
15447 {
15448         struct intel_crtc *intel_crtc;
15449         struct intel_crtc_state *crtc_state = NULL;
15450         struct intel_plane *primary = NULL;
15451         struct intel_plane *cursor = NULL;
15452         int sprite, ret;
15453
15454         intel_crtc = kzalloc(sizeof(*intel_crtc), GFP_KERNEL);
15455         if (!intel_crtc)
15456                 return -ENOMEM;
15457
15458         crtc_state = kzalloc(sizeof(*crtc_state), GFP_KERNEL);
15459         if (!crtc_state) {
15460                 ret = -ENOMEM;
15461                 goto fail;
15462         }
15463         intel_crtc->config = crtc_state;
15464         intel_crtc->base.state = &crtc_state->base;
15465         crtc_state->base.crtc = &intel_crtc->base;
15466
15467         primary = intel_primary_plane_create(dev_priv, pipe);
15468         if (IS_ERR(primary)) {
15469                 ret = PTR_ERR(primary);
15470                 goto fail;
15471         }
15472         intel_crtc->plane_ids_mask |= BIT(primary->id);
15473
15474         for_each_sprite(dev_priv, pipe, sprite) {
15475                 struct intel_plane *plane;
15476
15477                 plane = intel_sprite_plane_create(dev_priv, pipe, sprite);
15478                 if (IS_ERR(plane)) {
15479                         ret = PTR_ERR(plane);
15480                         goto fail;
15481                 }
15482                 intel_crtc->plane_ids_mask |= BIT(plane->id);
15483         }
15484
15485         cursor = intel_cursor_plane_create(dev_priv, pipe);
15486         if (IS_ERR(cursor)) {
15487                 ret = PTR_ERR(cursor);
15488                 goto fail;
15489         }
15490         intel_crtc->plane_ids_mask |= BIT(cursor->id);
15491
15492         ret = drm_crtc_init_with_planes(&dev_priv->drm, &intel_crtc->base,
15493                                         &primary->base, &cursor->base,
15494                                         &intel_crtc_funcs,
15495                                         "pipe %c", pipe_name(pipe));
15496         if (ret)
15497                 goto fail;
15498
15499         intel_crtc->pipe = pipe;
15500         intel_crtc->plane = primary->plane;
15501
15502         intel_crtc->cursor_base = ~0;
15503         intel_crtc->cursor_cntl = ~0;
15504         intel_crtc->cursor_size = ~0;
15505
15506         intel_crtc->wm.cxsr_allowed = true;
15507
15508         /* initialize shared scalers */
15509         intel_crtc_init_scalers(intel_crtc, crtc_state);
15510
15511         BUG_ON(pipe >= ARRAY_SIZE(dev_priv->plane_to_crtc_mapping) ||
15512                dev_priv->plane_to_crtc_mapping[intel_crtc->plane] != NULL);
15513         dev_priv->plane_to_crtc_mapping[intel_crtc->plane] = intel_crtc;
15514         dev_priv->pipe_to_crtc_mapping[intel_crtc->pipe] = intel_crtc;
15515
15516         drm_crtc_helper_add(&intel_crtc->base, &intel_helper_funcs);
15517
15518         intel_color_init(&intel_crtc->base);
15519
15520         WARN_ON(drm_crtc_index(&intel_crtc->base) != intel_crtc->pipe);
15521
15522         return 0;
15523
15524 fail:
15525         /*
15526          * drm_mode_config_cleanup() will free up any
15527          * crtcs/planes already initialized.
15528          */
15529         kfree(crtc_state);
15530         kfree(intel_crtc);
15531
15532         return ret;
15533 }
15534
15535 enum pipe intel_get_pipe_from_connector(struct intel_connector *connector)
15536 {
15537         struct drm_encoder *encoder = connector->base.encoder;
15538         struct drm_device *dev = connector->base.dev;
15539
15540         WARN_ON(!drm_modeset_is_locked(&dev->mode_config.connection_mutex));
15541
15542         if (!encoder || WARN_ON(!encoder->crtc))
15543                 return INVALID_PIPE;
15544
15545         return to_intel_crtc(encoder->crtc)->pipe;
15546 }
15547
15548 int intel_get_pipe_from_crtc_id(struct drm_device *dev, void *data,
15549                                 struct drm_file *file)
15550 {
15551         struct drm_i915_get_pipe_from_crtc_id *pipe_from_crtc_id = data;
15552         struct drm_crtc *drmmode_crtc;
15553         struct intel_crtc *crtc;
15554
15555         drmmode_crtc = drm_crtc_find(dev, pipe_from_crtc_id->crtc_id);
15556         if (!drmmode_crtc)
15557                 return -ENOENT;
15558
15559         crtc = to_intel_crtc(drmmode_crtc);
15560         pipe_from_crtc_id->pipe = crtc->pipe;
15561
15562         return 0;
15563 }
15564
15565 static int intel_encoder_clones(struct intel_encoder *encoder)
15566 {
15567         struct drm_device *dev = encoder->base.dev;
15568         struct intel_encoder *source_encoder;
15569         int index_mask = 0;
15570         int entry = 0;
15571
15572         for_each_intel_encoder(dev, source_encoder) {
15573                 if (encoders_cloneable(encoder, source_encoder))
15574                         index_mask |= (1 << entry);
15575
15576                 entry++;
15577         }
15578
15579         return index_mask;
15580 }
15581
15582 static bool has_edp_a(struct drm_i915_private *dev_priv)
15583 {
15584         if (!IS_MOBILE(dev_priv))
15585                 return false;
15586
15587         if ((I915_READ(DP_A) & DP_DETECTED) == 0)
15588                 return false;
15589
15590         if (IS_GEN5(dev_priv) && (I915_READ(FUSE_STRAP) & ILK_eDP_A_DISABLE))
15591                 return false;
15592
15593         return true;
15594 }
15595
15596 static bool intel_crt_present(struct drm_i915_private *dev_priv)
15597 {
15598         if (INTEL_GEN(dev_priv) >= 9)
15599                 return false;
15600
15601         if (IS_HSW_ULT(dev_priv) || IS_BDW_ULT(dev_priv))
15602                 return false;
15603
15604         if (IS_CHERRYVIEW(dev_priv))
15605                 return false;
15606
15607         if (HAS_PCH_LPT_H(dev_priv) &&
15608             I915_READ(SFUSE_STRAP) & SFUSE_STRAP_CRT_DISABLED)
15609                 return false;
15610
15611         /* DDI E can't be used if DDI A requires 4 lanes */
15612         if (HAS_DDI(dev_priv) && I915_READ(DDI_BUF_CTL(PORT_A)) & DDI_A_4_LANES)
15613                 return false;
15614
15615         if (!dev_priv->vbt.int_crt_support)
15616                 return false;
15617
15618         return true;
15619 }
15620
15621 void intel_pps_unlock_regs_wa(struct drm_i915_private *dev_priv)
15622 {
15623         int pps_num;
15624         int pps_idx;
15625
15626         if (HAS_DDI(dev_priv))
15627                 return;
15628         /*
15629          * This w/a is needed at least on CPT/PPT, but to be sure apply it
15630          * everywhere where registers can be write protected.
15631          */
15632         if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
15633                 pps_num = 2;
15634         else
15635                 pps_num = 1;
15636
15637         for (pps_idx = 0; pps_idx < pps_num; pps_idx++) {
15638                 u32 val = I915_READ(PP_CONTROL(pps_idx));
15639
15640                 val = (val & ~PANEL_UNLOCK_MASK) | PANEL_UNLOCK_REGS;
15641                 I915_WRITE(PP_CONTROL(pps_idx), val);
15642         }
15643 }
15644
15645 static void intel_pps_init(struct drm_i915_private *dev_priv)
15646 {
15647         if (HAS_PCH_SPLIT(dev_priv) || IS_GEN9_LP(dev_priv))
15648                 dev_priv->pps_mmio_base = PCH_PPS_BASE;
15649         else if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
15650                 dev_priv->pps_mmio_base = VLV_PPS_BASE;
15651         else
15652                 dev_priv->pps_mmio_base = PPS_BASE;
15653
15654         intel_pps_unlock_regs_wa(dev_priv);
15655 }
15656
15657 static void intel_setup_outputs(struct drm_i915_private *dev_priv)
15658 {
15659         struct intel_encoder *encoder;
15660         bool dpd_is_edp = false;
15661
15662         intel_pps_init(dev_priv);
15663
15664         /*
15665          * intel_edp_init_connector() depends on this completing first, to
15666          * prevent the registeration of both eDP and LVDS and the incorrect
15667          * sharing of the PPS.
15668          */
15669         intel_lvds_init(dev_priv);
15670
15671         if (intel_crt_present(dev_priv))
15672                 intel_crt_init(dev_priv);
15673
15674         if (IS_GEN9_LP(dev_priv)) {
15675                 /*
15676                  * FIXME: Broxton doesn't support port detection via the
15677                  * DDI_BUF_CTL_A or SFUSE_STRAP registers, find another way to
15678                  * detect the ports.
15679                  */
15680                 intel_ddi_init(dev_priv, PORT_A);
15681                 intel_ddi_init(dev_priv, PORT_B);
15682                 intel_ddi_init(dev_priv, PORT_C);
15683
15684                 intel_dsi_init(dev_priv);
15685         } else if (HAS_DDI(dev_priv)) {
15686                 int found;
15687
15688                 /*
15689                  * Haswell uses DDI functions to detect digital outputs.
15690                  * On SKL pre-D0 the strap isn't connected, so we assume
15691                  * it's there.
15692                  */
15693                 found = I915_READ(DDI_BUF_CTL(PORT_A)) & DDI_INIT_DISPLAY_DETECTED;
15694                 /* WaIgnoreDDIAStrap: skl */
15695                 if (found || IS_SKYLAKE(dev_priv) || IS_KABYLAKE(dev_priv))
15696                         intel_ddi_init(dev_priv, PORT_A);
15697
15698                 /* DDI B, C and D detection is indicated by the SFUSE_STRAP
15699                  * register */
15700                 found = I915_READ(SFUSE_STRAP);
15701
15702                 if (found & SFUSE_STRAP_DDIB_DETECTED)
15703                         intel_ddi_init(dev_priv, PORT_B);
15704                 if (found & SFUSE_STRAP_DDIC_DETECTED)
15705                         intel_ddi_init(dev_priv, PORT_C);
15706                 if (found & SFUSE_STRAP_DDID_DETECTED)
15707                         intel_ddi_init(dev_priv, PORT_D);
15708                 /*
15709                  * On SKL we don't have a way to detect DDI-E so we rely on VBT.
15710                  */
15711                 if ((IS_SKYLAKE(dev_priv) || IS_KABYLAKE(dev_priv)) &&
15712                     (dev_priv->vbt.ddi_port_info[PORT_E].supports_dp ||
15713                      dev_priv->vbt.ddi_port_info[PORT_E].supports_dvi ||
15714                      dev_priv->vbt.ddi_port_info[PORT_E].supports_hdmi))
15715                         intel_ddi_init(dev_priv, PORT_E);
15716
15717         } else if (HAS_PCH_SPLIT(dev_priv)) {
15718                 int found;
15719                 dpd_is_edp = intel_dp_is_edp(dev_priv, PORT_D);
15720
15721                 if (has_edp_a(dev_priv))
15722                         intel_dp_init(dev_priv, DP_A, PORT_A);
15723
15724                 if (I915_READ(PCH_HDMIB) & SDVO_DETECTED) {
15725                         /* PCH SDVOB multiplex with HDMIB */
15726                         found = intel_sdvo_init(dev_priv, PCH_SDVOB, PORT_B);
15727                         if (!found)
15728                                 intel_hdmi_init(dev_priv, PCH_HDMIB, PORT_B);
15729                         if (!found && (I915_READ(PCH_DP_B) & DP_DETECTED))
15730                                 intel_dp_init(dev_priv, PCH_DP_B, PORT_B);
15731                 }
15732
15733                 if (I915_READ(PCH_HDMIC) & SDVO_DETECTED)
15734                         intel_hdmi_init(dev_priv, PCH_HDMIC, PORT_C);
15735
15736                 if (!dpd_is_edp && I915_READ(PCH_HDMID) & SDVO_DETECTED)
15737                         intel_hdmi_init(dev_priv, PCH_HDMID, PORT_D);
15738
15739                 if (I915_READ(PCH_DP_C) & DP_DETECTED)
15740                         intel_dp_init(dev_priv, PCH_DP_C, PORT_C);
15741
15742                 if (I915_READ(PCH_DP_D) & DP_DETECTED)
15743                         intel_dp_init(dev_priv, PCH_DP_D, PORT_D);
15744         } else if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv)) {
15745                 bool has_edp, has_port;
15746
15747                 /*
15748                  * The DP_DETECTED bit is the latched state of the DDC
15749                  * SDA pin at boot. However since eDP doesn't require DDC
15750                  * (no way to plug in a DP->HDMI dongle) the DDC pins for
15751                  * eDP ports may have been muxed to an alternate function.
15752                  * Thus we can't rely on the DP_DETECTED bit alone to detect
15753                  * eDP ports. Consult the VBT as well as DP_DETECTED to
15754                  * detect eDP ports.
15755                  *
15756                  * Sadly the straps seem to be missing sometimes even for HDMI
15757                  * ports (eg. on Voyo V3 - CHT x7-Z8700), so check both strap
15758                  * and VBT for the presence of the port. Additionally we can't
15759                  * trust the port type the VBT declares as we've seen at least
15760                  * HDMI ports that the VBT claim are DP or eDP.
15761                  */
15762                 has_edp = intel_dp_is_edp(dev_priv, PORT_B);
15763                 has_port = intel_bios_is_port_present(dev_priv, PORT_B);
15764                 if (I915_READ(VLV_DP_B) & DP_DETECTED || has_port)
15765                         has_edp &= intel_dp_init(dev_priv, VLV_DP_B, PORT_B);
15766                 if ((I915_READ(VLV_HDMIB) & SDVO_DETECTED || has_port) && !has_edp)
15767                         intel_hdmi_init(dev_priv, VLV_HDMIB, PORT_B);
15768
15769                 has_edp = intel_dp_is_edp(dev_priv, PORT_C);
15770                 has_port = intel_bios_is_port_present(dev_priv, PORT_C);
15771                 if (I915_READ(VLV_DP_C) & DP_DETECTED || has_port)
15772                         has_edp &= intel_dp_init(dev_priv, VLV_DP_C, PORT_C);
15773                 if ((I915_READ(VLV_HDMIC) & SDVO_DETECTED || has_port) && !has_edp)
15774                         intel_hdmi_init(dev_priv, VLV_HDMIC, PORT_C);
15775
15776                 if (IS_CHERRYVIEW(dev_priv)) {
15777                         /*
15778                          * eDP not supported on port D,
15779                          * so no need to worry about it
15780                          */
15781                         has_port = intel_bios_is_port_present(dev_priv, PORT_D);
15782                         if (I915_READ(CHV_DP_D) & DP_DETECTED || has_port)
15783                                 intel_dp_init(dev_priv, CHV_DP_D, PORT_D);
15784                         if (I915_READ(CHV_HDMID) & SDVO_DETECTED || has_port)
15785                                 intel_hdmi_init(dev_priv, CHV_HDMID, PORT_D);
15786                 }
15787
15788                 intel_dsi_init(dev_priv);
15789         } else if (!IS_GEN2(dev_priv) && !IS_PINEVIEW(dev_priv)) {
15790                 bool found = false;
15791
15792                 if (I915_READ(GEN3_SDVOB) & SDVO_DETECTED) {
15793                         DRM_DEBUG_KMS("probing SDVOB\n");
15794                         found = intel_sdvo_init(dev_priv, GEN3_SDVOB, PORT_B);
15795                         if (!found && IS_G4X(dev_priv)) {
15796                                 DRM_DEBUG_KMS("probing HDMI on SDVOB\n");
15797                                 intel_hdmi_init(dev_priv, GEN4_HDMIB, PORT_B);
15798                         }
15799
15800                         if (!found && IS_G4X(dev_priv))
15801                                 intel_dp_init(dev_priv, DP_B, PORT_B);
15802                 }
15803
15804                 /* Before G4X SDVOC doesn't have its own detect register */
15805
15806                 if (I915_READ(GEN3_SDVOB) & SDVO_DETECTED) {
15807                         DRM_DEBUG_KMS("probing SDVOC\n");
15808                         found = intel_sdvo_init(dev_priv, GEN3_SDVOC, PORT_C);
15809                 }
15810
15811                 if (!found && (I915_READ(GEN3_SDVOC) & SDVO_DETECTED)) {
15812
15813                         if (IS_G4X(dev_priv)) {
15814                                 DRM_DEBUG_KMS("probing HDMI on SDVOC\n");
15815                                 intel_hdmi_init(dev_priv, GEN4_HDMIC, PORT_C);
15816                         }
15817                         if (IS_G4X(dev_priv))
15818                                 intel_dp_init(dev_priv, DP_C, PORT_C);
15819                 }
15820
15821                 if (IS_G4X(dev_priv) && (I915_READ(DP_D) & DP_DETECTED))
15822                         intel_dp_init(dev_priv, DP_D, PORT_D);
15823         } else if (IS_GEN2(dev_priv))
15824                 intel_dvo_init(dev_priv);
15825
15826         if (SUPPORTS_TV(dev_priv))
15827                 intel_tv_init(dev_priv);
15828
15829         intel_psr_init(dev_priv);
15830
15831         for_each_intel_encoder(&dev_priv->drm, encoder) {
15832                 encoder->base.possible_crtcs = encoder->crtc_mask;
15833                 encoder->base.possible_clones =
15834                         intel_encoder_clones(encoder);
15835         }
15836
15837         intel_init_pch_refclk(dev_priv);
15838
15839         drm_helper_move_panel_connectors_to_head(&dev_priv->drm);
15840 }
15841
15842 static void intel_user_framebuffer_destroy(struct drm_framebuffer *fb)
15843 {
15844         struct drm_device *dev = fb->dev;
15845         struct intel_framebuffer *intel_fb = to_intel_framebuffer(fb);
15846
15847         drm_framebuffer_cleanup(fb);
15848         mutex_lock(&dev->struct_mutex);
15849         WARN_ON(!intel_fb->obj->framebuffer_references--);
15850         i915_gem_object_put(intel_fb->obj);
15851         mutex_unlock(&dev->struct_mutex);
15852         kfree(intel_fb);
15853 }
15854
15855 static int intel_user_framebuffer_create_handle(struct drm_framebuffer *fb,
15856                                                 struct drm_file *file,
15857                                                 unsigned int *handle)
15858 {
15859         struct intel_framebuffer *intel_fb = to_intel_framebuffer(fb);
15860         struct drm_i915_gem_object *obj = intel_fb->obj;
15861
15862         if (obj->userptr.mm) {
15863                 DRM_DEBUG("attempting to use a userptr for a framebuffer, denied\n");
15864                 return -EINVAL;
15865         }
15866
15867         return drm_gem_handle_create(file, &obj->base, handle);
15868 }
15869
15870 static int intel_user_framebuffer_dirty(struct drm_framebuffer *fb,
15871                                         struct drm_file *file,
15872                                         unsigned flags, unsigned color,
15873                                         struct drm_clip_rect *clips,
15874                                         unsigned num_clips)
15875 {
15876         struct drm_device *dev = fb->dev;
15877         struct intel_framebuffer *intel_fb = to_intel_framebuffer(fb);
15878         struct drm_i915_gem_object *obj = intel_fb->obj;
15879
15880         mutex_lock(&dev->struct_mutex);
15881         if (obj->pin_display && obj->cache_dirty)
15882                 i915_gem_clflush_object(obj, true);
15883         intel_fb_obj_flush(obj, false, ORIGIN_DIRTYFB);
15884         mutex_unlock(&dev->struct_mutex);
15885
15886         return 0;
15887 }
15888
15889 static const struct drm_framebuffer_funcs intel_fb_funcs = {
15890         .destroy = intel_user_framebuffer_destroy,
15891         .create_handle = intel_user_framebuffer_create_handle,
15892         .dirty = intel_user_framebuffer_dirty,
15893 };
15894
15895 static
15896 u32 intel_fb_pitch_limit(struct drm_i915_private *dev_priv,
15897                          uint64_t fb_modifier, uint32_t pixel_format)
15898 {
15899         u32 gen = INTEL_INFO(dev_priv)->gen;
15900
15901         if (gen >= 9) {
15902                 int cpp = drm_format_plane_cpp(pixel_format, 0);
15903
15904                 /* "The stride in bytes must not exceed the of the size of 8K
15905                  *  pixels and 32K bytes."
15906                  */
15907                 return min(8192 * cpp, 32768);
15908         } else if (gen >= 5 && !IS_VALLEYVIEW(dev_priv) &&
15909                    !IS_CHERRYVIEW(dev_priv)) {
15910                 return 32*1024;
15911         } else if (gen >= 4) {
15912                 if (fb_modifier == I915_FORMAT_MOD_X_TILED)
15913                         return 16*1024;
15914                 else
15915                         return 32*1024;
15916         } else if (gen >= 3) {
15917                 if (fb_modifier == I915_FORMAT_MOD_X_TILED)
15918                         return 8*1024;
15919                 else
15920                         return 16*1024;
15921         } else {
15922                 /* XXX DSPC is limited to 4k tiled */
15923                 return 8*1024;
15924         }
15925 }
15926
15927 static int intel_framebuffer_init(struct drm_device *dev,
15928                                   struct intel_framebuffer *intel_fb,
15929                                   struct drm_mode_fb_cmd2 *mode_cmd,
15930                                   struct drm_i915_gem_object *obj)
15931 {
15932         struct drm_i915_private *dev_priv = to_i915(dev);
15933         unsigned int tiling = i915_gem_object_get_tiling(obj);
15934         int ret;
15935         u32 pitch_limit, stride_alignment;
15936         struct drm_format_name_buf format_name;
15937
15938         WARN_ON(!mutex_is_locked(&dev->struct_mutex));
15939
15940         if (mode_cmd->flags & DRM_MODE_FB_MODIFIERS) {
15941                 /*
15942                  * If there's a fence, enforce that
15943                  * the fb modifier and tiling mode match.
15944                  */
15945                 if (tiling != I915_TILING_NONE &&
15946                     tiling != intel_fb_modifier_to_tiling(mode_cmd->modifier[0])) {
15947                         DRM_DEBUG("tiling_mode doesn't match fb modifier\n");
15948                         return -EINVAL;
15949                 }
15950         } else {
15951                 if (tiling == I915_TILING_X) {
15952                         mode_cmd->modifier[0] = I915_FORMAT_MOD_X_TILED;
15953                 } else if (tiling == I915_TILING_Y) {
15954                         DRM_DEBUG("No Y tiling for legacy addfb\n");
15955                         return -EINVAL;
15956                 }
15957         }
15958
15959         /* Passed in modifier sanity checking. */
15960         switch (mode_cmd->modifier[0]) {
15961         case I915_FORMAT_MOD_Y_TILED:
15962         case I915_FORMAT_MOD_Yf_TILED:
15963                 if (INTEL_GEN(dev_priv) < 9) {
15964                         DRM_DEBUG("Unsupported tiling 0x%llx!\n",
15965                                   mode_cmd->modifier[0]);
15966                         return -EINVAL;
15967                 }
15968         case DRM_FORMAT_MOD_NONE:
15969         case I915_FORMAT_MOD_X_TILED:
15970                 break;
15971         default:
15972                 DRM_DEBUG("Unsupported fb modifier 0x%llx!\n",
15973                           mode_cmd->modifier[0]);
15974                 return -EINVAL;
15975         }
15976
15977         /*
15978          * gen2/3 display engine uses the fence if present,
15979          * so the tiling mode must match the fb modifier exactly.
15980          */
15981         if (INTEL_INFO(dev_priv)->gen < 4 &&
15982             tiling != intel_fb_modifier_to_tiling(mode_cmd->modifier[0])) {
15983                 DRM_DEBUG("tiling_mode must match fb modifier exactly on gen2/3\n");
15984                 return -EINVAL;
15985         }
15986
15987         stride_alignment = intel_fb_stride_alignment(dev_priv,
15988                                                      mode_cmd->modifier[0],
15989                                                      mode_cmd->pixel_format);
15990         if (mode_cmd->pitches[0] & (stride_alignment - 1)) {
15991                 DRM_DEBUG("pitch (%d) must be at least %u byte aligned\n",
15992                           mode_cmd->pitches[0], stride_alignment);
15993                 return -EINVAL;
15994         }
15995
15996         pitch_limit = intel_fb_pitch_limit(dev_priv, mode_cmd->modifier[0],
15997                                            mode_cmd->pixel_format);
15998         if (mode_cmd->pitches[0] > pitch_limit) {
15999                 DRM_DEBUG("%s pitch (%u) must be at less than %d\n",
16000                           mode_cmd->modifier[0] != DRM_FORMAT_MOD_NONE ?
16001                           "tiled" : "linear",
16002                           mode_cmd->pitches[0], pitch_limit);
16003                 return -EINVAL;
16004         }
16005
16006         /*
16007          * If there's a fence, enforce that
16008          * the fb pitch and fence stride match.
16009          */
16010         if (tiling != I915_TILING_NONE &&
16011             mode_cmd->pitches[0] != i915_gem_object_get_stride(obj)) {
16012                 DRM_DEBUG("pitch (%d) must match tiling stride (%d)\n",
16013                           mode_cmd->pitches[0],
16014                           i915_gem_object_get_stride(obj));
16015                 return -EINVAL;
16016         }
16017
16018         /* Reject formats not supported by any plane early. */
16019         switch (mode_cmd->pixel_format) {
16020         case DRM_FORMAT_C8:
16021         case DRM_FORMAT_RGB565:
16022         case DRM_FORMAT_XRGB8888:
16023         case DRM_FORMAT_ARGB8888:
16024                 break;
16025         case DRM_FORMAT_XRGB1555:
16026                 if (INTEL_GEN(dev_priv) > 3) {
16027                         DRM_DEBUG("unsupported pixel format: %s\n",
16028                                   drm_get_format_name(mode_cmd->pixel_format, &format_name));
16029                         return -EINVAL;
16030                 }
16031                 break;
16032         case DRM_FORMAT_ABGR8888:
16033                 if (!IS_VALLEYVIEW(dev_priv) && !IS_CHERRYVIEW(dev_priv) &&
16034                     INTEL_GEN(dev_priv) < 9) {
16035                         DRM_DEBUG("unsupported pixel format: %s\n",
16036                                   drm_get_format_name(mode_cmd->pixel_format, &format_name));
16037                         return -EINVAL;
16038                 }
16039                 break;
16040         case DRM_FORMAT_XBGR8888:
16041         case DRM_FORMAT_XRGB2101010:
16042         case DRM_FORMAT_XBGR2101010:
16043                 if (INTEL_GEN(dev_priv) < 4) {
16044                         DRM_DEBUG("unsupported pixel format: %s\n",
16045                                   drm_get_format_name(mode_cmd->pixel_format, &format_name));
16046                         return -EINVAL;
16047                 }
16048                 break;
16049         case DRM_FORMAT_ABGR2101010:
16050                 if (!IS_VALLEYVIEW(dev_priv) && !IS_CHERRYVIEW(dev_priv)) {
16051                         DRM_DEBUG("unsupported pixel format: %s\n",
16052                                   drm_get_format_name(mode_cmd->pixel_format, &format_name));
16053                         return -EINVAL;
16054                 }
16055                 break;
16056         case DRM_FORMAT_YUYV:
16057         case DRM_FORMAT_UYVY:
16058         case DRM_FORMAT_YVYU:
16059         case DRM_FORMAT_VYUY:
16060                 if (INTEL_GEN(dev_priv) < 5) {
16061                         DRM_DEBUG("unsupported pixel format: %s\n",
16062                                   drm_get_format_name(mode_cmd->pixel_format, &format_name));
16063                         return -EINVAL;
16064                 }
16065                 break;
16066         default:
16067                 DRM_DEBUG("unsupported pixel format: %s\n",
16068                           drm_get_format_name(mode_cmd->pixel_format, &format_name));
16069                 return -EINVAL;
16070         }
16071
16072         /* FIXME need to adjust LINOFF/TILEOFF accordingly. */
16073         if (mode_cmd->offsets[0] != 0)
16074                 return -EINVAL;
16075
16076         drm_helper_mode_fill_fb_struct(dev, &intel_fb->base, mode_cmd);
16077         intel_fb->obj = obj;
16078
16079         ret = intel_fill_fb_info(dev_priv, &intel_fb->base);
16080         if (ret)
16081                 return ret;
16082
16083         ret = drm_framebuffer_init(dev, &intel_fb->base, &intel_fb_funcs);
16084         if (ret) {
16085                 DRM_ERROR("framebuffer init failed %d\n", ret);
16086                 return ret;
16087         }
16088
16089         intel_fb->obj->framebuffer_references++;
16090
16091         return 0;
16092 }
16093
16094 static struct drm_framebuffer *
16095 intel_user_framebuffer_create(struct drm_device *dev,
16096                               struct drm_file *filp,
16097                               const struct drm_mode_fb_cmd2 *user_mode_cmd)
16098 {
16099         struct drm_framebuffer *fb;
16100         struct drm_i915_gem_object *obj;
16101         struct drm_mode_fb_cmd2 mode_cmd = *user_mode_cmd;
16102
16103         obj = i915_gem_object_lookup(filp, mode_cmd.handles[0]);
16104         if (!obj)
16105                 return ERR_PTR(-ENOENT);
16106
16107         fb = intel_framebuffer_create(dev, &mode_cmd, obj);
16108         if (IS_ERR(fb))
16109                 i915_gem_object_put(obj);
16110
16111         return fb;
16112 }
16113
16114 static void intel_atomic_state_free(struct drm_atomic_state *state)
16115 {
16116         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
16117
16118         drm_atomic_state_default_release(state);
16119
16120         i915_sw_fence_fini(&intel_state->commit_ready);
16121
16122         kfree(state);
16123 }
16124
16125 static const struct drm_mode_config_funcs intel_mode_funcs = {
16126         .fb_create = intel_user_framebuffer_create,
16127         .output_poll_changed = intel_fbdev_output_poll_changed,
16128         .atomic_check = intel_atomic_check,
16129         .atomic_commit = intel_atomic_commit,
16130         .atomic_state_alloc = intel_atomic_state_alloc,
16131         .atomic_state_clear = intel_atomic_state_clear,
16132         .atomic_state_free = intel_atomic_state_free,
16133 };
16134
16135 /**
16136  * intel_init_display_hooks - initialize the display modesetting hooks
16137  * @dev_priv: device private
16138  */
16139 void intel_init_display_hooks(struct drm_i915_private *dev_priv)
16140 {
16141         if (INTEL_INFO(dev_priv)->gen >= 9) {
16142                 dev_priv->display.get_pipe_config = haswell_get_pipe_config;
16143                 dev_priv->display.get_initial_plane_config =
16144                         skylake_get_initial_plane_config;
16145                 dev_priv->display.crtc_compute_clock =
16146                         haswell_crtc_compute_clock;
16147                 dev_priv->display.crtc_enable = haswell_crtc_enable;
16148                 dev_priv->display.crtc_disable = haswell_crtc_disable;
16149         } else if (HAS_DDI(dev_priv)) {
16150                 dev_priv->display.get_pipe_config = haswell_get_pipe_config;
16151                 dev_priv->display.get_initial_plane_config =
16152                         ironlake_get_initial_plane_config;
16153                 dev_priv->display.crtc_compute_clock =
16154                         haswell_crtc_compute_clock;
16155                 dev_priv->display.crtc_enable = haswell_crtc_enable;
16156                 dev_priv->display.crtc_disable = haswell_crtc_disable;
16157         } else if (HAS_PCH_SPLIT(dev_priv)) {
16158                 dev_priv->display.get_pipe_config = ironlake_get_pipe_config;
16159                 dev_priv->display.get_initial_plane_config =
16160                         ironlake_get_initial_plane_config;
16161                 dev_priv->display.crtc_compute_clock =
16162                         ironlake_crtc_compute_clock;
16163                 dev_priv->display.crtc_enable = ironlake_crtc_enable;
16164                 dev_priv->display.crtc_disable = ironlake_crtc_disable;
16165         } else if (IS_CHERRYVIEW(dev_priv)) {
16166                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
16167                 dev_priv->display.get_initial_plane_config =
16168                         i9xx_get_initial_plane_config;
16169                 dev_priv->display.crtc_compute_clock = chv_crtc_compute_clock;
16170                 dev_priv->display.crtc_enable = valleyview_crtc_enable;
16171                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
16172         } else if (IS_VALLEYVIEW(dev_priv)) {
16173                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
16174                 dev_priv->display.get_initial_plane_config =
16175                         i9xx_get_initial_plane_config;
16176                 dev_priv->display.crtc_compute_clock = vlv_crtc_compute_clock;
16177                 dev_priv->display.crtc_enable = valleyview_crtc_enable;
16178                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
16179         } else if (IS_G4X(dev_priv)) {
16180                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
16181                 dev_priv->display.get_initial_plane_config =
16182                         i9xx_get_initial_plane_config;
16183                 dev_priv->display.crtc_compute_clock = g4x_crtc_compute_clock;
16184                 dev_priv->display.crtc_enable = i9xx_crtc_enable;
16185                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
16186         } else if (IS_PINEVIEW(dev_priv)) {
16187                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
16188                 dev_priv->display.get_initial_plane_config =
16189                         i9xx_get_initial_plane_config;
16190                 dev_priv->display.crtc_compute_clock = pnv_crtc_compute_clock;
16191                 dev_priv->display.crtc_enable = i9xx_crtc_enable;
16192                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
16193         } else if (!IS_GEN2(dev_priv)) {
16194                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
16195                 dev_priv->display.get_initial_plane_config =
16196                         i9xx_get_initial_plane_config;
16197                 dev_priv->display.crtc_compute_clock = i9xx_crtc_compute_clock;
16198                 dev_priv->display.crtc_enable = i9xx_crtc_enable;
16199                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
16200         } else {
16201                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
16202                 dev_priv->display.get_initial_plane_config =
16203                         i9xx_get_initial_plane_config;
16204                 dev_priv->display.crtc_compute_clock = i8xx_crtc_compute_clock;
16205                 dev_priv->display.crtc_enable = i9xx_crtc_enable;
16206                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
16207         }
16208
16209         /* Returns the core display clock speed */
16210         if (IS_SKYLAKE(dev_priv) || IS_KABYLAKE(dev_priv))
16211                 dev_priv->display.get_display_clock_speed =
16212                         skylake_get_display_clock_speed;
16213         else if (IS_GEN9_LP(dev_priv))
16214                 dev_priv->display.get_display_clock_speed =
16215                         broxton_get_display_clock_speed;
16216         else if (IS_BROADWELL(dev_priv))
16217                 dev_priv->display.get_display_clock_speed =
16218                         broadwell_get_display_clock_speed;
16219         else if (IS_HASWELL(dev_priv))
16220                 dev_priv->display.get_display_clock_speed =
16221                         haswell_get_display_clock_speed;
16222         else if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
16223                 dev_priv->display.get_display_clock_speed =
16224                         valleyview_get_display_clock_speed;
16225         else if (IS_GEN5(dev_priv))
16226                 dev_priv->display.get_display_clock_speed =
16227                         ilk_get_display_clock_speed;
16228         else if (IS_I945G(dev_priv) || IS_I965G(dev_priv) ||
16229                  IS_GEN6(dev_priv) || IS_IVYBRIDGE(dev_priv))
16230                 dev_priv->display.get_display_clock_speed =
16231                         i945_get_display_clock_speed;
16232         else if (IS_GM45(dev_priv))
16233                 dev_priv->display.get_display_clock_speed =
16234                         gm45_get_display_clock_speed;
16235         else if (IS_I965GM(dev_priv))
16236                 dev_priv->display.get_display_clock_speed =
16237                         i965gm_get_display_clock_speed;
16238         else if (IS_PINEVIEW(dev_priv))
16239                 dev_priv->display.get_display_clock_speed =
16240                         pnv_get_display_clock_speed;
16241         else if (IS_G33(dev_priv) || IS_G4X(dev_priv))
16242                 dev_priv->display.get_display_clock_speed =
16243                         g33_get_display_clock_speed;
16244         else if (IS_I915G(dev_priv))
16245                 dev_priv->display.get_display_clock_speed =
16246                         i915_get_display_clock_speed;
16247         else if (IS_I945GM(dev_priv) || IS_I845G(dev_priv))
16248                 dev_priv->display.get_display_clock_speed =
16249                         i9xx_misc_get_display_clock_speed;
16250         else if (IS_I915GM(dev_priv))
16251                 dev_priv->display.get_display_clock_speed =
16252                         i915gm_get_display_clock_speed;
16253         else if (IS_I865G(dev_priv))
16254                 dev_priv->display.get_display_clock_speed =
16255                         i865_get_display_clock_speed;
16256         else if (IS_I85X(dev_priv))
16257                 dev_priv->display.get_display_clock_speed =
16258                         i85x_get_display_clock_speed;
16259         else { /* 830 */
16260                 WARN(!IS_I830(dev_priv), "Unknown platform. Assuming 133 MHz CDCLK\n");
16261                 dev_priv->display.get_display_clock_speed =
16262                         i830_get_display_clock_speed;
16263         }
16264
16265         if (IS_GEN5(dev_priv)) {
16266                 dev_priv->display.fdi_link_train = ironlake_fdi_link_train;
16267         } else if (IS_GEN6(dev_priv)) {
16268                 dev_priv->display.fdi_link_train = gen6_fdi_link_train;
16269         } else if (IS_IVYBRIDGE(dev_priv)) {
16270                 /* FIXME: detect B0+ stepping and use auto training */
16271                 dev_priv->display.fdi_link_train = ivb_manual_fdi_link_train;
16272         } else if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv)) {
16273                 dev_priv->display.fdi_link_train = hsw_fdi_link_train;
16274         }
16275
16276         if (IS_BROADWELL(dev_priv)) {
16277                 dev_priv->display.modeset_commit_cdclk =
16278                         broadwell_modeset_commit_cdclk;
16279                 dev_priv->display.modeset_calc_cdclk =
16280                         broadwell_modeset_calc_cdclk;
16281         } else if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv)) {
16282                 dev_priv->display.modeset_commit_cdclk =
16283                         valleyview_modeset_commit_cdclk;
16284                 dev_priv->display.modeset_calc_cdclk =
16285                         valleyview_modeset_calc_cdclk;
16286         } else if (IS_GEN9_LP(dev_priv)) {
16287                 dev_priv->display.modeset_commit_cdclk =
16288                         bxt_modeset_commit_cdclk;
16289                 dev_priv->display.modeset_calc_cdclk =
16290                         bxt_modeset_calc_cdclk;
16291         } else if (IS_SKYLAKE(dev_priv) || IS_KABYLAKE(dev_priv)) {
16292                 dev_priv->display.modeset_commit_cdclk =
16293                         skl_modeset_commit_cdclk;
16294                 dev_priv->display.modeset_calc_cdclk =
16295                         skl_modeset_calc_cdclk;
16296         }
16297
16298         if (dev_priv->info.gen >= 9)
16299                 dev_priv->display.update_crtcs = skl_update_crtcs;
16300         else
16301                 dev_priv->display.update_crtcs = intel_update_crtcs;
16302
16303         switch (INTEL_INFO(dev_priv)->gen) {
16304         case 2:
16305                 dev_priv->display.queue_flip = intel_gen2_queue_flip;
16306                 break;
16307
16308         case 3:
16309                 dev_priv->display.queue_flip = intel_gen3_queue_flip;
16310                 break;
16311
16312         case 4:
16313         case 5:
16314                 dev_priv->display.queue_flip = intel_gen4_queue_flip;
16315                 break;
16316
16317         case 6:
16318                 dev_priv->display.queue_flip = intel_gen6_queue_flip;
16319                 break;
16320         case 7:
16321         case 8: /* FIXME(BDW): Check that the gen8 RCS flip works. */
16322                 dev_priv->display.queue_flip = intel_gen7_queue_flip;
16323                 break;
16324         case 9:
16325                 /* Drop through - unsupported since execlist only. */
16326         default:
16327                 /* Default just returns -ENODEV to indicate unsupported */
16328                 dev_priv->display.queue_flip = intel_default_queue_flip;
16329         }
16330 }
16331
16332 /*
16333  * Some BIOSes insist on assuming the GPU's pipe A is enabled at suspend,
16334  * resume, or other times.  This quirk makes sure that's the case for
16335  * affected systems.
16336  */
16337 static void quirk_pipea_force(struct drm_device *dev)
16338 {
16339         struct drm_i915_private *dev_priv = to_i915(dev);
16340
16341         dev_priv->quirks |= QUIRK_PIPEA_FORCE;
16342         DRM_INFO("applying pipe a force quirk\n");
16343 }
16344
16345 static void quirk_pipeb_force(struct drm_device *dev)
16346 {
16347         struct drm_i915_private *dev_priv = to_i915(dev);
16348
16349         dev_priv->quirks |= QUIRK_PIPEB_FORCE;
16350         DRM_INFO("applying pipe b force quirk\n");
16351 }
16352
16353 /*
16354  * Some machines (Lenovo U160) do not work with SSC on LVDS for some reason
16355  */
16356 static void quirk_ssc_force_disable(struct drm_device *dev)
16357 {
16358         struct drm_i915_private *dev_priv = to_i915(dev);
16359         dev_priv->quirks |= QUIRK_LVDS_SSC_DISABLE;
16360         DRM_INFO("applying lvds SSC disable quirk\n");
16361 }
16362
16363 /*
16364  * A machine (e.g. Acer Aspire 5734Z) may need to invert the panel backlight
16365  * brightness value
16366  */
16367 static void quirk_invert_brightness(struct drm_device *dev)
16368 {
16369         struct drm_i915_private *dev_priv = to_i915(dev);
16370         dev_priv->quirks |= QUIRK_INVERT_BRIGHTNESS;
16371         DRM_INFO("applying inverted panel brightness quirk\n");
16372 }
16373
16374 /* Some VBT's incorrectly indicate no backlight is present */
16375 static void quirk_backlight_present(struct drm_device *dev)
16376 {
16377         struct drm_i915_private *dev_priv = to_i915(dev);
16378         dev_priv->quirks |= QUIRK_BACKLIGHT_PRESENT;
16379         DRM_INFO("applying backlight present quirk\n");
16380 }
16381
16382 struct intel_quirk {
16383         int device;
16384         int subsystem_vendor;
16385         int subsystem_device;
16386         void (*hook)(struct drm_device *dev);
16387 };
16388
16389 /* For systems that don't have a meaningful PCI subdevice/subvendor ID */
16390 struct intel_dmi_quirk {
16391         void (*hook)(struct drm_device *dev);
16392         const struct dmi_system_id (*dmi_id_list)[];
16393 };
16394
16395 static int intel_dmi_reverse_brightness(const struct dmi_system_id *id)
16396 {
16397         DRM_INFO("Backlight polarity reversed on %s\n", id->ident);
16398         return 1;
16399 }
16400
16401 static const struct intel_dmi_quirk intel_dmi_quirks[] = {
16402         {
16403                 .dmi_id_list = &(const struct dmi_system_id[]) {
16404                         {
16405                                 .callback = intel_dmi_reverse_brightness,
16406                                 .ident = "NCR Corporation",
16407                                 .matches = {DMI_MATCH(DMI_SYS_VENDOR, "NCR Corporation"),
16408                                             DMI_MATCH(DMI_PRODUCT_NAME, ""),
16409                                 },
16410                         },
16411                         { }  /* terminating entry */
16412                 },
16413                 .hook = quirk_invert_brightness,
16414         },
16415 };
16416
16417 static struct intel_quirk intel_quirks[] = {
16418         /* Toshiba Protege R-205, S-209 needs pipe A force quirk */
16419         { 0x2592, 0x1179, 0x0001, quirk_pipea_force },
16420
16421         /* ThinkPad T60 needs pipe A force quirk (bug #16494) */
16422         { 0x2782, 0x17aa, 0x201a, quirk_pipea_force },
16423
16424         /* 830 needs to leave pipe A & dpll A up */
16425         { 0x3577, PCI_ANY_ID, PCI_ANY_ID, quirk_pipea_force },
16426
16427         /* 830 needs to leave pipe B & dpll B up */
16428         { 0x3577, PCI_ANY_ID, PCI_ANY_ID, quirk_pipeb_force },
16429
16430         /* Lenovo U160 cannot use SSC on LVDS */
16431         { 0x0046, 0x17aa, 0x3920, quirk_ssc_force_disable },
16432
16433         /* Sony Vaio Y cannot use SSC on LVDS */
16434         { 0x0046, 0x104d, 0x9076, quirk_ssc_force_disable },
16435
16436         /* Acer Aspire 5734Z must invert backlight brightness */
16437         { 0x2a42, 0x1025, 0x0459, quirk_invert_brightness },
16438
16439         /* Acer/eMachines G725 */
16440         { 0x2a42, 0x1025, 0x0210, quirk_invert_brightness },
16441
16442         /* Acer/eMachines e725 */
16443         { 0x2a42, 0x1025, 0x0212, quirk_invert_brightness },
16444
16445         /* Acer/Packard Bell NCL20 */
16446         { 0x2a42, 0x1025, 0x034b, quirk_invert_brightness },
16447
16448         /* Acer Aspire 4736Z */
16449         { 0x2a42, 0x1025, 0x0260, quirk_invert_brightness },
16450
16451         /* Acer Aspire 5336 */
16452         { 0x2a42, 0x1025, 0x048a, quirk_invert_brightness },
16453
16454         /* Acer C720 and C720P Chromebooks (Celeron 2955U) have backlights */
16455         { 0x0a06, 0x1025, 0x0a11, quirk_backlight_present },
16456
16457         /* Acer C720 Chromebook (Core i3 4005U) */
16458         { 0x0a16, 0x1025, 0x0a11, quirk_backlight_present },
16459
16460         /* Apple Macbook 2,1 (Core 2 T7400) */
16461         { 0x27a2, 0x8086, 0x7270, quirk_backlight_present },
16462
16463         /* Apple Macbook 4,1 */
16464         { 0x2a02, 0x106b, 0x00a1, quirk_backlight_present },
16465
16466         /* Toshiba CB35 Chromebook (Celeron 2955U) */
16467         { 0x0a06, 0x1179, 0x0a88, quirk_backlight_present },
16468
16469         /* HP Chromebook 14 (Celeron 2955U) */
16470         { 0x0a06, 0x103c, 0x21ed, quirk_backlight_present },
16471
16472         /* Dell Chromebook 11 */
16473         { 0x0a06, 0x1028, 0x0a35, quirk_backlight_present },
16474
16475         /* Dell Chromebook 11 (2015 version) */
16476         { 0x0a16, 0x1028, 0x0a35, quirk_backlight_present },
16477 };
16478
16479 static void intel_init_quirks(struct drm_device *dev)
16480 {
16481         struct pci_dev *d = dev->pdev;
16482         int i;
16483
16484         for (i = 0; i < ARRAY_SIZE(intel_quirks); i++) {
16485                 struct intel_quirk *q = &intel_quirks[i];
16486
16487                 if (d->device == q->device &&
16488                     (d->subsystem_vendor == q->subsystem_vendor ||
16489                      q->subsystem_vendor == PCI_ANY_ID) &&
16490                     (d->subsystem_device == q->subsystem_device ||
16491                      q->subsystem_device == PCI_ANY_ID))
16492                         q->hook(dev);
16493         }
16494         for (i = 0; i < ARRAY_SIZE(intel_dmi_quirks); i++) {
16495                 if (dmi_check_system(*intel_dmi_quirks[i].dmi_id_list) != 0)
16496                         intel_dmi_quirks[i].hook(dev);
16497         }
16498 }
16499
16500 /* Disable the VGA plane that we never use */
16501 static void i915_disable_vga(struct drm_i915_private *dev_priv)
16502 {
16503         struct pci_dev *pdev = dev_priv->drm.pdev;
16504         u8 sr1;
16505         i915_reg_t vga_reg = i915_vgacntrl_reg(dev_priv);
16506
16507         /* WaEnableVGAAccessThroughIOPort:ctg,elk,ilk,snb,ivb,vlv,hsw */
16508         vga_get_uninterruptible(pdev, VGA_RSRC_LEGACY_IO);
16509         outb(SR01, VGA_SR_INDEX);
16510         sr1 = inb(VGA_SR_DATA);
16511         outb(sr1 | 1<<5, VGA_SR_DATA);
16512         vga_put(pdev, VGA_RSRC_LEGACY_IO);
16513         udelay(300);
16514
16515         I915_WRITE(vga_reg, VGA_DISP_DISABLE);
16516         POSTING_READ(vga_reg);
16517 }
16518
16519 void intel_modeset_init_hw(struct drm_device *dev)
16520 {
16521         struct drm_i915_private *dev_priv = to_i915(dev);
16522
16523         intel_update_cdclk(dev_priv);
16524
16525         dev_priv->atomic_cdclk_freq = dev_priv->cdclk_freq;
16526
16527         intel_init_clock_gating(dev_priv);
16528 }
16529
16530 /*
16531  * Calculate what we think the watermarks should be for the state we've read
16532  * out of the hardware and then immediately program those watermarks so that
16533  * we ensure the hardware settings match our internal state.
16534  *
16535  * We can calculate what we think WM's should be by creating a duplicate of the
16536  * current state (which was constructed during hardware readout) and running it
16537  * through the atomic check code to calculate new watermark values in the
16538  * state object.
16539  */
16540 static void sanitize_watermarks(struct drm_device *dev)
16541 {
16542         struct drm_i915_private *dev_priv = to_i915(dev);
16543         struct drm_atomic_state *state;
16544         struct intel_atomic_state *intel_state;
16545         struct drm_crtc *crtc;
16546         struct drm_crtc_state *cstate;
16547         struct drm_modeset_acquire_ctx ctx;
16548         int ret;
16549         int i;
16550
16551         /* Only supported on platforms that use atomic watermark design */
16552         if (!dev_priv->display.optimize_watermarks)
16553                 return;
16554
16555         /*
16556          * We need to hold connection_mutex before calling duplicate_state so
16557          * that the connector loop is protected.
16558          */
16559         drm_modeset_acquire_init(&ctx, 0);
16560 retry:
16561         ret = drm_modeset_lock_all_ctx(dev, &ctx);
16562         if (ret == -EDEADLK) {
16563                 drm_modeset_backoff(&ctx);
16564                 goto retry;
16565         } else if (WARN_ON(ret)) {
16566                 goto fail;
16567         }
16568
16569         state = drm_atomic_helper_duplicate_state(dev, &ctx);
16570         if (WARN_ON(IS_ERR(state)))
16571                 goto fail;
16572
16573         intel_state = to_intel_atomic_state(state);
16574
16575         /*
16576          * Hardware readout is the only time we don't want to calculate
16577          * intermediate watermarks (since we don't trust the current
16578          * watermarks).
16579          */
16580         intel_state->skip_intermediate_wm = true;
16581
16582         ret = intel_atomic_check(dev, state);
16583         if (ret) {
16584                 /*
16585                  * If we fail here, it means that the hardware appears to be
16586                  * programmed in a way that shouldn't be possible, given our
16587                  * understanding of watermark requirements.  This might mean a
16588                  * mistake in the hardware readout code or a mistake in the
16589                  * watermark calculations for a given platform.  Raise a WARN
16590                  * so that this is noticeable.
16591                  *
16592                  * If this actually happens, we'll have to just leave the
16593                  * BIOS-programmed watermarks untouched and hope for the best.
16594                  */
16595                 WARN(true, "Could not determine valid watermarks for inherited state\n");
16596                 goto put_state;
16597         }
16598
16599         /* Write calculated watermark values back */
16600         for_each_crtc_in_state(state, crtc, cstate, i) {
16601                 struct intel_crtc_state *cs = to_intel_crtc_state(cstate);
16602
16603                 cs->wm.need_postvbl_update = true;
16604                 dev_priv->display.optimize_watermarks(intel_state, cs);
16605         }
16606
16607 put_state:
16608         drm_atomic_state_put(state);
16609 fail:
16610         drm_modeset_drop_locks(&ctx);
16611         drm_modeset_acquire_fini(&ctx);
16612 }
16613
16614 int intel_modeset_init(struct drm_device *dev)
16615 {
16616         struct drm_i915_private *dev_priv = to_i915(dev);
16617         struct i915_ggtt *ggtt = &dev_priv->ggtt;
16618         enum pipe pipe;
16619         struct intel_crtc *crtc;
16620
16621         drm_mode_config_init(dev);
16622
16623         dev->mode_config.min_width = 0;
16624         dev->mode_config.min_height = 0;
16625
16626         dev->mode_config.preferred_depth = 24;
16627         dev->mode_config.prefer_shadow = 1;
16628
16629         dev->mode_config.allow_fb_modifiers = true;
16630
16631         dev->mode_config.funcs = &intel_mode_funcs;
16632
16633         INIT_WORK(&dev_priv->atomic_helper.free_work,
16634                   intel_atomic_helper_free_state_worker);
16635
16636         intel_init_quirks(dev);
16637
16638         intel_init_pm(dev_priv);
16639
16640         if (INTEL_INFO(dev_priv)->num_pipes == 0)
16641                 return 0;
16642
16643         /*
16644          * There may be no VBT; and if the BIOS enabled SSC we can
16645          * just keep using it to avoid unnecessary flicker.  Whereas if the
16646          * BIOS isn't using it, don't assume it will work even if the VBT
16647          * indicates as much.
16648          */
16649         if (HAS_PCH_IBX(dev_priv) || HAS_PCH_CPT(dev_priv)) {
16650                 bool bios_lvds_use_ssc = !!(I915_READ(PCH_DREF_CONTROL) &
16651                                             DREF_SSC1_ENABLE);
16652
16653                 if (dev_priv->vbt.lvds_use_ssc != bios_lvds_use_ssc) {
16654                         DRM_DEBUG_KMS("SSC %sabled by BIOS, overriding VBT which says %sabled\n",
16655                                      bios_lvds_use_ssc ? "en" : "dis",
16656                                      dev_priv->vbt.lvds_use_ssc ? "en" : "dis");
16657                         dev_priv->vbt.lvds_use_ssc = bios_lvds_use_ssc;
16658                 }
16659         }
16660
16661         if (IS_GEN2(dev_priv)) {
16662                 dev->mode_config.max_width = 2048;
16663                 dev->mode_config.max_height = 2048;
16664         } else if (IS_GEN3(dev_priv)) {
16665                 dev->mode_config.max_width = 4096;
16666                 dev->mode_config.max_height = 4096;
16667         } else {
16668                 dev->mode_config.max_width = 8192;
16669                 dev->mode_config.max_height = 8192;
16670         }
16671
16672         if (IS_I845G(dev_priv) || IS_I865G(dev_priv)) {
16673                 dev->mode_config.cursor_width = IS_I845G(dev_priv) ? 64 : 512;
16674                 dev->mode_config.cursor_height = 1023;
16675         } else if (IS_GEN2(dev_priv)) {
16676                 dev->mode_config.cursor_width = GEN2_CURSOR_WIDTH;
16677                 dev->mode_config.cursor_height = GEN2_CURSOR_HEIGHT;
16678         } else {
16679                 dev->mode_config.cursor_width = MAX_CURSOR_WIDTH;
16680                 dev->mode_config.cursor_height = MAX_CURSOR_HEIGHT;
16681         }
16682
16683         dev->mode_config.fb_base = ggtt->mappable_base;
16684
16685         DRM_DEBUG_KMS("%d display pipe%s available.\n",
16686                       INTEL_INFO(dev_priv)->num_pipes,
16687                       INTEL_INFO(dev_priv)->num_pipes > 1 ? "s" : "");
16688
16689         for_each_pipe(dev_priv, pipe) {
16690                 int ret;
16691
16692                 ret = intel_crtc_init(dev_priv, pipe);
16693                 if (ret) {
16694                         drm_mode_config_cleanup(dev);
16695                         return ret;
16696                 }
16697         }
16698
16699         intel_shared_dpll_init(dev);
16700
16701         intel_update_czclk(dev_priv);
16702         intel_modeset_init_hw(dev);
16703
16704         if (dev_priv->max_cdclk_freq == 0)
16705                 intel_update_max_cdclk(dev_priv);
16706
16707         /* Just disable it once at startup */
16708         i915_disable_vga(dev_priv);
16709         intel_setup_outputs(dev_priv);
16710
16711         drm_modeset_lock_all(dev);
16712         intel_modeset_setup_hw_state(dev);
16713         drm_modeset_unlock_all(dev);
16714
16715         for_each_intel_crtc(dev, crtc) {
16716                 struct intel_initial_plane_config plane_config = {};
16717
16718                 if (!crtc->active)
16719                         continue;
16720
16721                 /*
16722                  * Note that reserving the BIOS fb up front prevents us
16723                  * from stuffing other stolen allocations like the ring
16724                  * on top.  This prevents some ugliness at boot time, and
16725                  * can even allow for smooth boot transitions if the BIOS
16726                  * fb is large enough for the active pipe configuration.
16727                  */
16728                 dev_priv->display.get_initial_plane_config(crtc,
16729                                                            &plane_config);
16730
16731                 /*
16732                  * If the fb is shared between multiple heads, we'll
16733                  * just get the first one.
16734                  */
16735                 intel_find_initial_plane_obj(crtc, &plane_config);
16736         }
16737
16738         /*
16739          * Make sure hardware watermarks really match the state we read out.
16740          * Note that we need to do this after reconstructing the BIOS fb's
16741          * since the watermark calculation done here will use pstate->fb.
16742          */
16743         sanitize_watermarks(dev);
16744
16745         return 0;
16746 }
16747
16748 static void intel_enable_pipe_a(struct drm_device *dev)
16749 {
16750         struct intel_connector *connector;
16751         struct drm_connector *crt = NULL;
16752         struct intel_load_detect_pipe load_detect_temp;
16753         struct drm_modeset_acquire_ctx *ctx = dev->mode_config.acquire_ctx;
16754
16755         /* We can't just switch on the pipe A, we need to set things up with a
16756          * proper mode and output configuration. As a gross hack, enable pipe A
16757          * by enabling the load detect pipe once. */
16758         for_each_intel_connector(dev, connector) {
16759                 if (connector->encoder->type == INTEL_OUTPUT_ANALOG) {
16760                         crt = &connector->base;
16761                         break;
16762                 }
16763         }
16764
16765         if (!crt)
16766                 return;
16767
16768         if (intel_get_load_detect_pipe(crt, NULL, &load_detect_temp, ctx))
16769                 intel_release_load_detect_pipe(crt, &load_detect_temp, ctx);
16770 }
16771
16772 static bool
16773 intel_check_plane_mapping(struct intel_crtc *crtc)
16774 {
16775         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
16776         u32 val;
16777
16778         if (INTEL_INFO(dev_priv)->num_pipes == 1)
16779                 return true;
16780
16781         val = I915_READ(DSPCNTR(!crtc->plane));
16782
16783         if ((val & DISPLAY_PLANE_ENABLE) &&
16784             (!!(val & DISPPLANE_SEL_PIPE_MASK) == crtc->pipe))
16785                 return false;
16786
16787         return true;
16788 }
16789
16790 static bool intel_crtc_has_encoders(struct intel_crtc *crtc)
16791 {
16792         struct drm_device *dev = crtc->base.dev;
16793         struct intel_encoder *encoder;
16794
16795         for_each_encoder_on_crtc(dev, &crtc->base, encoder)
16796                 return true;
16797
16798         return false;
16799 }
16800
16801 static struct intel_connector *intel_encoder_find_connector(struct intel_encoder *encoder)
16802 {
16803         struct drm_device *dev = encoder->base.dev;
16804         struct intel_connector *connector;
16805
16806         for_each_connector_on_encoder(dev, &encoder->base, connector)
16807                 return connector;
16808
16809         return NULL;
16810 }
16811
16812 static bool has_pch_trancoder(struct drm_i915_private *dev_priv,
16813                               enum transcoder pch_transcoder)
16814 {
16815         return HAS_PCH_IBX(dev_priv) || HAS_PCH_CPT(dev_priv) ||
16816                 (HAS_PCH_LPT_H(dev_priv) && pch_transcoder == TRANSCODER_A);
16817 }
16818
16819 static void intel_sanitize_crtc(struct intel_crtc *crtc)
16820 {
16821         struct drm_device *dev = crtc->base.dev;
16822         struct drm_i915_private *dev_priv = to_i915(dev);
16823         enum transcoder cpu_transcoder = crtc->config->cpu_transcoder;
16824
16825         /* Clear any frame start delays used for debugging left by the BIOS */
16826         if (!transcoder_is_dsi(cpu_transcoder)) {
16827                 i915_reg_t reg = PIPECONF(cpu_transcoder);
16828
16829                 I915_WRITE(reg,
16830                            I915_READ(reg) & ~PIPECONF_FRAME_START_DELAY_MASK);
16831         }
16832
16833         /* restore vblank interrupts to correct state */
16834         drm_crtc_vblank_reset(&crtc->base);
16835         if (crtc->active) {
16836                 struct intel_plane *plane;
16837
16838                 drm_crtc_vblank_on(&crtc->base);
16839
16840                 /* Disable everything but the primary plane */
16841                 for_each_intel_plane_on_crtc(dev, crtc, plane) {
16842                         if (plane->base.type == DRM_PLANE_TYPE_PRIMARY)
16843                                 continue;
16844
16845                         plane->disable_plane(&plane->base, &crtc->base);
16846                 }
16847         }
16848
16849         /* We need to sanitize the plane -> pipe mapping first because this will
16850          * disable the crtc (and hence change the state) if it is wrong. Note
16851          * that gen4+ has a fixed plane -> pipe mapping.  */
16852         if (INTEL_GEN(dev_priv) < 4 && !intel_check_plane_mapping(crtc)) {
16853                 bool plane;
16854
16855                 DRM_DEBUG_KMS("[CRTC:%d:%s] wrong plane connection detected!\n",
16856                               crtc->base.base.id, crtc->base.name);
16857
16858                 /* Pipe has the wrong plane attached and the plane is active.
16859                  * Temporarily change the plane mapping and disable everything
16860                  * ...  */
16861                 plane = crtc->plane;
16862                 crtc->base.primary->state->visible = true;
16863                 crtc->plane = !plane;
16864                 intel_crtc_disable_noatomic(&crtc->base);
16865                 crtc->plane = plane;
16866         }
16867
16868         if (dev_priv->quirks & QUIRK_PIPEA_FORCE &&
16869             crtc->pipe == PIPE_A && !crtc->active) {
16870                 /* BIOS forgot to enable pipe A, this mostly happens after
16871                  * resume. Force-enable the pipe to fix this, the update_dpms
16872                  * call below we restore the pipe to the right state, but leave
16873                  * the required bits on. */
16874                 intel_enable_pipe_a(dev);
16875         }
16876
16877         /* Adjust the state of the output pipe according to whether we
16878          * have active connectors/encoders. */
16879         if (crtc->active && !intel_crtc_has_encoders(crtc))
16880                 intel_crtc_disable_noatomic(&crtc->base);
16881
16882         if (crtc->active || HAS_GMCH_DISPLAY(dev_priv)) {
16883                 /*
16884                  * We start out with underrun reporting disabled to avoid races.
16885                  * For correct bookkeeping mark this on active crtcs.
16886                  *
16887                  * Also on gmch platforms we dont have any hardware bits to
16888                  * disable the underrun reporting. Which means we need to start
16889                  * out with underrun reporting disabled also on inactive pipes,
16890                  * since otherwise we'll complain about the garbage we read when
16891                  * e.g. coming up after runtime pm.
16892                  *
16893                  * No protection against concurrent access is required - at
16894                  * worst a fifo underrun happens which also sets this to false.
16895                  */
16896                 crtc->cpu_fifo_underrun_disabled = true;
16897                 /*
16898                  * We track the PCH trancoder underrun reporting state
16899                  * within the crtc. With crtc for pipe A housing the underrun
16900                  * reporting state for PCH transcoder A, crtc for pipe B housing
16901                  * it for PCH transcoder B, etc. LPT-H has only PCH transcoder A,
16902                  * and marking underrun reporting as disabled for the non-existing
16903                  * PCH transcoders B and C would prevent enabling the south
16904                  * error interrupt (see cpt_can_enable_serr_int()).
16905                  */
16906                 if (has_pch_trancoder(dev_priv, (enum transcoder)crtc->pipe))
16907                         crtc->pch_fifo_underrun_disabled = true;
16908         }
16909 }
16910
16911 static void intel_sanitize_encoder(struct intel_encoder *encoder)
16912 {
16913         struct intel_connector *connector;
16914
16915         /* We need to check both for a crtc link (meaning that the
16916          * encoder is active and trying to read from a pipe) and the
16917          * pipe itself being active. */
16918         bool has_active_crtc = encoder->base.crtc &&
16919                 to_intel_crtc(encoder->base.crtc)->active;
16920
16921         connector = intel_encoder_find_connector(encoder);
16922         if (connector && !has_active_crtc) {
16923                 DRM_DEBUG_KMS("[ENCODER:%d:%s] has active connectors but no active pipe!\n",
16924                               encoder->base.base.id,
16925                               encoder->base.name);
16926
16927                 /* Connector is active, but has no active pipe. This is
16928                  * fallout from our resume register restoring. Disable
16929                  * the encoder manually again. */
16930                 if (encoder->base.crtc) {
16931                         struct drm_crtc_state *crtc_state = encoder->base.crtc->state;
16932
16933                         DRM_DEBUG_KMS("[ENCODER:%d:%s] manually disabled\n",
16934                                       encoder->base.base.id,
16935                                       encoder->base.name);
16936                         encoder->disable(encoder, to_intel_crtc_state(crtc_state), connector->base.state);
16937                         if (encoder->post_disable)
16938                                 encoder->post_disable(encoder, to_intel_crtc_state(crtc_state), connector->base.state);
16939                 }
16940                 encoder->base.crtc = NULL;
16941
16942                 /* Inconsistent output/port/pipe state happens presumably due to
16943                  * a bug in one of the get_hw_state functions. Or someplace else
16944                  * in our code, like the register restore mess on resume. Clamp
16945                  * things to off as a safer default. */
16946
16947                 connector->base.dpms = DRM_MODE_DPMS_OFF;
16948                 connector->base.encoder = NULL;
16949         }
16950         /* Enabled encoders without active connectors will be fixed in
16951          * the crtc fixup. */
16952 }
16953
16954 void i915_redisable_vga_power_on(struct drm_i915_private *dev_priv)
16955 {
16956         i915_reg_t vga_reg = i915_vgacntrl_reg(dev_priv);
16957
16958         if (!(I915_READ(vga_reg) & VGA_DISP_DISABLE)) {
16959                 DRM_DEBUG_KMS("Something enabled VGA plane, disabling it\n");
16960                 i915_disable_vga(dev_priv);
16961         }
16962 }
16963
16964 void i915_redisable_vga(struct drm_i915_private *dev_priv)
16965 {
16966         /* This function can be called both from intel_modeset_setup_hw_state or
16967          * at a very early point in our resume sequence, where the power well
16968          * structures are not yet restored. Since this function is at a very
16969          * paranoid "someone might have enabled VGA while we were not looking"
16970          * level, just check if the power well is enabled instead of trying to
16971          * follow the "don't touch the power well if we don't need it" policy
16972          * the rest of the driver uses. */
16973         if (!intel_display_power_get_if_enabled(dev_priv, POWER_DOMAIN_VGA))
16974                 return;
16975
16976         i915_redisable_vga_power_on(dev_priv);
16977
16978         intel_display_power_put(dev_priv, POWER_DOMAIN_VGA);
16979 }
16980
16981 static bool primary_get_hw_state(struct intel_plane *plane)
16982 {
16983         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
16984
16985         return I915_READ(DSPCNTR(plane->plane)) & DISPLAY_PLANE_ENABLE;
16986 }
16987
16988 /* FIXME read out full plane state for all planes */
16989 static void readout_plane_state(struct intel_crtc *crtc)
16990 {
16991         struct drm_plane *primary = crtc->base.primary;
16992         struct intel_plane_state *plane_state =
16993                 to_intel_plane_state(primary->state);
16994
16995         plane_state->base.visible = crtc->active &&
16996                 primary_get_hw_state(to_intel_plane(primary));
16997
16998         if (plane_state->base.visible)
16999                 crtc->base.state->plane_mask |= 1 << drm_plane_index(primary);
17000 }
17001
17002 static void intel_modeset_readout_hw_state(struct drm_device *dev)
17003 {
17004         struct drm_i915_private *dev_priv = to_i915(dev);
17005         enum pipe pipe;
17006         struct intel_crtc *crtc;
17007         struct intel_encoder *encoder;
17008         struct intel_connector *connector;
17009         int i;
17010
17011         dev_priv->active_crtcs = 0;
17012
17013         for_each_intel_crtc(dev, crtc) {
17014                 struct intel_crtc_state *crtc_state =
17015                         to_intel_crtc_state(crtc->base.state);
17016
17017                 __drm_atomic_helper_crtc_destroy_state(&crtc_state->base);
17018                 memset(crtc_state, 0, sizeof(*crtc_state));
17019                 crtc_state->base.crtc = &crtc->base;
17020
17021                 crtc_state->base.active = crtc_state->base.enable =
17022                         dev_priv->display.get_pipe_config(crtc, crtc_state);
17023
17024                 crtc->base.enabled = crtc_state->base.enable;
17025                 crtc->active = crtc_state->base.active;
17026
17027                 if (crtc_state->base.active)
17028                         dev_priv->active_crtcs |= 1 << crtc->pipe;
17029
17030                 readout_plane_state(crtc);
17031
17032                 DRM_DEBUG_KMS("[CRTC:%d:%s] hw state readout: %s\n",
17033                               crtc->base.base.id, crtc->base.name,
17034                               enableddisabled(crtc_state->base.active));
17035         }
17036
17037         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
17038                 struct intel_shared_dpll *pll = &dev_priv->shared_dplls[i];
17039
17040                 pll->on = pll->funcs.get_hw_state(dev_priv, pll,
17041                                                   &pll->state.hw_state);
17042                 pll->state.crtc_mask = 0;
17043                 for_each_intel_crtc(dev, crtc) {
17044                         struct intel_crtc_state *crtc_state =
17045                                 to_intel_crtc_state(crtc->base.state);
17046
17047                         if (crtc_state->base.active &&
17048                             crtc_state->shared_dpll == pll)
17049                                 pll->state.crtc_mask |= 1 << crtc->pipe;
17050                 }
17051                 pll->active_mask = pll->state.crtc_mask;
17052
17053                 DRM_DEBUG_KMS("%s hw state readout: crtc_mask 0x%08x, on %i\n",
17054                               pll->name, pll->state.crtc_mask, pll->on);
17055         }
17056
17057         for_each_intel_encoder(dev, encoder) {
17058                 pipe = 0;
17059
17060                 if (encoder->get_hw_state(encoder, &pipe)) {
17061                         struct intel_crtc_state *crtc_state;
17062
17063                         crtc = intel_get_crtc_for_pipe(dev_priv, pipe);
17064                         crtc_state = to_intel_crtc_state(crtc->base.state);
17065
17066                         encoder->base.crtc = &crtc->base;
17067                         crtc_state->output_types |= 1 << encoder->type;
17068                         encoder->get_config(encoder, crtc_state);
17069                 } else {
17070                         encoder->base.crtc = NULL;
17071                 }
17072
17073                 DRM_DEBUG_KMS("[ENCODER:%d:%s] hw state readout: %s, pipe %c\n",
17074                               encoder->base.base.id, encoder->base.name,
17075                               enableddisabled(encoder->base.crtc),
17076                               pipe_name(pipe));
17077         }
17078
17079         for_each_intel_connector(dev, connector) {
17080                 if (connector->get_hw_state(connector)) {
17081                         connector->base.dpms = DRM_MODE_DPMS_ON;
17082
17083                         encoder = connector->encoder;
17084                         connector->base.encoder = &encoder->base;
17085
17086                         if (encoder->base.crtc &&
17087                             encoder->base.crtc->state->active) {
17088                                 /*
17089                                  * This has to be done during hardware readout
17090                                  * because anything calling .crtc_disable may
17091                                  * rely on the connector_mask being accurate.
17092                                  */
17093                                 encoder->base.crtc->state->connector_mask |=
17094                                         1 << drm_connector_index(&connector->base);
17095                                 encoder->base.crtc->state->encoder_mask |=
17096                                         1 << drm_encoder_index(&encoder->base);
17097                         }
17098
17099                 } else {
17100                         connector->base.dpms = DRM_MODE_DPMS_OFF;
17101                         connector->base.encoder = NULL;
17102                 }
17103                 DRM_DEBUG_KMS("[CONNECTOR:%d:%s] hw state readout: %s\n",
17104                               connector->base.base.id, connector->base.name,
17105                               enableddisabled(connector->base.encoder));
17106         }
17107
17108         for_each_intel_crtc(dev, crtc) {
17109                 struct intel_crtc_state *crtc_state =
17110                         to_intel_crtc_state(crtc->base.state);
17111                 int pixclk = 0;
17112
17113                 crtc->base.hwmode = crtc_state->base.adjusted_mode;
17114
17115                 memset(&crtc->base.mode, 0, sizeof(crtc->base.mode));
17116                 if (crtc_state->base.active) {
17117                         intel_mode_from_pipe_config(&crtc->base.mode, crtc_state);
17118                         intel_mode_from_pipe_config(&crtc_state->base.adjusted_mode, crtc_state);
17119                         WARN_ON(drm_atomic_set_mode_for_crtc(crtc->base.state, &crtc->base.mode));
17120
17121                         /*
17122                          * The initial mode needs to be set in order to keep
17123                          * the atomic core happy. It wants a valid mode if the
17124                          * crtc's enabled, so we do the above call.
17125                          *
17126                          * But we don't set all the derived state fully, hence
17127                          * set a flag to indicate that a full recalculation is
17128                          * needed on the next commit.
17129                          */
17130                         crtc_state->base.mode.private_flags = I915_MODE_FLAG_INHERITED;
17131
17132                         if (INTEL_GEN(dev_priv) >= 9 || IS_BROADWELL(dev_priv))
17133                                 pixclk = ilk_pipe_pixel_rate(crtc_state);
17134                         else if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
17135                                 pixclk = crtc_state->base.adjusted_mode.crtc_clock;
17136                         else
17137                                 WARN_ON(dev_priv->display.modeset_calc_cdclk);
17138
17139                         /* pixel rate mustn't exceed 95% of cdclk with IPS on BDW */
17140                         if (IS_BROADWELL(dev_priv) && crtc_state->ips_enabled)
17141                                 pixclk = DIV_ROUND_UP(pixclk * 100, 95);
17142
17143                         drm_calc_timestamping_constants(&crtc->base, &crtc->base.hwmode);
17144                         update_scanline_offset(crtc);
17145                 }
17146
17147                 dev_priv->min_pixclk[crtc->pipe] = pixclk;
17148
17149                 intel_pipe_config_sanity_check(dev_priv, crtc_state);
17150         }
17151 }
17152
17153 /* Scan out the current hw modeset state,
17154  * and sanitizes it to the current state
17155  */
17156 static void
17157 intel_modeset_setup_hw_state(struct drm_device *dev)
17158 {
17159         struct drm_i915_private *dev_priv = to_i915(dev);
17160         enum pipe pipe;
17161         struct intel_crtc *crtc;
17162         struct intel_encoder *encoder;
17163         int i;
17164
17165         intel_modeset_readout_hw_state(dev);
17166
17167         /* HW state is read out, now we need to sanitize this mess. */
17168         for_each_intel_encoder(dev, encoder) {
17169                 intel_sanitize_encoder(encoder);
17170         }
17171
17172         for_each_pipe(dev_priv, pipe) {
17173                 crtc = intel_get_crtc_for_pipe(dev_priv, pipe);
17174
17175                 intel_sanitize_crtc(crtc);
17176                 intel_dump_pipe_config(crtc, crtc->config,
17177                                        "[setup_hw_state]");
17178         }
17179
17180         intel_modeset_update_connector_atomic_state(dev);
17181
17182         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
17183                 struct intel_shared_dpll *pll = &dev_priv->shared_dplls[i];
17184
17185                 if (!pll->on || pll->active_mask)
17186                         continue;
17187
17188                 DRM_DEBUG_KMS("%s enabled but not in use, disabling\n", pll->name);
17189
17190                 pll->funcs.disable(dev_priv, pll);
17191                 pll->on = false;
17192         }
17193
17194         if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
17195                 vlv_wm_get_hw_state(dev);
17196         else if (IS_GEN9(dev_priv))
17197                 skl_wm_get_hw_state(dev);
17198         else if (HAS_PCH_SPLIT(dev_priv))
17199                 ilk_wm_get_hw_state(dev);
17200
17201         for_each_intel_crtc(dev, crtc) {
17202                 unsigned long put_domains;
17203
17204                 put_domains = modeset_get_crtc_power_domains(&crtc->base, crtc->config);
17205                 if (WARN_ON(put_domains))
17206                         modeset_put_power_domains(dev_priv, put_domains);
17207         }
17208         intel_display_set_init_power(dev_priv, false);
17209
17210         intel_fbc_init_pipe_state(dev_priv);
17211 }
17212
17213 void intel_display_resume(struct drm_device *dev)
17214 {
17215         struct drm_i915_private *dev_priv = to_i915(dev);
17216         struct drm_atomic_state *state = dev_priv->modeset_restore_state;
17217         struct drm_modeset_acquire_ctx ctx;
17218         int ret;
17219
17220         dev_priv->modeset_restore_state = NULL;
17221         if (state)
17222                 state->acquire_ctx = &ctx;
17223
17224         /*
17225          * This is a cludge because with real atomic modeset mode_config.mutex
17226          * won't be taken. Unfortunately some probed state like
17227          * audio_codec_enable is still protected by mode_config.mutex, so lock
17228          * it here for now.
17229          */
17230         mutex_lock(&dev->mode_config.mutex);
17231         drm_modeset_acquire_init(&ctx, 0);
17232
17233         while (1) {
17234                 ret = drm_modeset_lock_all_ctx(dev, &ctx);
17235                 if (ret != -EDEADLK)
17236                         break;
17237
17238                 drm_modeset_backoff(&ctx);
17239         }
17240
17241         if (!ret)
17242                 ret = __intel_display_resume(dev, state);
17243
17244         drm_modeset_drop_locks(&ctx);
17245         drm_modeset_acquire_fini(&ctx);
17246         mutex_unlock(&dev->mode_config.mutex);
17247
17248         if (ret)
17249                 DRM_ERROR("Restoring old state failed with %i\n", ret);
17250         if (state)
17251                 drm_atomic_state_put(state);
17252 }
17253
17254 void intel_modeset_gem_init(struct drm_device *dev)
17255 {
17256         struct drm_i915_private *dev_priv = to_i915(dev);
17257
17258         intel_init_gt_powersave(dev_priv);
17259
17260         intel_setup_overlay(dev_priv);
17261 }
17262
17263 int intel_connector_register(struct drm_connector *connector)
17264 {
17265         struct intel_connector *intel_connector = to_intel_connector(connector);
17266         int ret;
17267
17268         ret = intel_backlight_device_register(intel_connector);
17269         if (ret)
17270                 goto err;
17271
17272         return 0;
17273
17274 err:
17275         return ret;
17276 }
17277
17278 void intel_connector_unregister(struct drm_connector *connector)
17279 {
17280         struct intel_connector *intel_connector = to_intel_connector(connector);
17281
17282         intel_backlight_device_unregister(intel_connector);
17283         intel_panel_destroy_backlight(connector);
17284 }
17285
17286 void intel_modeset_cleanup(struct drm_device *dev)
17287 {
17288         struct drm_i915_private *dev_priv = to_i915(dev);
17289
17290         flush_work(&dev_priv->atomic_helper.free_work);
17291         WARN_ON(!llist_empty(&dev_priv->atomic_helper.free_list));
17292
17293         intel_disable_gt_powersave(dev_priv);
17294
17295         /*
17296          * Interrupts and polling as the first thing to avoid creating havoc.
17297          * Too much stuff here (turning of connectors, ...) would
17298          * experience fancy races otherwise.
17299          */
17300         intel_irq_uninstall(dev_priv);
17301
17302         /*
17303          * Due to the hpd irq storm handling the hotplug work can re-arm the
17304          * poll handlers. Hence disable polling after hpd handling is shut down.
17305          */
17306         drm_kms_helper_poll_fini(dev);
17307
17308         intel_unregister_dsm_handler();
17309
17310         intel_fbc_global_disable(dev_priv);
17311
17312         /* flush any delayed tasks or pending work */
17313         flush_scheduled_work();
17314
17315         drm_mode_config_cleanup(dev);
17316
17317         intel_cleanup_overlay(dev_priv);
17318
17319         intel_cleanup_gt_powersave(dev_priv);
17320
17321         intel_teardown_gmbus(dev_priv);
17322 }
17323
17324 void intel_connector_attach_encoder(struct intel_connector *connector,
17325                                     struct intel_encoder *encoder)
17326 {
17327         connector->encoder = encoder;
17328         drm_mode_connector_attach_encoder(&connector->base,
17329                                           &encoder->base);
17330 }
17331
17332 /*
17333  * set vga decode state - true == enable VGA decode
17334  */
17335 int intel_modeset_vga_set_state(struct drm_i915_private *dev_priv, bool state)
17336 {
17337         unsigned reg = INTEL_GEN(dev_priv) >= 6 ? SNB_GMCH_CTRL : INTEL_GMCH_CTRL;
17338         u16 gmch_ctrl;
17339
17340         if (pci_read_config_word(dev_priv->bridge_dev, reg, &gmch_ctrl)) {
17341                 DRM_ERROR("failed to read control word\n");
17342                 return -EIO;
17343         }
17344
17345         if (!!(gmch_ctrl & INTEL_GMCH_VGA_DISABLE) == !state)
17346                 return 0;
17347
17348         if (state)
17349                 gmch_ctrl &= ~INTEL_GMCH_VGA_DISABLE;
17350         else
17351                 gmch_ctrl |= INTEL_GMCH_VGA_DISABLE;
17352
17353         if (pci_write_config_word(dev_priv->bridge_dev, reg, gmch_ctrl)) {
17354                 DRM_ERROR("failed to write control word\n");
17355                 return -EIO;
17356         }
17357
17358         return 0;
17359 }
17360
17361 #if IS_ENABLED(CONFIG_DRM_I915_CAPTURE_ERROR)
17362
17363 struct intel_display_error_state {
17364
17365         u32 power_well_driver;
17366
17367         int num_transcoders;
17368
17369         struct intel_cursor_error_state {
17370                 u32 control;
17371                 u32 position;
17372                 u32 base;
17373                 u32 size;
17374         } cursor[I915_MAX_PIPES];
17375
17376         struct intel_pipe_error_state {
17377                 bool power_domain_on;
17378                 u32 source;
17379                 u32 stat;
17380         } pipe[I915_MAX_PIPES];
17381
17382         struct intel_plane_error_state {
17383                 u32 control;
17384                 u32 stride;
17385                 u32 size;
17386                 u32 pos;
17387                 u32 addr;
17388                 u32 surface;
17389                 u32 tile_offset;
17390         } plane[I915_MAX_PIPES];
17391
17392         struct intel_transcoder_error_state {
17393                 bool power_domain_on;
17394                 enum transcoder cpu_transcoder;
17395
17396                 u32 conf;
17397
17398                 u32 htotal;
17399                 u32 hblank;
17400                 u32 hsync;
17401                 u32 vtotal;
17402                 u32 vblank;
17403                 u32 vsync;
17404         } transcoder[4];
17405 };
17406
17407 struct intel_display_error_state *
17408 intel_display_capture_error_state(struct drm_i915_private *dev_priv)
17409 {
17410         struct intel_display_error_state *error;
17411         int transcoders[] = {
17412                 TRANSCODER_A,
17413                 TRANSCODER_B,
17414                 TRANSCODER_C,
17415                 TRANSCODER_EDP,
17416         };
17417         int i;
17418
17419         if (INTEL_INFO(dev_priv)->num_pipes == 0)
17420                 return NULL;
17421
17422         error = kzalloc(sizeof(*error), GFP_ATOMIC);
17423         if (error == NULL)
17424                 return NULL;
17425
17426         if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv))
17427                 error->power_well_driver = I915_READ(HSW_PWR_WELL_DRIVER);
17428
17429         for_each_pipe(dev_priv, i) {
17430                 error->pipe[i].power_domain_on =
17431                         __intel_display_power_is_enabled(dev_priv,
17432                                                          POWER_DOMAIN_PIPE(i));
17433                 if (!error->pipe[i].power_domain_on)
17434                         continue;
17435
17436                 error->cursor[i].control = I915_READ(CURCNTR(i));
17437                 error->cursor[i].position = I915_READ(CURPOS(i));
17438                 error->cursor[i].base = I915_READ(CURBASE(i));
17439
17440                 error->plane[i].control = I915_READ(DSPCNTR(i));
17441                 error->plane[i].stride = I915_READ(DSPSTRIDE(i));
17442                 if (INTEL_GEN(dev_priv) <= 3) {
17443                         error->plane[i].size = I915_READ(DSPSIZE(i));
17444                         error->plane[i].pos = I915_READ(DSPPOS(i));
17445                 }
17446                 if (INTEL_GEN(dev_priv) <= 7 && !IS_HASWELL(dev_priv))
17447                         error->plane[i].addr = I915_READ(DSPADDR(i));
17448                 if (INTEL_GEN(dev_priv) >= 4) {
17449                         error->plane[i].surface = I915_READ(DSPSURF(i));
17450                         error->plane[i].tile_offset = I915_READ(DSPTILEOFF(i));
17451                 }
17452
17453                 error->pipe[i].source = I915_READ(PIPESRC(i));
17454
17455                 if (HAS_GMCH_DISPLAY(dev_priv))
17456                         error->pipe[i].stat = I915_READ(PIPESTAT(i));
17457         }
17458
17459         /* Note: this does not include DSI transcoders. */
17460         error->num_transcoders = INTEL_INFO(dev_priv)->num_pipes;
17461         if (HAS_DDI(dev_priv))
17462                 error->num_transcoders++; /* Account for eDP. */
17463
17464         for (i = 0; i < error->num_transcoders; i++) {
17465                 enum transcoder cpu_transcoder = transcoders[i];
17466
17467                 error->transcoder[i].power_domain_on =
17468                         __intel_display_power_is_enabled(dev_priv,
17469                                 POWER_DOMAIN_TRANSCODER(cpu_transcoder));
17470                 if (!error->transcoder[i].power_domain_on)
17471                         continue;
17472
17473                 error->transcoder[i].cpu_transcoder = cpu_transcoder;
17474
17475                 error->transcoder[i].conf = I915_READ(PIPECONF(cpu_transcoder));
17476                 error->transcoder[i].htotal = I915_READ(HTOTAL(cpu_transcoder));
17477                 error->transcoder[i].hblank = I915_READ(HBLANK(cpu_transcoder));
17478                 error->transcoder[i].hsync = I915_READ(HSYNC(cpu_transcoder));
17479                 error->transcoder[i].vtotal = I915_READ(VTOTAL(cpu_transcoder));
17480                 error->transcoder[i].vblank = I915_READ(VBLANK(cpu_transcoder));
17481                 error->transcoder[i].vsync = I915_READ(VSYNC(cpu_transcoder));
17482         }
17483
17484         return error;
17485 }
17486
17487 #define err_printf(e, ...) i915_error_printf(e, __VA_ARGS__)
17488
17489 void
17490 intel_display_print_error_state(struct drm_i915_error_state_buf *m,
17491                                 struct drm_i915_private *dev_priv,
17492                                 struct intel_display_error_state *error)
17493 {
17494         int i;
17495
17496         if (!error)
17497                 return;
17498
17499         err_printf(m, "Num Pipes: %d\n", INTEL_INFO(dev_priv)->num_pipes);
17500         if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv))
17501                 err_printf(m, "PWR_WELL_CTL2: %08x\n",
17502                            error->power_well_driver);
17503         for_each_pipe(dev_priv, i) {
17504                 err_printf(m, "Pipe [%d]:\n", i);
17505                 err_printf(m, "  Power: %s\n",
17506                            onoff(error->pipe[i].power_domain_on));
17507                 err_printf(m, "  SRC: %08x\n", error->pipe[i].source);
17508                 err_printf(m, "  STAT: %08x\n", error->pipe[i].stat);
17509
17510                 err_printf(m, "Plane [%d]:\n", i);
17511                 err_printf(m, "  CNTR: %08x\n", error->plane[i].control);
17512                 err_printf(m, "  STRIDE: %08x\n", error->plane[i].stride);
17513                 if (INTEL_GEN(dev_priv) <= 3) {
17514                         err_printf(m, "  SIZE: %08x\n", error->plane[i].size);
17515                         err_printf(m, "  POS: %08x\n", error->plane[i].pos);
17516                 }
17517                 if (INTEL_GEN(dev_priv) <= 7 && !IS_HASWELL(dev_priv))
17518                         err_printf(m, "  ADDR: %08x\n", error->plane[i].addr);
17519                 if (INTEL_GEN(dev_priv) >= 4) {
17520                         err_printf(m, "  SURF: %08x\n", error->plane[i].surface);
17521                         err_printf(m, "  TILEOFF: %08x\n", error->plane[i].tile_offset);
17522                 }
17523
17524                 err_printf(m, "Cursor [%d]:\n", i);
17525                 err_printf(m, "  CNTR: %08x\n", error->cursor[i].control);
17526                 err_printf(m, "  POS: %08x\n", error->cursor[i].position);
17527                 err_printf(m, "  BASE: %08x\n", error->cursor[i].base);
17528         }
17529
17530         for (i = 0; i < error->num_transcoders; i++) {
17531                 err_printf(m, "CPU transcoder: %s\n",
17532                            transcoder_name(error->transcoder[i].cpu_transcoder));
17533                 err_printf(m, "  Power: %s\n",
17534                            onoff(error->transcoder[i].power_domain_on));
17535                 err_printf(m, "  CONF: %08x\n", error->transcoder[i].conf);
17536                 err_printf(m, "  HTOTAL: %08x\n", error->transcoder[i].htotal);
17537                 err_printf(m, "  HBLANK: %08x\n", error->transcoder[i].hblank);
17538                 err_printf(m, "  HSYNC: %08x\n", error->transcoder[i].hsync);
17539                 err_printf(m, "  VTOTAL: %08x\n", error->transcoder[i].vtotal);
17540                 err_printf(m, "  VBLANK: %08x\n", error->transcoder[i].vblank);
17541                 err_printf(m, "  VSYNC: %08x\n", error->transcoder[i].vsync);
17542         }
17543 }
17544
17545 #endif