]> git.kernelconcepts.de Git - karo-tx-linux.git/blob - drivers/gpu/drm/i915/intel_display.c
Merge tag 'drm-intel-next-2016-10-24' of git://anongit.freedesktop.org/drm-intel...
[karo-tx-linux.git] / drivers / gpu / drm / i915 / intel_display.c
1 /*
2  * Copyright © 2006-2007 Intel Corporation
3  *
4  * Permission is hereby granted, free of charge, to any person obtaining a
5  * copy of this software and associated documentation files (the "Software"),
6  * to deal in the Software without restriction, including without limitation
7  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
8  * and/or sell copies of the Software, and to permit persons to whom the
9  * Software is furnished to do so, subject to the following conditions:
10  *
11  * The above copyright notice and this permission notice (including the next
12  * paragraph) shall be included in all copies or substantial portions of the
13  * Software.
14  *
15  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
18  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
21  * DEALINGS IN THE SOFTWARE.
22  *
23  * Authors:
24  *      Eric Anholt <eric@anholt.net>
25  */
26
27 #include <linux/dmi.h>
28 #include <linux/module.h>
29 #include <linux/input.h>
30 #include <linux/i2c.h>
31 #include <linux/kernel.h>
32 #include <linux/slab.h>
33 #include <linux/vgaarb.h>
34 #include <drm/drm_edid.h>
35 #include <drm/drmP.h>
36 #include "intel_drv.h"
37 #include "intel_frontbuffer.h"
38 #include <drm/i915_drm.h>
39 #include "i915_drv.h"
40 #include "i915_gem_dmabuf.h"
41 #include "intel_dsi.h"
42 #include "i915_trace.h"
43 #include <drm/drm_atomic.h>
44 #include <drm/drm_atomic_helper.h>
45 #include <drm/drm_dp_helper.h>
46 #include <drm/drm_crtc_helper.h>
47 #include <drm/drm_plane_helper.h>
48 #include <drm/drm_rect.h>
49 #include <linux/dma_remapping.h>
50 #include <linux/reservation.h>
51
52 static bool is_mmio_work(struct intel_flip_work *work)
53 {
54         return work->mmio_work.func;
55 }
56
57 /* Primary plane formats for gen <= 3 */
58 static const uint32_t i8xx_primary_formats[] = {
59         DRM_FORMAT_C8,
60         DRM_FORMAT_RGB565,
61         DRM_FORMAT_XRGB1555,
62         DRM_FORMAT_XRGB8888,
63 };
64
65 /* Primary plane formats for gen >= 4 */
66 static const uint32_t i965_primary_formats[] = {
67         DRM_FORMAT_C8,
68         DRM_FORMAT_RGB565,
69         DRM_FORMAT_XRGB8888,
70         DRM_FORMAT_XBGR8888,
71         DRM_FORMAT_XRGB2101010,
72         DRM_FORMAT_XBGR2101010,
73 };
74
75 static const uint32_t skl_primary_formats[] = {
76         DRM_FORMAT_C8,
77         DRM_FORMAT_RGB565,
78         DRM_FORMAT_XRGB8888,
79         DRM_FORMAT_XBGR8888,
80         DRM_FORMAT_ARGB8888,
81         DRM_FORMAT_ABGR8888,
82         DRM_FORMAT_XRGB2101010,
83         DRM_FORMAT_XBGR2101010,
84         DRM_FORMAT_YUYV,
85         DRM_FORMAT_YVYU,
86         DRM_FORMAT_UYVY,
87         DRM_FORMAT_VYUY,
88 };
89
90 /* Cursor formats */
91 static const uint32_t intel_cursor_formats[] = {
92         DRM_FORMAT_ARGB8888,
93 };
94
95 static void i9xx_crtc_clock_get(struct intel_crtc *crtc,
96                                 struct intel_crtc_state *pipe_config);
97 static void ironlake_pch_clock_get(struct intel_crtc *crtc,
98                                    struct intel_crtc_state *pipe_config);
99
100 static int intel_framebuffer_init(struct drm_device *dev,
101                                   struct intel_framebuffer *ifb,
102                                   struct drm_mode_fb_cmd2 *mode_cmd,
103                                   struct drm_i915_gem_object *obj);
104 static void i9xx_set_pipeconf(struct intel_crtc *intel_crtc);
105 static void intel_set_pipe_timings(struct intel_crtc *intel_crtc);
106 static void intel_set_pipe_src_size(struct intel_crtc *intel_crtc);
107 static void intel_cpu_transcoder_set_m_n(struct intel_crtc *crtc,
108                                          struct intel_link_m_n *m_n,
109                                          struct intel_link_m_n *m2_n2);
110 static void ironlake_set_pipeconf(struct drm_crtc *crtc);
111 static void haswell_set_pipeconf(struct drm_crtc *crtc);
112 static void haswell_set_pipemisc(struct drm_crtc *crtc);
113 static void vlv_prepare_pll(struct intel_crtc *crtc,
114                             const struct intel_crtc_state *pipe_config);
115 static void chv_prepare_pll(struct intel_crtc *crtc,
116                             const struct intel_crtc_state *pipe_config);
117 static void intel_begin_crtc_commit(struct drm_crtc *, struct drm_crtc_state *);
118 static void intel_finish_crtc_commit(struct drm_crtc *, struct drm_crtc_state *);
119 static void skl_init_scalers(struct drm_device *dev, struct intel_crtc *intel_crtc,
120         struct intel_crtc_state *crtc_state);
121 static void skylake_pfit_enable(struct intel_crtc *crtc);
122 static void ironlake_pfit_disable(struct intel_crtc *crtc, bool force);
123 static void ironlake_pfit_enable(struct intel_crtc *crtc);
124 static void intel_modeset_setup_hw_state(struct drm_device *dev);
125 static void intel_pre_disable_primary_noatomic(struct drm_crtc *crtc);
126 static int ilk_max_pixel_rate(struct drm_atomic_state *state);
127 static int bxt_calc_cdclk(int max_pixclk);
128
129 struct intel_limit {
130         struct {
131                 int min, max;
132         } dot, vco, n, m, m1, m2, p, p1;
133
134         struct {
135                 int dot_limit;
136                 int p2_slow, p2_fast;
137         } p2;
138 };
139
140 /* returns HPLL frequency in kHz */
141 static int valleyview_get_vco(struct drm_i915_private *dev_priv)
142 {
143         int hpll_freq, vco_freq[] = { 800, 1600, 2000, 2400 };
144
145         /* Obtain SKU information */
146         mutex_lock(&dev_priv->sb_lock);
147         hpll_freq = vlv_cck_read(dev_priv, CCK_FUSE_REG) &
148                 CCK_FUSE_HPLL_FREQ_MASK;
149         mutex_unlock(&dev_priv->sb_lock);
150
151         return vco_freq[hpll_freq] * 1000;
152 }
153
154 int vlv_get_cck_clock(struct drm_i915_private *dev_priv,
155                       const char *name, u32 reg, int ref_freq)
156 {
157         u32 val;
158         int divider;
159
160         mutex_lock(&dev_priv->sb_lock);
161         val = vlv_cck_read(dev_priv, reg);
162         mutex_unlock(&dev_priv->sb_lock);
163
164         divider = val & CCK_FREQUENCY_VALUES;
165
166         WARN((val & CCK_FREQUENCY_STATUS) !=
167              (divider << CCK_FREQUENCY_STATUS_SHIFT),
168              "%s change in progress\n", name);
169
170         return DIV_ROUND_CLOSEST(ref_freq << 1, divider + 1);
171 }
172
173 static int vlv_get_cck_clock_hpll(struct drm_i915_private *dev_priv,
174                                   const char *name, u32 reg)
175 {
176         if (dev_priv->hpll_freq == 0)
177                 dev_priv->hpll_freq = valleyview_get_vco(dev_priv);
178
179         return vlv_get_cck_clock(dev_priv, name, reg,
180                                  dev_priv->hpll_freq);
181 }
182
183 static int
184 intel_pch_rawclk(struct drm_i915_private *dev_priv)
185 {
186         return (I915_READ(PCH_RAWCLK_FREQ) & RAWCLK_FREQ_MASK) * 1000;
187 }
188
189 static int
190 intel_vlv_hrawclk(struct drm_i915_private *dev_priv)
191 {
192         /* RAWCLK_FREQ_VLV register updated from power well code */
193         return vlv_get_cck_clock_hpll(dev_priv, "hrawclk",
194                                       CCK_DISPLAY_REF_CLOCK_CONTROL);
195 }
196
197 static int
198 intel_g4x_hrawclk(struct drm_i915_private *dev_priv)
199 {
200         uint32_t clkcfg;
201
202         /* hrawclock is 1/4 the FSB frequency */
203         clkcfg = I915_READ(CLKCFG);
204         switch (clkcfg & CLKCFG_FSB_MASK) {
205         case CLKCFG_FSB_400:
206                 return 100000;
207         case CLKCFG_FSB_533:
208                 return 133333;
209         case CLKCFG_FSB_667:
210                 return 166667;
211         case CLKCFG_FSB_800:
212                 return 200000;
213         case CLKCFG_FSB_1067:
214                 return 266667;
215         case CLKCFG_FSB_1333:
216                 return 333333;
217         /* these two are just a guess; one of them might be right */
218         case CLKCFG_FSB_1600:
219         case CLKCFG_FSB_1600_ALT:
220                 return 400000;
221         default:
222                 return 133333;
223         }
224 }
225
226 void intel_update_rawclk(struct drm_i915_private *dev_priv)
227 {
228         if (HAS_PCH_SPLIT(dev_priv))
229                 dev_priv->rawclk_freq = intel_pch_rawclk(dev_priv);
230         else if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
231                 dev_priv->rawclk_freq = intel_vlv_hrawclk(dev_priv);
232         else if (IS_G4X(dev_priv) || IS_PINEVIEW(dev_priv))
233                 dev_priv->rawclk_freq = intel_g4x_hrawclk(dev_priv);
234         else
235                 return; /* no rawclk on other platforms, or no need to know it */
236
237         DRM_DEBUG_DRIVER("rawclk rate: %d kHz\n", dev_priv->rawclk_freq);
238 }
239
240 static void intel_update_czclk(struct drm_i915_private *dev_priv)
241 {
242         if (!(IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv)))
243                 return;
244
245         dev_priv->czclk_freq = vlv_get_cck_clock_hpll(dev_priv, "czclk",
246                                                       CCK_CZ_CLOCK_CONTROL);
247
248         DRM_DEBUG_DRIVER("CZ clock rate: %d kHz\n", dev_priv->czclk_freq);
249 }
250
251 static inline u32 /* units of 100MHz */
252 intel_fdi_link_freq(struct drm_i915_private *dev_priv,
253                     const struct intel_crtc_state *pipe_config)
254 {
255         if (HAS_DDI(dev_priv))
256                 return pipe_config->port_clock; /* SPLL */
257         else if (IS_GEN5(dev_priv))
258                 return ((I915_READ(FDI_PLL_BIOS_0) & FDI_PLL_FB_CLOCK_MASK) + 2) * 10000;
259         else
260                 return 270000;
261 }
262
263 static const struct intel_limit intel_limits_i8xx_dac = {
264         .dot = { .min = 25000, .max = 350000 },
265         .vco = { .min = 908000, .max = 1512000 },
266         .n = { .min = 2, .max = 16 },
267         .m = { .min = 96, .max = 140 },
268         .m1 = { .min = 18, .max = 26 },
269         .m2 = { .min = 6, .max = 16 },
270         .p = { .min = 4, .max = 128 },
271         .p1 = { .min = 2, .max = 33 },
272         .p2 = { .dot_limit = 165000,
273                 .p2_slow = 4, .p2_fast = 2 },
274 };
275
276 static const struct intel_limit intel_limits_i8xx_dvo = {
277         .dot = { .min = 25000, .max = 350000 },
278         .vco = { .min = 908000, .max = 1512000 },
279         .n = { .min = 2, .max = 16 },
280         .m = { .min = 96, .max = 140 },
281         .m1 = { .min = 18, .max = 26 },
282         .m2 = { .min = 6, .max = 16 },
283         .p = { .min = 4, .max = 128 },
284         .p1 = { .min = 2, .max = 33 },
285         .p2 = { .dot_limit = 165000,
286                 .p2_slow = 4, .p2_fast = 4 },
287 };
288
289 static const struct intel_limit intel_limits_i8xx_lvds = {
290         .dot = { .min = 25000, .max = 350000 },
291         .vco = { .min = 908000, .max = 1512000 },
292         .n = { .min = 2, .max = 16 },
293         .m = { .min = 96, .max = 140 },
294         .m1 = { .min = 18, .max = 26 },
295         .m2 = { .min = 6, .max = 16 },
296         .p = { .min = 4, .max = 128 },
297         .p1 = { .min = 1, .max = 6 },
298         .p2 = { .dot_limit = 165000,
299                 .p2_slow = 14, .p2_fast = 7 },
300 };
301
302 static const struct intel_limit intel_limits_i9xx_sdvo = {
303         .dot = { .min = 20000, .max = 400000 },
304         .vco = { .min = 1400000, .max = 2800000 },
305         .n = { .min = 1, .max = 6 },
306         .m = { .min = 70, .max = 120 },
307         .m1 = { .min = 8, .max = 18 },
308         .m2 = { .min = 3, .max = 7 },
309         .p = { .min = 5, .max = 80 },
310         .p1 = { .min = 1, .max = 8 },
311         .p2 = { .dot_limit = 200000,
312                 .p2_slow = 10, .p2_fast = 5 },
313 };
314
315 static const struct intel_limit intel_limits_i9xx_lvds = {
316         .dot = { .min = 20000, .max = 400000 },
317         .vco = { .min = 1400000, .max = 2800000 },
318         .n = { .min = 1, .max = 6 },
319         .m = { .min = 70, .max = 120 },
320         .m1 = { .min = 8, .max = 18 },
321         .m2 = { .min = 3, .max = 7 },
322         .p = { .min = 7, .max = 98 },
323         .p1 = { .min = 1, .max = 8 },
324         .p2 = { .dot_limit = 112000,
325                 .p2_slow = 14, .p2_fast = 7 },
326 };
327
328
329 static const struct intel_limit intel_limits_g4x_sdvo = {
330         .dot = { .min = 25000, .max = 270000 },
331         .vco = { .min = 1750000, .max = 3500000},
332         .n = { .min = 1, .max = 4 },
333         .m = { .min = 104, .max = 138 },
334         .m1 = { .min = 17, .max = 23 },
335         .m2 = { .min = 5, .max = 11 },
336         .p = { .min = 10, .max = 30 },
337         .p1 = { .min = 1, .max = 3},
338         .p2 = { .dot_limit = 270000,
339                 .p2_slow = 10,
340                 .p2_fast = 10
341         },
342 };
343
344 static const struct intel_limit intel_limits_g4x_hdmi = {
345         .dot = { .min = 22000, .max = 400000 },
346         .vco = { .min = 1750000, .max = 3500000},
347         .n = { .min = 1, .max = 4 },
348         .m = { .min = 104, .max = 138 },
349         .m1 = { .min = 16, .max = 23 },
350         .m2 = { .min = 5, .max = 11 },
351         .p = { .min = 5, .max = 80 },
352         .p1 = { .min = 1, .max = 8},
353         .p2 = { .dot_limit = 165000,
354                 .p2_slow = 10, .p2_fast = 5 },
355 };
356
357 static const struct intel_limit intel_limits_g4x_single_channel_lvds = {
358         .dot = { .min = 20000, .max = 115000 },
359         .vco = { .min = 1750000, .max = 3500000 },
360         .n = { .min = 1, .max = 3 },
361         .m = { .min = 104, .max = 138 },
362         .m1 = { .min = 17, .max = 23 },
363         .m2 = { .min = 5, .max = 11 },
364         .p = { .min = 28, .max = 112 },
365         .p1 = { .min = 2, .max = 8 },
366         .p2 = { .dot_limit = 0,
367                 .p2_slow = 14, .p2_fast = 14
368         },
369 };
370
371 static const struct intel_limit intel_limits_g4x_dual_channel_lvds = {
372         .dot = { .min = 80000, .max = 224000 },
373         .vco = { .min = 1750000, .max = 3500000 },
374         .n = { .min = 1, .max = 3 },
375         .m = { .min = 104, .max = 138 },
376         .m1 = { .min = 17, .max = 23 },
377         .m2 = { .min = 5, .max = 11 },
378         .p = { .min = 14, .max = 42 },
379         .p1 = { .min = 2, .max = 6 },
380         .p2 = { .dot_limit = 0,
381                 .p2_slow = 7, .p2_fast = 7
382         },
383 };
384
385 static const struct intel_limit intel_limits_pineview_sdvo = {
386         .dot = { .min = 20000, .max = 400000},
387         .vco = { .min = 1700000, .max = 3500000 },
388         /* Pineview's Ncounter is a ring counter */
389         .n = { .min = 3, .max = 6 },
390         .m = { .min = 2, .max = 256 },
391         /* Pineview only has one combined m divider, which we treat as m2. */
392         .m1 = { .min = 0, .max = 0 },
393         .m2 = { .min = 0, .max = 254 },
394         .p = { .min = 5, .max = 80 },
395         .p1 = { .min = 1, .max = 8 },
396         .p2 = { .dot_limit = 200000,
397                 .p2_slow = 10, .p2_fast = 5 },
398 };
399
400 static const struct intel_limit intel_limits_pineview_lvds = {
401         .dot = { .min = 20000, .max = 400000 },
402         .vco = { .min = 1700000, .max = 3500000 },
403         .n = { .min = 3, .max = 6 },
404         .m = { .min = 2, .max = 256 },
405         .m1 = { .min = 0, .max = 0 },
406         .m2 = { .min = 0, .max = 254 },
407         .p = { .min = 7, .max = 112 },
408         .p1 = { .min = 1, .max = 8 },
409         .p2 = { .dot_limit = 112000,
410                 .p2_slow = 14, .p2_fast = 14 },
411 };
412
413 /* Ironlake / Sandybridge
414  *
415  * We calculate clock using (register_value + 2) for N/M1/M2, so here
416  * the range value for them is (actual_value - 2).
417  */
418 static const struct intel_limit intel_limits_ironlake_dac = {
419         .dot = { .min = 25000, .max = 350000 },
420         .vco = { .min = 1760000, .max = 3510000 },
421         .n = { .min = 1, .max = 5 },
422         .m = { .min = 79, .max = 127 },
423         .m1 = { .min = 12, .max = 22 },
424         .m2 = { .min = 5, .max = 9 },
425         .p = { .min = 5, .max = 80 },
426         .p1 = { .min = 1, .max = 8 },
427         .p2 = { .dot_limit = 225000,
428                 .p2_slow = 10, .p2_fast = 5 },
429 };
430
431 static const struct intel_limit intel_limits_ironlake_single_lvds = {
432         .dot = { .min = 25000, .max = 350000 },
433         .vco = { .min = 1760000, .max = 3510000 },
434         .n = { .min = 1, .max = 3 },
435         .m = { .min = 79, .max = 118 },
436         .m1 = { .min = 12, .max = 22 },
437         .m2 = { .min = 5, .max = 9 },
438         .p = { .min = 28, .max = 112 },
439         .p1 = { .min = 2, .max = 8 },
440         .p2 = { .dot_limit = 225000,
441                 .p2_slow = 14, .p2_fast = 14 },
442 };
443
444 static const struct intel_limit intel_limits_ironlake_dual_lvds = {
445         .dot = { .min = 25000, .max = 350000 },
446         .vco = { .min = 1760000, .max = 3510000 },
447         .n = { .min = 1, .max = 3 },
448         .m = { .min = 79, .max = 127 },
449         .m1 = { .min = 12, .max = 22 },
450         .m2 = { .min = 5, .max = 9 },
451         .p = { .min = 14, .max = 56 },
452         .p1 = { .min = 2, .max = 8 },
453         .p2 = { .dot_limit = 225000,
454                 .p2_slow = 7, .p2_fast = 7 },
455 };
456
457 /* LVDS 100mhz refclk limits. */
458 static const struct intel_limit intel_limits_ironlake_single_lvds_100m = {
459         .dot = { .min = 25000, .max = 350000 },
460         .vco = { .min = 1760000, .max = 3510000 },
461         .n = { .min = 1, .max = 2 },
462         .m = { .min = 79, .max = 126 },
463         .m1 = { .min = 12, .max = 22 },
464         .m2 = { .min = 5, .max = 9 },
465         .p = { .min = 28, .max = 112 },
466         .p1 = { .min = 2, .max = 8 },
467         .p2 = { .dot_limit = 225000,
468                 .p2_slow = 14, .p2_fast = 14 },
469 };
470
471 static const struct intel_limit intel_limits_ironlake_dual_lvds_100m = {
472         .dot = { .min = 25000, .max = 350000 },
473         .vco = { .min = 1760000, .max = 3510000 },
474         .n = { .min = 1, .max = 3 },
475         .m = { .min = 79, .max = 126 },
476         .m1 = { .min = 12, .max = 22 },
477         .m2 = { .min = 5, .max = 9 },
478         .p = { .min = 14, .max = 42 },
479         .p1 = { .min = 2, .max = 6 },
480         .p2 = { .dot_limit = 225000,
481                 .p2_slow = 7, .p2_fast = 7 },
482 };
483
484 static const struct intel_limit intel_limits_vlv = {
485          /*
486           * These are the data rate limits (measured in fast clocks)
487           * since those are the strictest limits we have. The fast
488           * clock and actual rate limits are more relaxed, so checking
489           * them would make no difference.
490           */
491         .dot = { .min = 25000 * 5, .max = 270000 * 5 },
492         .vco = { .min = 4000000, .max = 6000000 },
493         .n = { .min = 1, .max = 7 },
494         .m1 = { .min = 2, .max = 3 },
495         .m2 = { .min = 11, .max = 156 },
496         .p1 = { .min = 2, .max = 3 },
497         .p2 = { .p2_slow = 2, .p2_fast = 20 }, /* slow=min, fast=max */
498 };
499
500 static const struct intel_limit intel_limits_chv = {
501         /*
502          * These are the data rate limits (measured in fast clocks)
503          * since those are the strictest limits we have.  The fast
504          * clock and actual rate limits are more relaxed, so checking
505          * them would make no difference.
506          */
507         .dot = { .min = 25000 * 5, .max = 540000 * 5},
508         .vco = { .min = 4800000, .max = 6480000 },
509         .n = { .min = 1, .max = 1 },
510         .m1 = { .min = 2, .max = 2 },
511         .m2 = { .min = 24 << 22, .max = 175 << 22 },
512         .p1 = { .min = 2, .max = 4 },
513         .p2 = { .p2_slow = 1, .p2_fast = 14 },
514 };
515
516 static const struct intel_limit intel_limits_bxt = {
517         /* FIXME: find real dot limits */
518         .dot = { .min = 0, .max = INT_MAX },
519         .vco = { .min = 4800000, .max = 6700000 },
520         .n = { .min = 1, .max = 1 },
521         .m1 = { .min = 2, .max = 2 },
522         /* FIXME: find real m2 limits */
523         .m2 = { .min = 2 << 22, .max = 255 << 22 },
524         .p1 = { .min = 2, .max = 4 },
525         .p2 = { .p2_slow = 1, .p2_fast = 20 },
526 };
527
528 static bool
529 needs_modeset(struct drm_crtc_state *state)
530 {
531         return drm_atomic_crtc_needs_modeset(state);
532 }
533
534 /*
535  * Platform specific helpers to calculate the port PLL loopback- (clock.m),
536  * and post-divider (clock.p) values, pre- (clock.vco) and post-divided fast
537  * (clock.dot) clock rates. This fast dot clock is fed to the port's IO logic.
538  * The helpers' return value is the rate of the clock that is fed to the
539  * display engine's pipe which can be the above fast dot clock rate or a
540  * divided-down version of it.
541  */
542 /* m1 is reserved as 0 in Pineview, n is a ring counter */
543 static int pnv_calc_dpll_params(int refclk, struct dpll *clock)
544 {
545         clock->m = clock->m2 + 2;
546         clock->p = clock->p1 * clock->p2;
547         if (WARN_ON(clock->n == 0 || clock->p == 0))
548                 return 0;
549         clock->vco = DIV_ROUND_CLOSEST(refclk * clock->m, clock->n);
550         clock->dot = DIV_ROUND_CLOSEST(clock->vco, clock->p);
551
552         return clock->dot;
553 }
554
555 static uint32_t i9xx_dpll_compute_m(struct dpll *dpll)
556 {
557         return 5 * (dpll->m1 + 2) + (dpll->m2 + 2);
558 }
559
560 static int i9xx_calc_dpll_params(int refclk, struct dpll *clock)
561 {
562         clock->m = i9xx_dpll_compute_m(clock);
563         clock->p = clock->p1 * clock->p2;
564         if (WARN_ON(clock->n + 2 == 0 || clock->p == 0))
565                 return 0;
566         clock->vco = DIV_ROUND_CLOSEST(refclk * clock->m, clock->n + 2);
567         clock->dot = DIV_ROUND_CLOSEST(clock->vco, clock->p);
568
569         return clock->dot;
570 }
571
572 static int vlv_calc_dpll_params(int refclk, struct dpll *clock)
573 {
574         clock->m = clock->m1 * clock->m2;
575         clock->p = clock->p1 * clock->p2;
576         if (WARN_ON(clock->n == 0 || clock->p == 0))
577                 return 0;
578         clock->vco = DIV_ROUND_CLOSEST(refclk * clock->m, clock->n);
579         clock->dot = DIV_ROUND_CLOSEST(clock->vco, clock->p);
580
581         return clock->dot / 5;
582 }
583
584 int chv_calc_dpll_params(int refclk, struct dpll *clock)
585 {
586         clock->m = clock->m1 * clock->m2;
587         clock->p = clock->p1 * clock->p2;
588         if (WARN_ON(clock->n == 0 || clock->p == 0))
589                 return 0;
590         clock->vco = DIV_ROUND_CLOSEST_ULL((uint64_t)refclk * clock->m,
591                         clock->n << 22);
592         clock->dot = DIV_ROUND_CLOSEST(clock->vco, clock->p);
593
594         return clock->dot / 5;
595 }
596
597 #define INTELPllInvalid(s)   do { /* DRM_DEBUG(s); */ return false; } while (0)
598 /**
599  * Returns whether the given set of divisors are valid for a given refclk with
600  * the given connectors.
601  */
602
603 static bool intel_PLL_is_valid(struct drm_i915_private *dev_priv,
604                                const struct intel_limit *limit,
605                                const struct dpll *clock)
606 {
607         if (clock->n   < limit->n.min   || limit->n.max   < clock->n)
608                 INTELPllInvalid("n out of range\n");
609         if (clock->p1  < limit->p1.min  || limit->p1.max  < clock->p1)
610                 INTELPllInvalid("p1 out of range\n");
611         if (clock->m2  < limit->m2.min  || limit->m2.max  < clock->m2)
612                 INTELPllInvalid("m2 out of range\n");
613         if (clock->m1  < limit->m1.min  || limit->m1.max  < clock->m1)
614                 INTELPllInvalid("m1 out of range\n");
615
616         if (!IS_PINEVIEW(dev_priv) && !IS_VALLEYVIEW(dev_priv) &&
617             !IS_CHERRYVIEW(dev_priv) && !IS_BROXTON(dev_priv))
618                 if (clock->m1 <= clock->m2)
619                         INTELPllInvalid("m1 <= m2\n");
620
621         if (!IS_VALLEYVIEW(dev_priv) && !IS_CHERRYVIEW(dev_priv) &&
622             !IS_BROXTON(dev_priv)) {
623                 if (clock->p < limit->p.min || limit->p.max < clock->p)
624                         INTELPllInvalid("p out of range\n");
625                 if (clock->m < limit->m.min || limit->m.max < clock->m)
626                         INTELPllInvalid("m out of range\n");
627         }
628
629         if (clock->vco < limit->vco.min || limit->vco.max < clock->vco)
630                 INTELPllInvalid("vco out of range\n");
631         /* XXX: We may need to be checking "Dot clock" depending on the multiplier,
632          * connector, etc., rather than just a single range.
633          */
634         if (clock->dot < limit->dot.min || limit->dot.max < clock->dot)
635                 INTELPllInvalid("dot out of range\n");
636
637         return true;
638 }
639
640 static int
641 i9xx_select_p2_div(const struct intel_limit *limit,
642                    const struct intel_crtc_state *crtc_state,
643                    int target)
644 {
645         struct drm_device *dev = crtc_state->base.crtc->dev;
646
647         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
648                 /*
649                  * For LVDS just rely on its current settings for dual-channel.
650                  * We haven't figured out how to reliably set up different
651                  * single/dual channel state, if we even can.
652                  */
653                 if (intel_is_dual_link_lvds(dev))
654                         return limit->p2.p2_fast;
655                 else
656                         return limit->p2.p2_slow;
657         } else {
658                 if (target < limit->p2.dot_limit)
659                         return limit->p2.p2_slow;
660                 else
661                         return limit->p2.p2_fast;
662         }
663 }
664
665 /*
666  * Returns a set of divisors for the desired target clock with the given
667  * refclk, or FALSE.  The returned values represent the clock equation:
668  * reflck * (5 * (m1 + 2) + (m2 + 2)) / (n + 2) / p1 / p2.
669  *
670  * Target and reference clocks are specified in kHz.
671  *
672  * If match_clock is provided, then best_clock P divider must match the P
673  * divider from @match_clock used for LVDS downclocking.
674  */
675 static bool
676 i9xx_find_best_dpll(const struct intel_limit *limit,
677                     struct intel_crtc_state *crtc_state,
678                     int target, int refclk, struct dpll *match_clock,
679                     struct dpll *best_clock)
680 {
681         struct drm_device *dev = crtc_state->base.crtc->dev;
682         struct dpll clock;
683         int err = target;
684
685         memset(best_clock, 0, sizeof(*best_clock));
686
687         clock.p2 = i9xx_select_p2_div(limit, crtc_state, target);
688
689         for (clock.m1 = limit->m1.min; clock.m1 <= limit->m1.max;
690              clock.m1++) {
691                 for (clock.m2 = limit->m2.min;
692                      clock.m2 <= limit->m2.max; clock.m2++) {
693                         if (clock.m2 >= clock.m1)
694                                 break;
695                         for (clock.n = limit->n.min;
696                              clock.n <= limit->n.max; clock.n++) {
697                                 for (clock.p1 = limit->p1.min;
698                                         clock.p1 <= limit->p1.max; clock.p1++) {
699                                         int this_err;
700
701                                         i9xx_calc_dpll_params(refclk, &clock);
702                                         if (!intel_PLL_is_valid(to_i915(dev),
703                                                                 limit,
704                                                                 &clock))
705                                                 continue;
706                                         if (match_clock &&
707                                             clock.p != match_clock->p)
708                                                 continue;
709
710                                         this_err = abs(clock.dot - target);
711                                         if (this_err < err) {
712                                                 *best_clock = clock;
713                                                 err = this_err;
714                                         }
715                                 }
716                         }
717                 }
718         }
719
720         return (err != target);
721 }
722
723 /*
724  * Returns a set of divisors for the desired target clock with the given
725  * refclk, or FALSE.  The returned values represent the clock equation:
726  * reflck * (5 * (m1 + 2) + (m2 + 2)) / (n + 2) / p1 / p2.
727  *
728  * Target and reference clocks are specified in kHz.
729  *
730  * If match_clock is provided, then best_clock P divider must match the P
731  * divider from @match_clock used for LVDS downclocking.
732  */
733 static bool
734 pnv_find_best_dpll(const struct intel_limit *limit,
735                    struct intel_crtc_state *crtc_state,
736                    int target, int refclk, struct dpll *match_clock,
737                    struct dpll *best_clock)
738 {
739         struct drm_device *dev = crtc_state->base.crtc->dev;
740         struct dpll clock;
741         int err = target;
742
743         memset(best_clock, 0, sizeof(*best_clock));
744
745         clock.p2 = i9xx_select_p2_div(limit, crtc_state, target);
746
747         for (clock.m1 = limit->m1.min; clock.m1 <= limit->m1.max;
748              clock.m1++) {
749                 for (clock.m2 = limit->m2.min;
750                      clock.m2 <= limit->m2.max; clock.m2++) {
751                         for (clock.n = limit->n.min;
752                              clock.n <= limit->n.max; clock.n++) {
753                                 for (clock.p1 = limit->p1.min;
754                                         clock.p1 <= limit->p1.max; clock.p1++) {
755                                         int this_err;
756
757                                         pnv_calc_dpll_params(refclk, &clock);
758                                         if (!intel_PLL_is_valid(to_i915(dev),
759                                                                 limit,
760                                                                 &clock))
761                                                 continue;
762                                         if (match_clock &&
763                                             clock.p != match_clock->p)
764                                                 continue;
765
766                                         this_err = abs(clock.dot - target);
767                                         if (this_err < err) {
768                                                 *best_clock = clock;
769                                                 err = this_err;
770                                         }
771                                 }
772                         }
773                 }
774         }
775
776         return (err != target);
777 }
778
779 /*
780  * Returns a set of divisors for the desired target clock with the given
781  * refclk, or FALSE.  The returned values represent the clock equation:
782  * reflck * (5 * (m1 + 2) + (m2 + 2)) / (n + 2) / p1 / p2.
783  *
784  * Target and reference clocks are specified in kHz.
785  *
786  * If match_clock is provided, then best_clock P divider must match the P
787  * divider from @match_clock used for LVDS downclocking.
788  */
789 static bool
790 g4x_find_best_dpll(const struct intel_limit *limit,
791                    struct intel_crtc_state *crtc_state,
792                    int target, int refclk, struct dpll *match_clock,
793                    struct dpll *best_clock)
794 {
795         struct drm_device *dev = crtc_state->base.crtc->dev;
796         struct dpll clock;
797         int max_n;
798         bool found = false;
799         /* approximately equals target * 0.00585 */
800         int err_most = (target >> 8) + (target >> 9);
801
802         memset(best_clock, 0, sizeof(*best_clock));
803
804         clock.p2 = i9xx_select_p2_div(limit, crtc_state, target);
805
806         max_n = limit->n.max;
807         /* based on hardware requirement, prefer smaller n to precision */
808         for (clock.n = limit->n.min; clock.n <= max_n; clock.n++) {
809                 /* based on hardware requirement, prefere larger m1,m2 */
810                 for (clock.m1 = limit->m1.max;
811                      clock.m1 >= limit->m1.min; clock.m1--) {
812                         for (clock.m2 = limit->m2.max;
813                              clock.m2 >= limit->m2.min; clock.m2--) {
814                                 for (clock.p1 = limit->p1.max;
815                                      clock.p1 >= limit->p1.min; clock.p1--) {
816                                         int this_err;
817
818                                         i9xx_calc_dpll_params(refclk, &clock);
819                                         if (!intel_PLL_is_valid(to_i915(dev),
820                                                                 limit,
821                                                                 &clock))
822                                                 continue;
823
824                                         this_err = abs(clock.dot - target);
825                                         if (this_err < err_most) {
826                                                 *best_clock = clock;
827                                                 err_most = this_err;
828                                                 max_n = clock.n;
829                                                 found = true;
830                                         }
831                                 }
832                         }
833                 }
834         }
835         return found;
836 }
837
838 /*
839  * Check if the calculated PLL configuration is more optimal compared to the
840  * best configuration and error found so far. Return the calculated error.
841  */
842 static bool vlv_PLL_is_optimal(struct drm_device *dev, int target_freq,
843                                const struct dpll *calculated_clock,
844                                const struct dpll *best_clock,
845                                unsigned int best_error_ppm,
846                                unsigned int *error_ppm)
847 {
848         /*
849          * For CHV ignore the error and consider only the P value.
850          * Prefer a bigger P value based on HW requirements.
851          */
852         if (IS_CHERRYVIEW(to_i915(dev))) {
853                 *error_ppm = 0;
854
855                 return calculated_clock->p > best_clock->p;
856         }
857
858         if (WARN_ON_ONCE(!target_freq))
859                 return false;
860
861         *error_ppm = div_u64(1000000ULL *
862                                 abs(target_freq - calculated_clock->dot),
863                              target_freq);
864         /*
865          * Prefer a better P value over a better (smaller) error if the error
866          * is small. Ensure this preference for future configurations too by
867          * setting the error to 0.
868          */
869         if (*error_ppm < 100 && calculated_clock->p > best_clock->p) {
870                 *error_ppm = 0;
871
872                 return true;
873         }
874
875         return *error_ppm + 10 < best_error_ppm;
876 }
877
878 /*
879  * Returns a set of divisors for the desired target clock with the given
880  * refclk, or FALSE.  The returned values represent the clock equation:
881  * reflck * (5 * (m1 + 2) + (m2 + 2)) / (n + 2) / p1 / p2.
882  */
883 static bool
884 vlv_find_best_dpll(const struct intel_limit *limit,
885                    struct intel_crtc_state *crtc_state,
886                    int target, int refclk, struct dpll *match_clock,
887                    struct dpll *best_clock)
888 {
889         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
890         struct drm_device *dev = crtc->base.dev;
891         struct dpll clock;
892         unsigned int bestppm = 1000000;
893         /* min update 19.2 MHz */
894         int max_n = min(limit->n.max, refclk / 19200);
895         bool found = false;
896
897         target *= 5; /* fast clock */
898
899         memset(best_clock, 0, sizeof(*best_clock));
900
901         /* based on hardware requirement, prefer smaller n to precision */
902         for (clock.n = limit->n.min; clock.n <= max_n; clock.n++) {
903                 for (clock.p1 = limit->p1.max; clock.p1 >= limit->p1.min; clock.p1--) {
904                         for (clock.p2 = limit->p2.p2_fast; clock.p2 >= limit->p2.p2_slow;
905                              clock.p2 -= clock.p2 > 10 ? 2 : 1) {
906                                 clock.p = clock.p1 * clock.p2;
907                                 /* based on hardware requirement, prefer bigger m1,m2 values */
908                                 for (clock.m1 = limit->m1.min; clock.m1 <= limit->m1.max; clock.m1++) {
909                                         unsigned int ppm;
910
911                                         clock.m2 = DIV_ROUND_CLOSEST(target * clock.p * clock.n,
912                                                                      refclk * clock.m1);
913
914                                         vlv_calc_dpll_params(refclk, &clock);
915
916                                         if (!intel_PLL_is_valid(to_i915(dev),
917                                                                 limit,
918                                                                 &clock))
919                                                 continue;
920
921                                         if (!vlv_PLL_is_optimal(dev, target,
922                                                                 &clock,
923                                                                 best_clock,
924                                                                 bestppm, &ppm))
925                                                 continue;
926
927                                         *best_clock = clock;
928                                         bestppm = ppm;
929                                         found = true;
930                                 }
931                         }
932                 }
933         }
934
935         return found;
936 }
937
938 /*
939  * Returns a set of divisors for the desired target clock with the given
940  * refclk, or FALSE.  The returned values represent the clock equation:
941  * reflck * (5 * (m1 + 2) + (m2 + 2)) / (n + 2) / p1 / p2.
942  */
943 static bool
944 chv_find_best_dpll(const struct intel_limit *limit,
945                    struct intel_crtc_state *crtc_state,
946                    int target, int refclk, struct dpll *match_clock,
947                    struct dpll *best_clock)
948 {
949         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
950         struct drm_device *dev = crtc->base.dev;
951         unsigned int best_error_ppm;
952         struct dpll clock;
953         uint64_t m2;
954         int found = false;
955
956         memset(best_clock, 0, sizeof(*best_clock));
957         best_error_ppm = 1000000;
958
959         /*
960          * Based on hardware doc, the n always set to 1, and m1 always
961          * set to 2.  If requires to support 200Mhz refclk, we need to
962          * revisit this because n may not 1 anymore.
963          */
964         clock.n = 1, clock.m1 = 2;
965         target *= 5;    /* fast clock */
966
967         for (clock.p1 = limit->p1.max; clock.p1 >= limit->p1.min; clock.p1--) {
968                 for (clock.p2 = limit->p2.p2_fast;
969                                 clock.p2 >= limit->p2.p2_slow;
970                                 clock.p2 -= clock.p2 > 10 ? 2 : 1) {
971                         unsigned int error_ppm;
972
973                         clock.p = clock.p1 * clock.p2;
974
975                         m2 = DIV_ROUND_CLOSEST_ULL(((uint64_t)target * clock.p *
976                                         clock.n) << 22, refclk * clock.m1);
977
978                         if (m2 > INT_MAX/clock.m1)
979                                 continue;
980
981                         clock.m2 = m2;
982
983                         chv_calc_dpll_params(refclk, &clock);
984
985                         if (!intel_PLL_is_valid(to_i915(dev), limit, &clock))
986                                 continue;
987
988                         if (!vlv_PLL_is_optimal(dev, target, &clock, best_clock,
989                                                 best_error_ppm, &error_ppm))
990                                 continue;
991
992                         *best_clock = clock;
993                         best_error_ppm = error_ppm;
994                         found = true;
995                 }
996         }
997
998         return found;
999 }
1000
1001 bool bxt_find_best_dpll(struct intel_crtc_state *crtc_state, int target_clock,
1002                         struct dpll *best_clock)
1003 {
1004         int refclk = 100000;
1005         const struct intel_limit *limit = &intel_limits_bxt;
1006
1007         return chv_find_best_dpll(limit, crtc_state,
1008                                   target_clock, refclk, NULL, best_clock);
1009 }
1010
1011 bool intel_crtc_active(struct drm_crtc *crtc)
1012 {
1013         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
1014
1015         /* Be paranoid as we can arrive here with only partial
1016          * state retrieved from the hardware during setup.
1017          *
1018          * We can ditch the adjusted_mode.crtc_clock check as soon
1019          * as Haswell has gained clock readout/fastboot support.
1020          *
1021          * We can ditch the crtc->primary->fb check as soon as we can
1022          * properly reconstruct framebuffers.
1023          *
1024          * FIXME: The intel_crtc->active here should be switched to
1025          * crtc->state->active once we have proper CRTC states wired up
1026          * for atomic.
1027          */
1028         return intel_crtc->active && crtc->primary->state->fb &&
1029                 intel_crtc->config->base.adjusted_mode.crtc_clock;
1030 }
1031
1032 enum transcoder intel_pipe_to_cpu_transcoder(struct drm_i915_private *dev_priv,
1033                                              enum pipe pipe)
1034 {
1035         struct drm_crtc *crtc = dev_priv->pipe_to_crtc_mapping[pipe];
1036         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
1037
1038         return intel_crtc->config->cpu_transcoder;
1039 }
1040
1041 static bool pipe_dsl_stopped(struct drm_device *dev, enum pipe pipe)
1042 {
1043         struct drm_i915_private *dev_priv = to_i915(dev);
1044         i915_reg_t reg = PIPEDSL(pipe);
1045         u32 line1, line2;
1046         u32 line_mask;
1047
1048         if (IS_GEN2(dev_priv))
1049                 line_mask = DSL_LINEMASK_GEN2;
1050         else
1051                 line_mask = DSL_LINEMASK_GEN3;
1052
1053         line1 = I915_READ(reg) & line_mask;
1054         msleep(5);
1055         line2 = I915_READ(reg) & line_mask;
1056
1057         return line1 == line2;
1058 }
1059
1060 /*
1061  * intel_wait_for_pipe_off - wait for pipe to turn off
1062  * @crtc: crtc whose pipe to wait for
1063  *
1064  * After disabling a pipe, we can't wait for vblank in the usual way,
1065  * spinning on the vblank interrupt status bit, since we won't actually
1066  * see an interrupt when the pipe is disabled.
1067  *
1068  * On Gen4 and above:
1069  *   wait for the pipe register state bit to turn off
1070  *
1071  * Otherwise:
1072  *   wait for the display line value to settle (it usually
1073  *   ends up stopping at the start of the next frame).
1074  *
1075  */
1076 static void intel_wait_for_pipe_off(struct intel_crtc *crtc)
1077 {
1078         struct drm_device *dev = crtc->base.dev;
1079         struct drm_i915_private *dev_priv = to_i915(dev);
1080         enum transcoder cpu_transcoder = crtc->config->cpu_transcoder;
1081         enum pipe pipe = crtc->pipe;
1082
1083         if (INTEL_INFO(dev)->gen >= 4) {
1084                 i915_reg_t reg = PIPECONF(cpu_transcoder);
1085
1086                 /* Wait for the Pipe State to go off */
1087                 if (intel_wait_for_register(dev_priv,
1088                                             reg, I965_PIPECONF_ACTIVE, 0,
1089                                             100))
1090                         WARN(1, "pipe_off wait timed out\n");
1091         } else {
1092                 /* Wait for the display line to settle */
1093                 if (wait_for(pipe_dsl_stopped(dev, pipe), 100))
1094                         WARN(1, "pipe_off wait timed out\n");
1095         }
1096 }
1097
1098 /* Only for pre-ILK configs */
1099 void assert_pll(struct drm_i915_private *dev_priv,
1100                 enum pipe pipe, bool state)
1101 {
1102         u32 val;
1103         bool cur_state;
1104
1105         val = I915_READ(DPLL(pipe));
1106         cur_state = !!(val & DPLL_VCO_ENABLE);
1107         I915_STATE_WARN(cur_state != state,
1108              "PLL state assertion failure (expected %s, current %s)\n",
1109                         onoff(state), onoff(cur_state));
1110 }
1111
1112 /* XXX: the dsi pll is shared between MIPI DSI ports */
1113 void assert_dsi_pll(struct drm_i915_private *dev_priv, bool state)
1114 {
1115         u32 val;
1116         bool cur_state;
1117
1118         mutex_lock(&dev_priv->sb_lock);
1119         val = vlv_cck_read(dev_priv, CCK_REG_DSI_PLL_CONTROL);
1120         mutex_unlock(&dev_priv->sb_lock);
1121
1122         cur_state = val & DSI_PLL_VCO_EN;
1123         I915_STATE_WARN(cur_state != state,
1124              "DSI PLL state assertion failure (expected %s, current %s)\n",
1125                         onoff(state), onoff(cur_state));
1126 }
1127
1128 static void assert_fdi_tx(struct drm_i915_private *dev_priv,
1129                           enum pipe pipe, bool state)
1130 {
1131         bool cur_state;
1132         enum transcoder cpu_transcoder = intel_pipe_to_cpu_transcoder(dev_priv,
1133                                                                       pipe);
1134
1135         if (HAS_DDI(dev_priv)) {
1136                 /* DDI does not have a specific FDI_TX register */
1137                 u32 val = I915_READ(TRANS_DDI_FUNC_CTL(cpu_transcoder));
1138                 cur_state = !!(val & TRANS_DDI_FUNC_ENABLE);
1139         } else {
1140                 u32 val = I915_READ(FDI_TX_CTL(pipe));
1141                 cur_state = !!(val & FDI_TX_ENABLE);
1142         }
1143         I915_STATE_WARN(cur_state != state,
1144              "FDI TX state assertion failure (expected %s, current %s)\n",
1145                         onoff(state), onoff(cur_state));
1146 }
1147 #define assert_fdi_tx_enabled(d, p) assert_fdi_tx(d, p, true)
1148 #define assert_fdi_tx_disabled(d, p) assert_fdi_tx(d, p, false)
1149
1150 static void assert_fdi_rx(struct drm_i915_private *dev_priv,
1151                           enum pipe pipe, bool state)
1152 {
1153         u32 val;
1154         bool cur_state;
1155
1156         val = I915_READ(FDI_RX_CTL(pipe));
1157         cur_state = !!(val & FDI_RX_ENABLE);
1158         I915_STATE_WARN(cur_state != state,
1159              "FDI RX state assertion failure (expected %s, current %s)\n",
1160                         onoff(state), onoff(cur_state));
1161 }
1162 #define assert_fdi_rx_enabled(d, p) assert_fdi_rx(d, p, true)
1163 #define assert_fdi_rx_disabled(d, p) assert_fdi_rx(d, p, false)
1164
1165 static void assert_fdi_tx_pll_enabled(struct drm_i915_private *dev_priv,
1166                                       enum pipe pipe)
1167 {
1168         u32 val;
1169
1170         /* ILK FDI PLL is always enabled */
1171         if (IS_GEN5(dev_priv))
1172                 return;
1173
1174         /* On Haswell, DDI ports are responsible for the FDI PLL setup */
1175         if (HAS_DDI(dev_priv))
1176                 return;
1177
1178         val = I915_READ(FDI_TX_CTL(pipe));
1179         I915_STATE_WARN(!(val & FDI_TX_PLL_ENABLE), "FDI TX PLL assertion failure, should be active but is disabled\n");
1180 }
1181
1182 void assert_fdi_rx_pll(struct drm_i915_private *dev_priv,
1183                        enum pipe pipe, bool state)
1184 {
1185         u32 val;
1186         bool cur_state;
1187
1188         val = I915_READ(FDI_RX_CTL(pipe));
1189         cur_state = !!(val & FDI_RX_PLL_ENABLE);
1190         I915_STATE_WARN(cur_state != state,
1191              "FDI RX PLL assertion failure (expected %s, current %s)\n",
1192                         onoff(state), onoff(cur_state));
1193 }
1194
1195 void assert_panel_unlocked(struct drm_i915_private *dev_priv, enum pipe pipe)
1196 {
1197         i915_reg_t pp_reg;
1198         u32 val;
1199         enum pipe panel_pipe = PIPE_A;
1200         bool locked = true;
1201
1202         if (WARN_ON(HAS_DDI(dev_priv)))
1203                 return;
1204
1205         if (HAS_PCH_SPLIT(dev_priv)) {
1206                 u32 port_sel;
1207
1208                 pp_reg = PP_CONTROL(0);
1209                 port_sel = I915_READ(PP_ON_DELAYS(0)) & PANEL_PORT_SELECT_MASK;
1210
1211                 if (port_sel == PANEL_PORT_SELECT_LVDS &&
1212                     I915_READ(PCH_LVDS) & LVDS_PIPEB_SELECT)
1213                         panel_pipe = PIPE_B;
1214                 /* XXX: else fix for eDP */
1215         } else if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv)) {
1216                 /* presumably write lock depends on pipe, not port select */
1217                 pp_reg = PP_CONTROL(pipe);
1218                 panel_pipe = pipe;
1219         } else {
1220                 pp_reg = PP_CONTROL(0);
1221                 if (I915_READ(LVDS) & LVDS_PIPEB_SELECT)
1222                         panel_pipe = PIPE_B;
1223         }
1224
1225         val = I915_READ(pp_reg);
1226         if (!(val & PANEL_POWER_ON) ||
1227             ((val & PANEL_UNLOCK_MASK) == PANEL_UNLOCK_REGS))
1228                 locked = false;
1229
1230         I915_STATE_WARN(panel_pipe == pipe && locked,
1231              "panel assertion failure, pipe %c regs locked\n",
1232              pipe_name(pipe));
1233 }
1234
1235 static void assert_cursor(struct drm_i915_private *dev_priv,
1236                           enum pipe pipe, bool state)
1237 {
1238         bool cur_state;
1239
1240         if (IS_845G(dev_priv) || IS_I865G(dev_priv))
1241                 cur_state = I915_READ(CURCNTR(PIPE_A)) & CURSOR_ENABLE;
1242         else
1243                 cur_state = I915_READ(CURCNTR(pipe)) & CURSOR_MODE;
1244
1245         I915_STATE_WARN(cur_state != state,
1246              "cursor on pipe %c assertion failure (expected %s, current %s)\n",
1247                         pipe_name(pipe), onoff(state), onoff(cur_state));
1248 }
1249 #define assert_cursor_enabled(d, p) assert_cursor(d, p, true)
1250 #define assert_cursor_disabled(d, p) assert_cursor(d, p, false)
1251
1252 void assert_pipe(struct drm_i915_private *dev_priv,
1253                  enum pipe pipe, bool state)
1254 {
1255         bool cur_state;
1256         enum transcoder cpu_transcoder = intel_pipe_to_cpu_transcoder(dev_priv,
1257                                                                       pipe);
1258         enum intel_display_power_domain power_domain;
1259
1260         /* if we need the pipe quirk it must be always on */
1261         if ((pipe == PIPE_A && dev_priv->quirks & QUIRK_PIPEA_FORCE) ||
1262             (pipe == PIPE_B && dev_priv->quirks & QUIRK_PIPEB_FORCE))
1263                 state = true;
1264
1265         power_domain = POWER_DOMAIN_TRANSCODER(cpu_transcoder);
1266         if (intel_display_power_get_if_enabled(dev_priv, power_domain)) {
1267                 u32 val = I915_READ(PIPECONF(cpu_transcoder));
1268                 cur_state = !!(val & PIPECONF_ENABLE);
1269
1270                 intel_display_power_put(dev_priv, power_domain);
1271         } else {
1272                 cur_state = false;
1273         }
1274
1275         I915_STATE_WARN(cur_state != state,
1276              "pipe %c assertion failure (expected %s, current %s)\n",
1277                         pipe_name(pipe), onoff(state), onoff(cur_state));
1278 }
1279
1280 static void assert_plane(struct drm_i915_private *dev_priv,
1281                          enum plane plane, bool state)
1282 {
1283         u32 val;
1284         bool cur_state;
1285
1286         val = I915_READ(DSPCNTR(plane));
1287         cur_state = !!(val & DISPLAY_PLANE_ENABLE);
1288         I915_STATE_WARN(cur_state != state,
1289              "plane %c assertion failure (expected %s, current %s)\n",
1290                         plane_name(plane), onoff(state), onoff(cur_state));
1291 }
1292
1293 #define assert_plane_enabled(d, p) assert_plane(d, p, true)
1294 #define assert_plane_disabled(d, p) assert_plane(d, p, false)
1295
1296 static void assert_planes_disabled(struct drm_i915_private *dev_priv,
1297                                    enum pipe pipe)
1298 {
1299         struct drm_device *dev = &dev_priv->drm;
1300         int i;
1301
1302         /* Primary planes are fixed to pipes on gen4+ */
1303         if (INTEL_INFO(dev)->gen >= 4) {
1304                 u32 val = I915_READ(DSPCNTR(pipe));
1305                 I915_STATE_WARN(val & DISPLAY_PLANE_ENABLE,
1306                      "plane %c assertion failure, should be disabled but not\n",
1307                      plane_name(pipe));
1308                 return;
1309         }
1310
1311         /* Need to check both planes against the pipe */
1312         for_each_pipe(dev_priv, i) {
1313                 u32 val = I915_READ(DSPCNTR(i));
1314                 enum pipe cur_pipe = (val & DISPPLANE_SEL_PIPE_MASK) >>
1315                         DISPPLANE_SEL_PIPE_SHIFT;
1316                 I915_STATE_WARN((val & DISPLAY_PLANE_ENABLE) && pipe == cur_pipe,
1317                      "plane %c assertion failure, should be off on pipe %c but is still active\n",
1318                      plane_name(i), pipe_name(pipe));
1319         }
1320 }
1321
1322 static void assert_sprites_disabled(struct drm_i915_private *dev_priv,
1323                                     enum pipe pipe)
1324 {
1325         struct drm_device *dev = &dev_priv->drm;
1326         int sprite;
1327
1328         if (INTEL_INFO(dev)->gen >= 9) {
1329                 for_each_sprite(dev_priv, pipe, sprite) {
1330                         u32 val = I915_READ(PLANE_CTL(pipe, sprite));
1331                         I915_STATE_WARN(val & PLANE_CTL_ENABLE,
1332                              "plane %d assertion failure, should be off on pipe %c but is still active\n",
1333                              sprite, pipe_name(pipe));
1334                 }
1335         } else if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv)) {
1336                 for_each_sprite(dev_priv, pipe, sprite) {
1337                         u32 val = I915_READ(SPCNTR(pipe, sprite));
1338                         I915_STATE_WARN(val & SP_ENABLE,
1339                              "sprite %c assertion failure, should be off on pipe %c but is still active\n",
1340                              sprite_name(pipe, sprite), pipe_name(pipe));
1341                 }
1342         } else if (INTEL_INFO(dev)->gen >= 7) {
1343                 u32 val = I915_READ(SPRCTL(pipe));
1344                 I915_STATE_WARN(val & SPRITE_ENABLE,
1345                      "sprite %c assertion failure, should be off on pipe %c but is still active\n",
1346                      plane_name(pipe), pipe_name(pipe));
1347         } else if (INTEL_INFO(dev)->gen >= 5) {
1348                 u32 val = I915_READ(DVSCNTR(pipe));
1349                 I915_STATE_WARN(val & DVS_ENABLE,
1350                      "sprite %c assertion failure, should be off on pipe %c but is still active\n",
1351                      plane_name(pipe), pipe_name(pipe));
1352         }
1353 }
1354
1355 static void assert_vblank_disabled(struct drm_crtc *crtc)
1356 {
1357         if (I915_STATE_WARN_ON(drm_crtc_vblank_get(crtc) == 0))
1358                 drm_crtc_vblank_put(crtc);
1359 }
1360
1361 void assert_pch_transcoder_disabled(struct drm_i915_private *dev_priv,
1362                                     enum pipe pipe)
1363 {
1364         u32 val;
1365         bool enabled;
1366
1367         val = I915_READ(PCH_TRANSCONF(pipe));
1368         enabled = !!(val & TRANS_ENABLE);
1369         I915_STATE_WARN(enabled,
1370              "transcoder assertion failed, should be off on pipe %c but is still active\n",
1371              pipe_name(pipe));
1372 }
1373
1374 static bool dp_pipe_enabled(struct drm_i915_private *dev_priv,
1375                             enum pipe pipe, u32 port_sel, u32 val)
1376 {
1377         if ((val & DP_PORT_EN) == 0)
1378                 return false;
1379
1380         if (HAS_PCH_CPT(dev_priv)) {
1381                 u32 trans_dp_ctl = I915_READ(TRANS_DP_CTL(pipe));
1382                 if ((trans_dp_ctl & TRANS_DP_PORT_SEL_MASK) != port_sel)
1383                         return false;
1384         } else if (IS_CHERRYVIEW(dev_priv)) {
1385                 if ((val & DP_PIPE_MASK_CHV) != DP_PIPE_SELECT_CHV(pipe))
1386                         return false;
1387         } else {
1388                 if ((val & DP_PIPE_MASK) != (pipe << 30))
1389                         return false;
1390         }
1391         return true;
1392 }
1393
1394 static bool hdmi_pipe_enabled(struct drm_i915_private *dev_priv,
1395                               enum pipe pipe, u32 val)
1396 {
1397         if ((val & SDVO_ENABLE) == 0)
1398                 return false;
1399
1400         if (HAS_PCH_CPT(dev_priv)) {
1401                 if ((val & SDVO_PIPE_SEL_MASK_CPT) != SDVO_PIPE_SEL_CPT(pipe))
1402                         return false;
1403         } else if (IS_CHERRYVIEW(dev_priv)) {
1404                 if ((val & SDVO_PIPE_SEL_MASK_CHV) != SDVO_PIPE_SEL_CHV(pipe))
1405                         return false;
1406         } else {
1407                 if ((val & SDVO_PIPE_SEL_MASK) != SDVO_PIPE_SEL(pipe))
1408                         return false;
1409         }
1410         return true;
1411 }
1412
1413 static bool lvds_pipe_enabled(struct drm_i915_private *dev_priv,
1414                               enum pipe pipe, u32 val)
1415 {
1416         if ((val & LVDS_PORT_EN) == 0)
1417                 return false;
1418
1419         if (HAS_PCH_CPT(dev_priv)) {
1420                 if ((val & PORT_TRANS_SEL_MASK) != PORT_TRANS_SEL_CPT(pipe))
1421                         return false;
1422         } else {
1423                 if ((val & LVDS_PIPE_MASK) != LVDS_PIPE(pipe))
1424                         return false;
1425         }
1426         return true;
1427 }
1428
1429 static bool adpa_pipe_enabled(struct drm_i915_private *dev_priv,
1430                               enum pipe pipe, u32 val)
1431 {
1432         if ((val & ADPA_DAC_ENABLE) == 0)
1433                 return false;
1434         if (HAS_PCH_CPT(dev_priv)) {
1435                 if ((val & PORT_TRANS_SEL_MASK) != PORT_TRANS_SEL_CPT(pipe))
1436                         return false;
1437         } else {
1438                 if ((val & ADPA_PIPE_SELECT_MASK) != ADPA_PIPE_SELECT(pipe))
1439                         return false;
1440         }
1441         return true;
1442 }
1443
1444 static void assert_pch_dp_disabled(struct drm_i915_private *dev_priv,
1445                                    enum pipe pipe, i915_reg_t reg,
1446                                    u32 port_sel)
1447 {
1448         u32 val = I915_READ(reg);
1449         I915_STATE_WARN(dp_pipe_enabled(dev_priv, pipe, port_sel, val),
1450              "PCH DP (0x%08x) enabled on transcoder %c, should be disabled\n",
1451              i915_mmio_reg_offset(reg), pipe_name(pipe));
1452
1453         I915_STATE_WARN(HAS_PCH_IBX(dev_priv) && (val & DP_PORT_EN) == 0
1454              && (val & DP_PIPEB_SELECT),
1455              "IBX PCH dp port still using transcoder B\n");
1456 }
1457
1458 static void assert_pch_hdmi_disabled(struct drm_i915_private *dev_priv,
1459                                      enum pipe pipe, i915_reg_t reg)
1460 {
1461         u32 val = I915_READ(reg);
1462         I915_STATE_WARN(hdmi_pipe_enabled(dev_priv, pipe, val),
1463              "PCH HDMI (0x%08x) enabled on transcoder %c, should be disabled\n",
1464              i915_mmio_reg_offset(reg), pipe_name(pipe));
1465
1466         I915_STATE_WARN(HAS_PCH_IBX(dev_priv) && (val & SDVO_ENABLE) == 0
1467              && (val & SDVO_PIPE_B_SELECT),
1468              "IBX PCH hdmi port still using transcoder B\n");
1469 }
1470
1471 static void assert_pch_ports_disabled(struct drm_i915_private *dev_priv,
1472                                       enum pipe pipe)
1473 {
1474         u32 val;
1475
1476         assert_pch_dp_disabled(dev_priv, pipe, PCH_DP_B, TRANS_DP_PORT_SEL_B);
1477         assert_pch_dp_disabled(dev_priv, pipe, PCH_DP_C, TRANS_DP_PORT_SEL_C);
1478         assert_pch_dp_disabled(dev_priv, pipe, PCH_DP_D, TRANS_DP_PORT_SEL_D);
1479
1480         val = I915_READ(PCH_ADPA);
1481         I915_STATE_WARN(adpa_pipe_enabled(dev_priv, pipe, val),
1482              "PCH VGA enabled on transcoder %c, should be disabled\n",
1483              pipe_name(pipe));
1484
1485         val = I915_READ(PCH_LVDS);
1486         I915_STATE_WARN(lvds_pipe_enabled(dev_priv, pipe, val),
1487              "PCH LVDS enabled on transcoder %c, should be disabled\n",
1488              pipe_name(pipe));
1489
1490         assert_pch_hdmi_disabled(dev_priv, pipe, PCH_HDMIB);
1491         assert_pch_hdmi_disabled(dev_priv, pipe, PCH_HDMIC);
1492         assert_pch_hdmi_disabled(dev_priv, pipe, PCH_HDMID);
1493 }
1494
1495 static void _vlv_enable_pll(struct intel_crtc *crtc,
1496                             const struct intel_crtc_state *pipe_config)
1497 {
1498         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1499         enum pipe pipe = crtc->pipe;
1500
1501         I915_WRITE(DPLL(pipe), pipe_config->dpll_hw_state.dpll);
1502         POSTING_READ(DPLL(pipe));
1503         udelay(150);
1504
1505         if (intel_wait_for_register(dev_priv,
1506                                     DPLL(pipe),
1507                                     DPLL_LOCK_VLV,
1508                                     DPLL_LOCK_VLV,
1509                                     1))
1510                 DRM_ERROR("DPLL %d failed to lock\n", pipe);
1511 }
1512
1513 static void vlv_enable_pll(struct intel_crtc *crtc,
1514                            const struct intel_crtc_state *pipe_config)
1515 {
1516         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1517         enum pipe pipe = crtc->pipe;
1518
1519         assert_pipe_disabled(dev_priv, pipe);
1520
1521         /* PLL is protected by panel, make sure we can write it */
1522         assert_panel_unlocked(dev_priv, pipe);
1523
1524         if (pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE)
1525                 _vlv_enable_pll(crtc, pipe_config);
1526
1527         I915_WRITE(DPLL_MD(pipe), pipe_config->dpll_hw_state.dpll_md);
1528         POSTING_READ(DPLL_MD(pipe));
1529 }
1530
1531
1532 static void _chv_enable_pll(struct intel_crtc *crtc,
1533                             const struct intel_crtc_state *pipe_config)
1534 {
1535         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1536         enum pipe pipe = crtc->pipe;
1537         enum dpio_channel port = vlv_pipe_to_channel(pipe);
1538         u32 tmp;
1539
1540         mutex_lock(&dev_priv->sb_lock);
1541
1542         /* Enable back the 10bit clock to display controller */
1543         tmp = vlv_dpio_read(dev_priv, pipe, CHV_CMN_DW14(port));
1544         tmp |= DPIO_DCLKP_EN;
1545         vlv_dpio_write(dev_priv, pipe, CHV_CMN_DW14(port), tmp);
1546
1547         mutex_unlock(&dev_priv->sb_lock);
1548
1549         /*
1550          * Need to wait > 100ns between dclkp clock enable bit and PLL enable.
1551          */
1552         udelay(1);
1553
1554         /* Enable PLL */
1555         I915_WRITE(DPLL(pipe), pipe_config->dpll_hw_state.dpll);
1556
1557         /* Check PLL is locked */
1558         if (intel_wait_for_register(dev_priv,
1559                                     DPLL(pipe), DPLL_LOCK_VLV, DPLL_LOCK_VLV,
1560                                     1))
1561                 DRM_ERROR("PLL %d failed to lock\n", pipe);
1562 }
1563
1564 static void chv_enable_pll(struct intel_crtc *crtc,
1565                            const struct intel_crtc_state *pipe_config)
1566 {
1567         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1568         enum pipe pipe = crtc->pipe;
1569
1570         assert_pipe_disabled(dev_priv, pipe);
1571
1572         /* PLL is protected by panel, make sure we can write it */
1573         assert_panel_unlocked(dev_priv, pipe);
1574
1575         if (pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE)
1576                 _chv_enable_pll(crtc, pipe_config);
1577
1578         if (pipe != PIPE_A) {
1579                 /*
1580                  * WaPixelRepeatModeFixForC0:chv
1581                  *
1582                  * DPLLCMD is AWOL. Use chicken bits to propagate
1583                  * the value from DPLLBMD to either pipe B or C.
1584                  */
1585                 I915_WRITE(CBR4_VLV, pipe == PIPE_B ? CBR_DPLLBMD_PIPE_B : CBR_DPLLBMD_PIPE_C);
1586                 I915_WRITE(DPLL_MD(PIPE_B), pipe_config->dpll_hw_state.dpll_md);
1587                 I915_WRITE(CBR4_VLV, 0);
1588                 dev_priv->chv_dpll_md[pipe] = pipe_config->dpll_hw_state.dpll_md;
1589
1590                 /*
1591                  * DPLLB VGA mode also seems to cause problems.
1592                  * We should always have it disabled.
1593                  */
1594                 WARN_ON((I915_READ(DPLL(PIPE_B)) & DPLL_VGA_MODE_DIS) == 0);
1595         } else {
1596                 I915_WRITE(DPLL_MD(pipe), pipe_config->dpll_hw_state.dpll_md);
1597                 POSTING_READ(DPLL_MD(pipe));
1598         }
1599 }
1600
1601 static int intel_num_dvo_pipes(struct drm_device *dev)
1602 {
1603         struct intel_crtc *crtc;
1604         int count = 0;
1605
1606         for_each_intel_crtc(dev, crtc) {
1607                 count += crtc->base.state->active &&
1608                         intel_crtc_has_type(crtc->config, INTEL_OUTPUT_DVO);
1609         }
1610
1611         return count;
1612 }
1613
1614 static void i9xx_enable_pll(struct intel_crtc *crtc)
1615 {
1616         struct drm_device *dev = crtc->base.dev;
1617         struct drm_i915_private *dev_priv = to_i915(dev);
1618         i915_reg_t reg = DPLL(crtc->pipe);
1619         u32 dpll = crtc->config->dpll_hw_state.dpll;
1620
1621         assert_pipe_disabled(dev_priv, crtc->pipe);
1622
1623         /* PLL is protected by panel, make sure we can write it */
1624         if (IS_MOBILE(dev_priv) && !IS_I830(dev_priv))
1625                 assert_panel_unlocked(dev_priv, crtc->pipe);
1626
1627         /* Enable DVO 2x clock on both PLLs if necessary */
1628         if (IS_I830(dev_priv) && intel_num_dvo_pipes(dev) > 0) {
1629                 /*
1630                  * It appears to be important that we don't enable this
1631                  * for the current pipe before otherwise configuring the
1632                  * PLL. No idea how this should be handled if multiple
1633                  * DVO outputs are enabled simultaneosly.
1634                  */
1635                 dpll |= DPLL_DVO_2X_MODE;
1636                 I915_WRITE(DPLL(!crtc->pipe),
1637                            I915_READ(DPLL(!crtc->pipe)) | DPLL_DVO_2X_MODE);
1638         }
1639
1640         /*
1641          * Apparently we need to have VGA mode enabled prior to changing
1642          * the P1/P2 dividers. Otherwise the DPLL will keep using the old
1643          * dividers, even though the register value does change.
1644          */
1645         I915_WRITE(reg, 0);
1646
1647         I915_WRITE(reg, dpll);
1648
1649         /* Wait for the clocks to stabilize. */
1650         POSTING_READ(reg);
1651         udelay(150);
1652
1653         if (INTEL_INFO(dev)->gen >= 4) {
1654                 I915_WRITE(DPLL_MD(crtc->pipe),
1655                            crtc->config->dpll_hw_state.dpll_md);
1656         } else {
1657                 /* The pixel multiplier can only be updated once the
1658                  * DPLL is enabled and the clocks are stable.
1659                  *
1660                  * So write it again.
1661                  */
1662                 I915_WRITE(reg, dpll);
1663         }
1664
1665         /* We do this three times for luck */
1666         I915_WRITE(reg, dpll);
1667         POSTING_READ(reg);
1668         udelay(150); /* wait for warmup */
1669         I915_WRITE(reg, dpll);
1670         POSTING_READ(reg);
1671         udelay(150); /* wait for warmup */
1672         I915_WRITE(reg, dpll);
1673         POSTING_READ(reg);
1674         udelay(150); /* wait for warmup */
1675 }
1676
1677 /**
1678  * i9xx_disable_pll - disable a PLL
1679  * @dev_priv: i915 private structure
1680  * @pipe: pipe PLL to disable
1681  *
1682  * Disable the PLL for @pipe, making sure the pipe is off first.
1683  *
1684  * Note!  This is for pre-ILK only.
1685  */
1686 static void i9xx_disable_pll(struct intel_crtc *crtc)
1687 {
1688         struct drm_device *dev = crtc->base.dev;
1689         struct drm_i915_private *dev_priv = to_i915(dev);
1690         enum pipe pipe = crtc->pipe;
1691
1692         /* Disable DVO 2x clock on both PLLs if necessary */
1693         if (IS_I830(dev_priv) &&
1694             intel_crtc_has_type(crtc->config, INTEL_OUTPUT_DVO) &&
1695             !intel_num_dvo_pipes(dev)) {
1696                 I915_WRITE(DPLL(PIPE_B),
1697                            I915_READ(DPLL(PIPE_B)) & ~DPLL_DVO_2X_MODE);
1698                 I915_WRITE(DPLL(PIPE_A),
1699                            I915_READ(DPLL(PIPE_A)) & ~DPLL_DVO_2X_MODE);
1700         }
1701
1702         /* Don't disable pipe or pipe PLLs if needed */
1703         if ((pipe == PIPE_A && dev_priv->quirks & QUIRK_PIPEA_FORCE) ||
1704             (pipe == PIPE_B && dev_priv->quirks & QUIRK_PIPEB_FORCE))
1705                 return;
1706
1707         /* Make sure the pipe isn't still relying on us */
1708         assert_pipe_disabled(dev_priv, pipe);
1709
1710         I915_WRITE(DPLL(pipe), DPLL_VGA_MODE_DIS);
1711         POSTING_READ(DPLL(pipe));
1712 }
1713
1714 static void vlv_disable_pll(struct drm_i915_private *dev_priv, enum pipe pipe)
1715 {
1716         u32 val;
1717
1718         /* Make sure the pipe isn't still relying on us */
1719         assert_pipe_disabled(dev_priv, pipe);
1720
1721         val = DPLL_INTEGRATED_REF_CLK_VLV |
1722                 DPLL_REF_CLK_ENABLE_VLV | DPLL_VGA_MODE_DIS;
1723         if (pipe != PIPE_A)
1724                 val |= DPLL_INTEGRATED_CRI_CLK_VLV;
1725
1726         I915_WRITE(DPLL(pipe), val);
1727         POSTING_READ(DPLL(pipe));
1728 }
1729
1730 static void chv_disable_pll(struct drm_i915_private *dev_priv, enum pipe pipe)
1731 {
1732         enum dpio_channel port = vlv_pipe_to_channel(pipe);
1733         u32 val;
1734
1735         /* Make sure the pipe isn't still relying on us */
1736         assert_pipe_disabled(dev_priv, pipe);
1737
1738         val = DPLL_SSC_REF_CLK_CHV |
1739                 DPLL_REF_CLK_ENABLE_VLV | DPLL_VGA_MODE_DIS;
1740         if (pipe != PIPE_A)
1741                 val |= DPLL_INTEGRATED_CRI_CLK_VLV;
1742
1743         I915_WRITE(DPLL(pipe), val);
1744         POSTING_READ(DPLL(pipe));
1745
1746         mutex_lock(&dev_priv->sb_lock);
1747
1748         /* Disable 10bit clock to display controller */
1749         val = vlv_dpio_read(dev_priv, pipe, CHV_CMN_DW14(port));
1750         val &= ~DPIO_DCLKP_EN;
1751         vlv_dpio_write(dev_priv, pipe, CHV_CMN_DW14(port), val);
1752
1753         mutex_unlock(&dev_priv->sb_lock);
1754 }
1755
1756 void vlv_wait_port_ready(struct drm_i915_private *dev_priv,
1757                          struct intel_digital_port *dport,
1758                          unsigned int expected_mask)
1759 {
1760         u32 port_mask;
1761         i915_reg_t dpll_reg;
1762
1763         switch (dport->port) {
1764         case PORT_B:
1765                 port_mask = DPLL_PORTB_READY_MASK;
1766                 dpll_reg = DPLL(0);
1767                 break;
1768         case PORT_C:
1769                 port_mask = DPLL_PORTC_READY_MASK;
1770                 dpll_reg = DPLL(0);
1771                 expected_mask <<= 4;
1772                 break;
1773         case PORT_D:
1774                 port_mask = DPLL_PORTD_READY_MASK;
1775                 dpll_reg = DPIO_PHY_STATUS;
1776                 break;
1777         default:
1778                 BUG();
1779         }
1780
1781         if (intel_wait_for_register(dev_priv,
1782                                     dpll_reg, port_mask, expected_mask,
1783                                     1000))
1784                 WARN(1, "timed out waiting for port %c ready: got 0x%x, expected 0x%x\n",
1785                      port_name(dport->port), I915_READ(dpll_reg) & port_mask, expected_mask);
1786 }
1787
1788 static void ironlake_enable_pch_transcoder(struct drm_i915_private *dev_priv,
1789                                            enum pipe pipe)
1790 {
1791         struct drm_crtc *crtc = dev_priv->pipe_to_crtc_mapping[pipe];
1792         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
1793         i915_reg_t reg;
1794         uint32_t val, pipeconf_val;
1795
1796         /* Make sure PCH DPLL is enabled */
1797         assert_shared_dpll_enabled(dev_priv, intel_crtc->config->shared_dpll);
1798
1799         /* FDI must be feeding us bits for PCH ports */
1800         assert_fdi_tx_enabled(dev_priv, pipe);
1801         assert_fdi_rx_enabled(dev_priv, pipe);
1802
1803         if (HAS_PCH_CPT(dev_priv)) {
1804                 /* Workaround: Set the timing override bit before enabling the
1805                  * pch transcoder. */
1806                 reg = TRANS_CHICKEN2(pipe);
1807                 val = I915_READ(reg);
1808                 val |= TRANS_CHICKEN2_TIMING_OVERRIDE;
1809                 I915_WRITE(reg, val);
1810         }
1811
1812         reg = PCH_TRANSCONF(pipe);
1813         val = I915_READ(reg);
1814         pipeconf_val = I915_READ(PIPECONF(pipe));
1815
1816         if (HAS_PCH_IBX(dev_priv)) {
1817                 /*
1818                  * Make the BPC in transcoder be consistent with
1819                  * that in pipeconf reg. For HDMI we must use 8bpc
1820                  * here for both 8bpc and 12bpc.
1821                  */
1822                 val &= ~PIPECONF_BPC_MASK;
1823                 if (intel_crtc_has_type(intel_crtc->config, INTEL_OUTPUT_HDMI))
1824                         val |= PIPECONF_8BPC;
1825                 else
1826                         val |= pipeconf_val & PIPECONF_BPC_MASK;
1827         }
1828
1829         val &= ~TRANS_INTERLACE_MASK;
1830         if ((pipeconf_val & PIPECONF_INTERLACE_MASK) == PIPECONF_INTERLACED_ILK)
1831                 if (HAS_PCH_IBX(dev_priv) &&
1832                     intel_crtc_has_type(intel_crtc->config, INTEL_OUTPUT_SDVO))
1833                         val |= TRANS_LEGACY_INTERLACED_ILK;
1834                 else
1835                         val |= TRANS_INTERLACED;
1836         else
1837                 val |= TRANS_PROGRESSIVE;
1838
1839         I915_WRITE(reg, val | TRANS_ENABLE);
1840         if (intel_wait_for_register(dev_priv,
1841                                     reg, TRANS_STATE_ENABLE, TRANS_STATE_ENABLE,
1842                                     100))
1843                 DRM_ERROR("failed to enable transcoder %c\n", pipe_name(pipe));
1844 }
1845
1846 static void lpt_enable_pch_transcoder(struct drm_i915_private *dev_priv,
1847                                       enum transcoder cpu_transcoder)
1848 {
1849         u32 val, pipeconf_val;
1850
1851         /* FDI must be feeding us bits for PCH ports */
1852         assert_fdi_tx_enabled(dev_priv, (enum pipe) cpu_transcoder);
1853         assert_fdi_rx_enabled(dev_priv, TRANSCODER_A);
1854
1855         /* Workaround: set timing override bit. */
1856         val = I915_READ(TRANS_CHICKEN2(PIPE_A));
1857         val |= TRANS_CHICKEN2_TIMING_OVERRIDE;
1858         I915_WRITE(TRANS_CHICKEN2(PIPE_A), val);
1859
1860         val = TRANS_ENABLE;
1861         pipeconf_val = I915_READ(PIPECONF(cpu_transcoder));
1862
1863         if ((pipeconf_val & PIPECONF_INTERLACE_MASK_HSW) ==
1864             PIPECONF_INTERLACED_ILK)
1865                 val |= TRANS_INTERLACED;
1866         else
1867                 val |= TRANS_PROGRESSIVE;
1868
1869         I915_WRITE(LPT_TRANSCONF, val);
1870         if (intel_wait_for_register(dev_priv,
1871                                     LPT_TRANSCONF,
1872                                     TRANS_STATE_ENABLE,
1873                                     TRANS_STATE_ENABLE,
1874                                     100))
1875                 DRM_ERROR("Failed to enable PCH transcoder\n");
1876 }
1877
1878 static void ironlake_disable_pch_transcoder(struct drm_i915_private *dev_priv,
1879                                             enum pipe pipe)
1880 {
1881         i915_reg_t reg;
1882         uint32_t val;
1883
1884         /* FDI relies on the transcoder */
1885         assert_fdi_tx_disabled(dev_priv, pipe);
1886         assert_fdi_rx_disabled(dev_priv, pipe);
1887
1888         /* Ports must be off as well */
1889         assert_pch_ports_disabled(dev_priv, pipe);
1890
1891         reg = PCH_TRANSCONF(pipe);
1892         val = I915_READ(reg);
1893         val &= ~TRANS_ENABLE;
1894         I915_WRITE(reg, val);
1895         /* wait for PCH transcoder off, transcoder state */
1896         if (intel_wait_for_register(dev_priv,
1897                                     reg, TRANS_STATE_ENABLE, 0,
1898                                     50))
1899                 DRM_ERROR("failed to disable transcoder %c\n", pipe_name(pipe));
1900
1901         if (HAS_PCH_CPT(dev_priv)) {
1902                 /* Workaround: Clear the timing override chicken bit again. */
1903                 reg = TRANS_CHICKEN2(pipe);
1904                 val = I915_READ(reg);
1905                 val &= ~TRANS_CHICKEN2_TIMING_OVERRIDE;
1906                 I915_WRITE(reg, val);
1907         }
1908 }
1909
1910 void lpt_disable_pch_transcoder(struct drm_i915_private *dev_priv)
1911 {
1912         u32 val;
1913
1914         val = I915_READ(LPT_TRANSCONF);
1915         val &= ~TRANS_ENABLE;
1916         I915_WRITE(LPT_TRANSCONF, val);
1917         /* wait for PCH transcoder off, transcoder state */
1918         if (intel_wait_for_register(dev_priv,
1919                                     LPT_TRANSCONF, TRANS_STATE_ENABLE, 0,
1920                                     50))
1921                 DRM_ERROR("Failed to disable PCH transcoder\n");
1922
1923         /* Workaround: clear timing override bit. */
1924         val = I915_READ(TRANS_CHICKEN2(PIPE_A));
1925         val &= ~TRANS_CHICKEN2_TIMING_OVERRIDE;
1926         I915_WRITE(TRANS_CHICKEN2(PIPE_A), val);
1927 }
1928
1929 enum transcoder intel_crtc_pch_transcoder(struct intel_crtc *crtc)
1930 {
1931         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1932
1933         WARN_ON(!crtc->config->has_pch_encoder);
1934
1935         if (HAS_PCH_LPT(dev_priv))
1936                 return TRANSCODER_A;
1937         else
1938                 return (enum transcoder) crtc->pipe;
1939 }
1940
1941 /**
1942  * intel_enable_pipe - enable a pipe, asserting requirements
1943  * @crtc: crtc responsible for the pipe
1944  *
1945  * Enable @crtc's pipe, making sure that various hardware specific requirements
1946  * are met, if applicable, e.g. PLL enabled, LVDS pairs enabled, etc.
1947  */
1948 static void intel_enable_pipe(struct intel_crtc *crtc)
1949 {
1950         struct drm_device *dev = crtc->base.dev;
1951         struct drm_i915_private *dev_priv = to_i915(dev);
1952         enum pipe pipe = crtc->pipe;
1953         enum transcoder cpu_transcoder = crtc->config->cpu_transcoder;
1954         i915_reg_t reg;
1955         u32 val;
1956
1957         DRM_DEBUG_KMS("enabling pipe %c\n", pipe_name(pipe));
1958
1959         assert_planes_disabled(dev_priv, pipe);
1960         assert_cursor_disabled(dev_priv, pipe);
1961         assert_sprites_disabled(dev_priv, pipe);
1962
1963         /*
1964          * A pipe without a PLL won't actually be able to drive bits from
1965          * a plane.  On ILK+ the pipe PLLs are integrated, so we don't
1966          * need the check.
1967          */
1968         if (HAS_GMCH_DISPLAY(dev_priv)) {
1969                 if (intel_crtc_has_type(crtc->config, INTEL_OUTPUT_DSI))
1970                         assert_dsi_pll_enabled(dev_priv);
1971                 else
1972                         assert_pll_enabled(dev_priv, pipe);
1973         } else {
1974                 if (crtc->config->has_pch_encoder) {
1975                         /* if driving the PCH, we need FDI enabled */
1976                         assert_fdi_rx_pll_enabled(dev_priv,
1977                                                   (enum pipe) intel_crtc_pch_transcoder(crtc));
1978                         assert_fdi_tx_pll_enabled(dev_priv,
1979                                                   (enum pipe) cpu_transcoder);
1980                 }
1981                 /* FIXME: assert CPU port conditions for SNB+ */
1982         }
1983
1984         reg = PIPECONF(cpu_transcoder);
1985         val = I915_READ(reg);
1986         if (val & PIPECONF_ENABLE) {
1987                 WARN_ON(!((pipe == PIPE_A && dev_priv->quirks & QUIRK_PIPEA_FORCE) ||
1988                           (pipe == PIPE_B && dev_priv->quirks & QUIRK_PIPEB_FORCE)));
1989                 return;
1990         }
1991
1992         I915_WRITE(reg, val | PIPECONF_ENABLE);
1993         POSTING_READ(reg);
1994
1995         /*
1996          * Until the pipe starts DSL will read as 0, which would cause
1997          * an apparent vblank timestamp jump, which messes up also the
1998          * frame count when it's derived from the timestamps. So let's
1999          * wait for the pipe to start properly before we call
2000          * drm_crtc_vblank_on()
2001          */
2002         if (dev->max_vblank_count == 0 &&
2003             wait_for(intel_get_crtc_scanline(crtc) != crtc->scanline_offset, 50))
2004                 DRM_ERROR("pipe %c didn't start\n", pipe_name(pipe));
2005 }
2006
2007 /**
2008  * intel_disable_pipe - disable a pipe, asserting requirements
2009  * @crtc: crtc whose pipes is to be disabled
2010  *
2011  * Disable the pipe of @crtc, making sure that various hardware
2012  * specific requirements are met, if applicable, e.g. plane
2013  * disabled, panel fitter off, etc.
2014  *
2015  * Will wait until the pipe has shut down before returning.
2016  */
2017 static void intel_disable_pipe(struct intel_crtc *crtc)
2018 {
2019         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
2020         enum transcoder cpu_transcoder = crtc->config->cpu_transcoder;
2021         enum pipe pipe = crtc->pipe;
2022         i915_reg_t reg;
2023         u32 val;
2024
2025         DRM_DEBUG_KMS("disabling pipe %c\n", pipe_name(pipe));
2026
2027         /*
2028          * Make sure planes won't keep trying to pump pixels to us,
2029          * or we might hang the display.
2030          */
2031         assert_planes_disabled(dev_priv, pipe);
2032         assert_cursor_disabled(dev_priv, pipe);
2033         assert_sprites_disabled(dev_priv, pipe);
2034
2035         reg = PIPECONF(cpu_transcoder);
2036         val = I915_READ(reg);
2037         if ((val & PIPECONF_ENABLE) == 0)
2038                 return;
2039
2040         /*
2041          * Double wide has implications for planes
2042          * so best keep it disabled when not needed.
2043          */
2044         if (crtc->config->double_wide)
2045                 val &= ~PIPECONF_DOUBLE_WIDE;
2046
2047         /* Don't disable pipe or pipe PLLs if needed */
2048         if (!(pipe == PIPE_A && dev_priv->quirks & QUIRK_PIPEA_FORCE) &&
2049             !(pipe == PIPE_B && dev_priv->quirks & QUIRK_PIPEB_FORCE))
2050                 val &= ~PIPECONF_ENABLE;
2051
2052         I915_WRITE(reg, val);
2053         if ((val & PIPECONF_ENABLE) == 0)
2054                 intel_wait_for_pipe_off(crtc);
2055 }
2056
2057 static unsigned int intel_tile_size(const struct drm_i915_private *dev_priv)
2058 {
2059         return IS_GEN2(dev_priv) ? 2048 : 4096;
2060 }
2061
2062 static unsigned int intel_tile_width_bytes(const struct drm_i915_private *dev_priv,
2063                                            uint64_t fb_modifier, unsigned int cpp)
2064 {
2065         switch (fb_modifier) {
2066         case DRM_FORMAT_MOD_NONE:
2067                 return cpp;
2068         case I915_FORMAT_MOD_X_TILED:
2069                 if (IS_GEN2(dev_priv))
2070                         return 128;
2071                 else
2072                         return 512;
2073         case I915_FORMAT_MOD_Y_TILED:
2074                 if (IS_GEN2(dev_priv) || HAS_128_BYTE_Y_TILING(dev_priv))
2075                         return 128;
2076                 else
2077                         return 512;
2078         case I915_FORMAT_MOD_Yf_TILED:
2079                 switch (cpp) {
2080                 case 1:
2081                         return 64;
2082                 case 2:
2083                 case 4:
2084                         return 128;
2085                 case 8:
2086                 case 16:
2087                         return 256;
2088                 default:
2089                         MISSING_CASE(cpp);
2090                         return cpp;
2091                 }
2092                 break;
2093         default:
2094                 MISSING_CASE(fb_modifier);
2095                 return cpp;
2096         }
2097 }
2098
2099 unsigned int intel_tile_height(const struct drm_i915_private *dev_priv,
2100                                uint64_t fb_modifier, unsigned int cpp)
2101 {
2102         if (fb_modifier == DRM_FORMAT_MOD_NONE)
2103                 return 1;
2104         else
2105                 return intel_tile_size(dev_priv) /
2106                         intel_tile_width_bytes(dev_priv, fb_modifier, cpp);
2107 }
2108
2109 /* Return the tile dimensions in pixel units */
2110 static void intel_tile_dims(const struct drm_i915_private *dev_priv,
2111                             unsigned int *tile_width,
2112                             unsigned int *tile_height,
2113                             uint64_t fb_modifier,
2114                             unsigned int cpp)
2115 {
2116         unsigned int tile_width_bytes =
2117                 intel_tile_width_bytes(dev_priv, fb_modifier, cpp);
2118
2119         *tile_width = tile_width_bytes / cpp;
2120         *tile_height = intel_tile_size(dev_priv) / tile_width_bytes;
2121 }
2122
2123 unsigned int
2124 intel_fb_align_height(struct drm_device *dev, unsigned int height,
2125                       uint32_t pixel_format, uint64_t fb_modifier)
2126 {
2127         unsigned int cpp = drm_format_plane_cpp(pixel_format, 0);
2128         unsigned int tile_height = intel_tile_height(to_i915(dev), fb_modifier, cpp);
2129
2130         return ALIGN(height, tile_height);
2131 }
2132
2133 unsigned int intel_rotation_info_size(const struct intel_rotation_info *rot_info)
2134 {
2135         unsigned int size = 0;
2136         int i;
2137
2138         for (i = 0 ; i < ARRAY_SIZE(rot_info->plane); i++)
2139                 size += rot_info->plane[i].width * rot_info->plane[i].height;
2140
2141         return size;
2142 }
2143
2144 static void
2145 intel_fill_fb_ggtt_view(struct i915_ggtt_view *view,
2146                         const struct drm_framebuffer *fb,
2147                         unsigned int rotation)
2148 {
2149         if (drm_rotation_90_or_270(rotation)) {
2150                 *view = i915_ggtt_view_rotated;
2151                 view->params.rotated = to_intel_framebuffer(fb)->rot_info;
2152         } else {
2153                 *view = i915_ggtt_view_normal;
2154         }
2155 }
2156
2157 static unsigned int intel_linear_alignment(const struct drm_i915_private *dev_priv)
2158 {
2159         if (INTEL_INFO(dev_priv)->gen >= 9)
2160                 return 256 * 1024;
2161         else if (IS_BROADWATER(dev_priv) || IS_CRESTLINE(dev_priv) ||
2162                  IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
2163                 return 128 * 1024;
2164         else if (INTEL_INFO(dev_priv)->gen >= 4)
2165                 return 4 * 1024;
2166         else
2167                 return 0;
2168 }
2169
2170 static unsigned int intel_surf_alignment(const struct drm_i915_private *dev_priv,
2171                                          uint64_t fb_modifier)
2172 {
2173         switch (fb_modifier) {
2174         case DRM_FORMAT_MOD_NONE:
2175                 return intel_linear_alignment(dev_priv);
2176         case I915_FORMAT_MOD_X_TILED:
2177                 if (INTEL_INFO(dev_priv)->gen >= 9)
2178                         return 256 * 1024;
2179                 return 0;
2180         case I915_FORMAT_MOD_Y_TILED:
2181         case I915_FORMAT_MOD_Yf_TILED:
2182                 return 1 * 1024 * 1024;
2183         default:
2184                 MISSING_CASE(fb_modifier);
2185                 return 0;
2186         }
2187 }
2188
2189 struct i915_vma *
2190 intel_pin_and_fence_fb_obj(struct drm_framebuffer *fb, unsigned int rotation)
2191 {
2192         struct drm_device *dev = fb->dev;
2193         struct drm_i915_private *dev_priv = to_i915(dev);
2194         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
2195         struct i915_ggtt_view view;
2196         struct i915_vma *vma;
2197         u32 alignment;
2198
2199         WARN_ON(!mutex_is_locked(&dev->struct_mutex));
2200
2201         alignment = intel_surf_alignment(dev_priv, fb->modifier[0]);
2202
2203         intel_fill_fb_ggtt_view(&view, fb, rotation);
2204
2205         /* Note that the w/a also requires 64 PTE of padding following the
2206          * bo. We currently fill all unused PTE with the shadow page and so
2207          * we should always have valid PTE following the scanout preventing
2208          * the VT-d warning.
2209          */
2210         if (intel_scanout_needs_vtd_wa(dev_priv) && alignment < 256 * 1024)
2211                 alignment = 256 * 1024;
2212
2213         /*
2214          * Global gtt pte registers are special registers which actually forward
2215          * writes to a chunk of system memory. Which means that there is no risk
2216          * that the register values disappear as soon as we call
2217          * intel_runtime_pm_put(), so it is correct to wrap only the
2218          * pin/unpin/fence and not more.
2219          */
2220         intel_runtime_pm_get(dev_priv);
2221
2222         vma = i915_gem_object_pin_to_display_plane(obj, alignment, &view);
2223         if (IS_ERR(vma))
2224                 goto err;
2225
2226         if (i915_vma_is_map_and_fenceable(vma)) {
2227                 /* Install a fence for tiled scan-out. Pre-i965 always needs a
2228                  * fence, whereas 965+ only requires a fence if using
2229                  * framebuffer compression.  For simplicity, we always, when
2230                  * possible, install a fence as the cost is not that onerous.
2231                  *
2232                  * If we fail to fence the tiled scanout, then either the
2233                  * modeset will reject the change (which is highly unlikely as
2234                  * the affected systems, all but one, do not have unmappable
2235                  * space) or we will not be able to enable full powersaving
2236                  * techniques (also likely not to apply due to various limits
2237                  * FBC and the like impose on the size of the buffer, which
2238                  * presumably we violated anyway with this unmappable buffer).
2239                  * Anyway, it is presumably better to stumble onwards with
2240                  * something and try to run the system in a "less than optimal"
2241                  * mode that matches the user configuration.
2242                  */
2243                 if (i915_vma_get_fence(vma) == 0)
2244                         i915_vma_pin_fence(vma);
2245         }
2246
2247 err:
2248         intel_runtime_pm_put(dev_priv);
2249         return vma;
2250 }
2251
2252 void intel_unpin_fb_obj(struct drm_framebuffer *fb, unsigned int rotation)
2253 {
2254         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
2255         struct i915_ggtt_view view;
2256         struct i915_vma *vma;
2257
2258         WARN_ON(!mutex_is_locked(&obj->base.dev->struct_mutex));
2259
2260         intel_fill_fb_ggtt_view(&view, fb, rotation);
2261         vma = i915_gem_object_to_ggtt(obj, &view);
2262
2263         i915_vma_unpin_fence(vma);
2264         i915_gem_object_unpin_from_display_plane(vma);
2265 }
2266
2267 static int intel_fb_pitch(const struct drm_framebuffer *fb, int plane,
2268                           unsigned int rotation)
2269 {
2270         if (drm_rotation_90_or_270(rotation))
2271                 return to_intel_framebuffer(fb)->rotated[plane].pitch;
2272         else
2273                 return fb->pitches[plane];
2274 }
2275
2276 /*
2277  * Convert the x/y offsets into a linear offset.
2278  * Only valid with 0/180 degree rotation, which is fine since linear
2279  * offset is only used with linear buffers on pre-hsw and tiled buffers
2280  * with gen2/3, and 90/270 degree rotations isn't supported on any of them.
2281  */
2282 u32 intel_fb_xy_to_linear(int x, int y,
2283                           const struct intel_plane_state *state,
2284                           int plane)
2285 {
2286         const struct drm_framebuffer *fb = state->base.fb;
2287         unsigned int cpp = drm_format_plane_cpp(fb->pixel_format, plane);
2288         unsigned int pitch = fb->pitches[plane];
2289
2290         return y * pitch + x * cpp;
2291 }
2292
2293 /*
2294  * Add the x/y offsets derived from fb->offsets[] to the user
2295  * specified plane src x/y offsets. The resulting x/y offsets
2296  * specify the start of scanout from the beginning of the gtt mapping.
2297  */
2298 void intel_add_fb_offsets(int *x, int *y,
2299                           const struct intel_plane_state *state,
2300                           int plane)
2301
2302 {
2303         const struct intel_framebuffer *intel_fb = to_intel_framebuffer(state->base.fb);
2304         unsigned int rotation = state->base.rotation;
2305
2306         if (drm_rotation_90_or_270(rotation)) {
2307                 *x += intel_fb->rotated[plane].x;
2308                 *y += intel_fb->rotated[plane].y;
2309         } else {
2310                 *x += intel_fb->normal[plane].x;
2311                 *y += intel_fb->normal[plane].y;
2312         }
2313 }
2314
2315 /*
2316  * Input tile dimensions and pitch must already be
2317  * rotated to match x and y, and in pixel units.
2318  */
2319 static u32 _intel_adjust_tile_offset(int *x, int *y,
2320                                      unsigned int tile_width,
2321                                      unsigned int tile_height,
2322                                      unsigned int tile_size,
2323                                      unsigned int pitch_tiles,
2324                                      u32 old_offset,
2325                                      u32 new_offset)
2326 {
2327         unsigned int pitch_pixels = pitch_tiles * tile_width;
2328         unsigned int tiles;
2329
2330         WARN_ON(old_offset & (tile_size - 1));
2331         WARN_ON(new_offset & (tile_size - 1));
2332         WARN_ON(new_offset > old_offset);
2333
2334         tiles = (old_offset - new_offset) / tile_size;
2335
2336         *y += tiles / pitch_tiles * tile_height;
2337         *x += tiles % pitch_tiles * tile_width;
2338
2339         /* minimize x in case it got needlessly big */
2340         *y += *x / pitch_pixels * tile_height;
2341         *x %= pitch_pixels;
2342
2343         return new_offset;
2344 }
2345
2346 /*
2347  * Adjust the tile offset by moving the difference into
2348  * the x/y offsets.
2349  */
2350 static u32 intel_adjust_tile_offset(int *x, int *y,
2351                                     const struct intel_plane_state *state, int plane,
2352                                     u32 old_offset, u32 new_offset)
2353 {
2354         const struct drm_i915_private *dev_priv = to_i915(state->base.plane->dev);
2355         const struct drm_framebuffer *fb = state->base.fb;
2356         unsigned int cpp = drm_format_plane_cpp(fb->pixel_format, plane);
2357         unsigned int rotation = state->base.rotation;
2358         unsigned int pitch = intel_fb_pitch(fb, plane, rotation);
2359
2360         WARN_ON(new_offset > old_offset);
2361
2362         if (fb->modifier[plane] != DRM_FORMAT_MOD_NONE) {
2363                 unsigned int tile_size, tile_width, tile_height;
2364                 unsigned int pitch_tiles;
2365
2366                 tile_size = intel_tile_size(dev_priv);
2367                 intel_tile_dims(dev_priv, &tile_width, &tile_height,
2368                                 fb->modifier[plane], cpp);
2369
2370                 if (drm_rotation_90_or_270(rotation)) {
2371                         pitch_tiles = pitch / tile_height;
2372                         swap(tile_width, tile_height);
2373                 } else {
2374                         pitch_tiles = pitch / (tile_width * cpp);
2375                 }
2376
2377                 _intel_adjust_tile_offset(x, y, tile_width, tile_height,
2378                                           tile_size, pitch_tiles,
2379                                           old_offset, new_offset);
2380         } else {
2381                 old_offset += *y * pitch + *x * cpp;
2382
2383                 *y = (old_offset - new_offset) / pitch;
2384                 *x = ((old_offset - new_offset) - *y * pitch) / cpp;
2385         }
2386
2387         return new_offset;
2388 }
2389
2390 /*
2391  * Computes the linear offset to the base tile and adjusts
2392  * x, y. bytes per pixel is assumed to be a power-of-two.
2393  *
2394  * In the 90/270 rotated case, x and y are assumed
2395  * to be already rotated to match the rotated GTT view, and
2396  * pitch is the tile_height aligned framebuffer height.
2397  *
2398  * This function is used when computing the derived information
2399  * under intel_framebuffer, so using any of that information
2400  * here is not allowed. Anything under drm_framebuffer can be
2401  * used. This is why the user has to pass in the pitch since it
2402  * is specified in the rotated orientation.
2403  */
2404 static u32 _intel_compute_tile_offset(const struct drm_i915_private *dev_priv,
2405                                       int *x, int *y,
2406                                       const struct drm_framebuffer *fb, int plane,
2407                                       unsigned int pitch,
2408                                       unsigned int rotation,
2409                                       u32 alignment)
2410 {
2411         uint64_t fb_modifier = fb->modifier[plane];
2412         unsigned int cpp = drm_format_plane_cpp(fb->pixel_format, plane);
2413         u32 offset, offset_aligned;
2414
2415         if (alignment)
2416                 alignment--;
2417
2418         if (fb_modifier != DRM_FORMAT_MOD_NONE) {
2419                 unsigned int tile_size, tile_width, tile_height;
2420                 unsigned int tile_rows, tiles, pitch_tiles;
2421
2422                 tile_size = intel_tile_size(dev_priv);
2423                 intel_tile_dims(dev_priv, &tile_width, &tile_height,
2424                                 fb_modifier, cpp);
2425
2426                 if (drm_rotation_90_or_270(rotation)) {
2427                         pitch_tiles = pitch / tile_height;
2428                         swap(tile_width, tile_height);
2429                 } else {
2430                         pitch_tiles = pitch / (tile_width * cpp);
2431                 }
2432
2433                 tile_rows = *y / tile_height;
2434                 *y %= tile_height;
2435
2436                 tiles = *x / tile_width;
2437                 *x %= tile_width;
2438
2439                 offset = (tile_rows * pitch_tiles + tiles) * tile_size;
2440                 offset_aligned = offset & ~alignment;
2441
2442                 _intel_adjust_tile_offset(x, y, tile_width, tile_height,
2443                                           tile_size, pitch_tiles,
2444                                           offset, offset_aligned);
2445         } else {
2446                 offset = *y * pitch + *x * cpp;
2447                 offset_aligned = offset & ~alignment;
2448
2449                 *y = (offset & alignment) / pitch;
2450                 *x = ((offset & alignment) - *y * pitch) / cpp;
2451         }
2452
2453         return offset_aligned;
2454 }
2455
2456 u32 intel_compute_tile_offset(int *x, int *y,
2457                               const struct intel_plane_state *state,
2458                               int plane)
2459 {
2460         const struct drm_i915_private *dev_priv = to_i915(state->base.plane->dev);
2461         const struct drm_framebuffer *fb = state->base.fb;
2462         unsigned int rotation = state->base.rotation;
2463         int pitch = intel_fb_pitch(fb, plane, rotation);
2464         u32 alignment;
2465
2466         /* AUX_DIST needs only 4K alignment */
2467         if (fb->pixel_format == DRM_FORMAT_NV12 && plane == 1)
2468                 alignment = 4096;
2469         else
2470                 alignment = intel_surf_alignment(dev_priv, fb->modifier[plane]);
2471
2472         return _intel_compute_tile_offset(dev_priv, x, y, fb, plane, pitch,
2473                                           rotation, alignment);
2474 }
2475
2476 /* Convert the fb->offset[] linear offset into x/y offsets */
2477 static void intel_fb_offset_to_xy(int *x, int *y,
2478                                   const struct drm_framebuffer *fb, int plane)
2479 {
2480         unsigned int cpp = drm_format_plane_cpp(fb->pixel_format, plane);
2481         unsigned int pitch = fb->pitches[plane];
2482         u32 linear_offset = fb->offsets[plane];
2483
2484         *y = linear_offset / pitch;
2485         *x = linear_offset % pitch / cpp;
2486 }
2487
2488 static unsigned int intel_fb_modifier_to_tiling(uint64_t fb_modifier)
2489 {
2490         switch (fb_modifier) {
2491         case I915_FORMAT_MOD_X_TILED:
2492                 return I915_TILING_X;
2493         case I915_FORMAT_MOD_Y_TILED:
2494                 return I915_TILING_Y;
2495         default:
2496                 return I915_TILING_NONE;
2497         }
2498 }
2499
2500 static int
2501 intel_fill_fb_info(struct drm_i915_private *dev_priv,
2502                    struct drm_framebuffer *fb)
2503 {
2504         struct intel_framebuffer *intel_fb = to_intel_framebuffer(fb);
2505         struct intel_rotation_info *rot_info = &intel_fb->rot_info;
2506         u32 gtt_offset_rotated = 0;
2507         unsigned int max_size = 0;
2508         uint32_t format = fb->pixel_format;
2509         int i, num_planes = drm_format_num_planes(format);
2510         unsigned int tile_size = intel_tile_size(dev_priv);
2511
2512         for (i = 0; i < num_planes; i++) {
2513                 unsigned int width, height;
2514                 unsigned int cpp, size;
2515                 u32 offset;
2516                 int x, y;
2517
2518                 cpp = drm_format_plane_cpp(format, i);
2519                 width = drm_format_plane_width(fb->width, format, i);
2520                 height = drm_format_plane_height(fb->height, format, i);
2521
2522                 intel_fb_offset_to_xy(&x, &y, fb, i);
2523
2524                 /*
2525                  * The fence (if used) is aligned to the start of the object
2526                  * so having the framebuffer wrap around across the edge of the
2527                  * fenced region doesn't really work. We have no API to configure
2528                  * the fence start offset within the object (nor could we probably
2529                  * on gen2/3). So it's just easier if we just require that the
2530                  * fb layout agrees with the fence layout. We already check that the
2531                  * fb stride matches the fence stride elsewhere.
2532                  */
2533                 if (i915_gem_object_is_tiled(intel_fb->obj) &&
2534                     (x + width) * cpp > fb->pitches[i]) {
2535                         DRM_DEBUG("bad fb plane %d offset: 0x%x\n",
2536                                   i, fb->offsets[i]);
2537                         return -EINVAL;
2538                 }
2539
2540                 /*
2541                  * First pixel of the framebuffer from
2542                  * the start of the normal gtt mapping.
2543                  */
2544                 intel_fb->normal[i].x = x;
2545                 intel_fb->normal[i].y = y;
2546
2547                 offset = _intel_compute_tile_offset(dev_priv, &x, &y,
2548                                                     fb, 0, fb->pitches[i],
2549                                                     DRM_ROTATE_0, tile_size);
2550                 offset /= tile_size;
2551
2552                 if (fb->modifier[i] != DRM_FORMAT_MOD_NONE) {
2553                         unsigned int tile_width, tile_height;
2554                         unsigned int pitch_tiles;
2555                         struct drm_rect r;
2556
2557                         intel_tile_dims(dev_priv, &tile_width, &tile_height,
2558                                         fb->modifier[i], cpp);
2559
2560                         rot_info->plane[i].offset = offset;
2561                         rot_info->plane[i].stride = DIV_ROUND_UP(fb->pitches[i], tile_width * cpp);
2562                         rot_info->plane[i].width = DIV_ROUND_UP(x + width, tile_width);
2563                         rot_info->plane[i].height = DIV_ROUND_UP(y + height, tile_height);
2564
2565                         intel_fb->rotated[i].pitch =
2566                                 rot_info->plane[i].height * tile_height;
2567
2568                         /* how many tiles does this plane need */
2569                         size = rot_info->plane[i].stride * rot_info->plane[i].height;
2570                         /*
2571                          * If the plane isn't horizontally tile aligned,
2572                          * we need one more tile.
2573                          */
2574                         if (x != 0)
2575                                 size++;
2576
2577                         /* rotate the x/y offsets to match the GTT view */
2578                         r.x1 = x;
2579                         r.y1 = y;
2580                         r.x2 = x + width;
2581                         r.y2 = y + height;
2582                         drm_rect_rotate(&r,
2583                                         rot_info->plane[i].width * tile_width,
2584                                         rot_info->plane[i].height * tile_height,
2585                                         DRM_ROTATE_270);
2586                         x = r.x1;
2587                         y = r.y1;
2588
2589                         /* rotate the tile dimensions to match the GTT view */
2590                         pitch_tiles = intel_fb->rotated[i].pitch / tile_height;
2591                         swap(tile_width, tile_height);
2592
2593                         /*
2594                          * We only keep the x/y offsets, so push all of the
2595                          * gtt offset into the x/y offsets.
2596                          */
2597                         _intel_adjust_tile_offset(&x, &y, tile_size,
2598                                                   tile_width, tile_height, pitch_tiles,
2599                                                   gtt_offset_rotated * tile_size, 0);
2600
2601                         gtt_offset_rotated += rot_info->plane[i].width * rot_info->plane[i].height;
2602
2603                         /*
2604                          * First pixel of the framebuffer from
2605                          * the start of the rotated gtt mapping.
2606                          */
2607                         intel_fb->rotated[i].x = x;
2608                         intel_fb->rotated[i].y = y;
2609                 } else {
2610                         size = DIV_ROUND_UP((y + height) * fb->pitches[i] +
2611                                             x * cpp, tile_size);
2612                 }
2613
2614                 /* how many tiles in total needed in the bo */
2615                 max_size = max(max_size, offset + size);
2616         }
2617
2618         if (max_size * tile_size > to_intel_framebuffer(fb)->obj->base.size) {
2619                 DRM_DEBUG("fb too big for bo (need %u bytes, have %zu bytes)\n",
2620                           max_size * tile_size, to_intel_framebuffer(fb)->obj->base.size);
2621                 return -EINVAL;
2622         }
2623
2624         return 0;
2625 }
2626
2627 static int i9xx_format_to_fourcc(int format)
2628 {
2629         switch (format) {
2630         case DISPPLANE_8BPP:
2631                 return DRM_FORMAT_C8;
2632         case DISPPLANE_BGRX555:
2633                 return DRM_FORMAT_XRGB1555;
2634         case DISPPLANE_BGRX565:
2635                 return DRM_FORMAT_RGB565;
2636         default:
2637         case DISPPLANE_BGRX888:
2638                 return DRM_FORMAT_XRGB8888;
2639         case DISPPLANE_RGBX888:
2640                 return DRM_FORMAT_XBGR8888;
2641         case DISPPLANE_BGRX101010:
2642                 return DRM_FORMAT_XRGB2101010;
2643         case DISPPLANE_RGBX101010:
2644                 return DRM_FORMAT_XBGR2101010;
2645         }
2646 }
2647
2648 static int skl_format_to_fourcc(int format, bool rgb_order, bool alpha)
2649 {
2650         switch (format) {
2651         case PLANE_CTL_FORMAT_RGB_565:
2652                 return DRM_FORMAT_RGB565;
2653         default:
2654         case PLANE_CTL_FORMAT_XRGB_8888:
2655                 if (rgb_order) {
2656                         if (alpha)
2657                                 return DRM_FORMAT_ABGR8888;
2658                         else
2659                                 return DRM_FORMAT_XBGR8888;
2660                 } else {
2661                         if (alpha)
2662                                 return DRM_FORMAT_ARGB8888;
2663                         else
2664                                 return DRM_FORMAT_XRGB8888;
2665                 }
2666         case PLANE_CTL_FORMAT_XRGB_2101010:
2667                 if (rgb_order)
2668                         return DRM_FORMAT_XBGR2101010;
2669                 else
2670                         return DRM_FORMAT_XRGB2101010;
2671         }
2672 }
2673
2674 static bool
2675 intel_alloc_initial_plane_obj(struct intel_crtc *crtc,
2676                               struct intel_initial_plane_config *plane_config)
2677 {
2678         struct drm_device *dev = crtc->base.dev;
2679         struct drm_i915_private *dev_priv = to_i915(dev);
2680         struct i915_ggtt *ggtt = &dev_priv->ggtt;
2681         struct drm_i915_gem_object *obj = NULL;
2682         struct drm_mode_fb_cmd2 mode_cmd = { 0 };
2683         struct drm_framebuffer *fb = &plane_config->fb->base;
2684         u32 base_aligned = round_down(plane_config->base, PAGE_SIZE);
2685         u32 size_aligned = round_up(plane_config->base + plane_config->size,
2686                                     PAGE_SIZE);
2687
2688         size_aligned -= base_aligned;
2689
2690         if (plane_config->size == 0)
2691                 return false;
2692
2693         /* If the FB is too big, just don't use it since fbdev is not very
2694          * important and we should probably use that space with FBC or other
2695          * features. */
2696         if (size_aligned * 2 > ggtt->stolen_usable_size)
2697                 return false;
2698
2699         mutex_lock(&dev->struct_mutex);
2700
2701         obj = i915_gem_object_create_stolen_for_preallocated(dev,
2702                                                              base_aligned,
2703                                                              base_aligned,
2704                                                              size_aligned);
2705         if (!obj) {
2706                 mutex_unlock(&dev->struct_mutex);
2707                 return false;
2708         }
2709
2710         if (plane_config->tiling == I915_TILING_X)
2711                 obj->tiling_and_stride = fb->pitches[0] | I915_TILING_X;
2712
2713         mode_cmd.pixel_format = fb->pixel_format;
2714         mode_cmd.width = fb->width;
2715         mode_cmd.height = fb->height;
2716         mode_cmd.pitches[0] = fb->pitches[0];
2717         mode_cmd.modifier[0] = fb->modifier[0];
2718         mode_cmd.flags = DRM_MODE_FB_MODIFIERS;
2719
2720         if (intel_framebuffer_init(dev, to_intel_framebuffer(fb),
2721                                    &mode_cmd, obj)) {
2722                 DRM_DEBUG_KMS("intel fb init failed\n");
2723                 goto out_unref_obj;
2724         }
2725
2726         mutex_unlock(&dev->struct_mutex);
2727
2728         DRM_DEBUG_KMS("initial plane fb obj %p\n", obj);
2729         return true;
2730
2731 out_unref_obj:
2732         i915_gem_object_put(obj);
2733         mutex_unlock(&dev->struct_mutex);
2734         return false;
2735 }
2736
2737 /* Update plane->state->fb to match plane->fb after driver-internal updates */
2738 static void
2739 update_state_fb(struct drm_plane *plane)
2740 {
2741         if (plane->fb == plane->state->fb)
2742                 return;
2743
2744         if (plane->state->fb)
2745                 drm_framebuffer_unreference(plane->state->fb);
2746         plane->state->fb = plane->fb;
2747         if (plane->state->fb)
2748                 drm_framebuffer_reference(plane->state->fb);
2749 }
2750
2751 static void
2752 intel_find_initial_plane_obj(struct intel_crtc *intel_crtc,
2753                              struct intel_initial_plane_config *plane_config)
2754 {
2755         struct drm_device *dev = intel_crtc->base.dev;
2756         struct drm_i915_private *dev_priv = to_i915(dev);
2757         struct drm_crtc *c;
2758         struct intel_crtc *i;
2759         struct drm_i915_gem_object *obj;
2760         struct drm_plane *primary = intel_crtc->base.primary;
2761         struct drm_plane_state *plane_state = primary->state;
2762         struct drm_crtc_state *crtc_state = intel_crtc->base.state;
2763         struct intel_plane *intel_plane = to_intel_plane(primary);
2764         struct intel_plane_state *intel_state =
2765                 to_intel_plane_state(plane_state);
2766         struct drm_framebuffer *fb;
2767
2768         if (!plane_config->fb)
2769                 return;
2770
2771         if (intel_alloc_initial_plane_obj(intel_crtc, plane_config)) {
2772                 fb = &plane_config->fb->base;
2773                 goto valid_fb;
2774         }
2775
2776         kfree(plane_config->fb);
2777
2778         /*
2779          * Failed to alloc the obj, check to see if we should share
2780          * an fb with another CRTC instead
2781          */
2782         for_each_crtc(dev, c) {
2783                 i = to_intel_crtc(c);
2784
2785                 if (c == &intel_crtc->base)
2786                         continue;
2787
2788                 if (!i->active)
2789                         continue;
2790
2791                 fb = c->primary->fb;
2792                 if (!fb)
2793                         continue;
2794
2795                 obj = intel_fb_obj(fb);
2796                 if (i915_gem_object_ggtt_offset(obj, NULL) == plane_config->base) {
2797                         drm_framebuffer_reference(fb);
2798                         goto valid_fb;
2799                 }
2800         }
2801
2802         /*
2803          * We've failed to reconstruct the BIOS FB.  Current display state
2804          * indicates that the primary plane is visible, but has a NULL FB,
2805          * which will lead to problems later if we don't fix it up.  The
2806          * simplest solution is to just disable the primary plane now and
2807          * pretend the BIOS never had it enabled.
2808          */
2809         to_intel_plane_state(plane_state)->base.visible = false;
2810         crtc_state->plane_mask &= ~(1 << drm_plane_index(primary));
2811         intel_pre_disable_primary_noatomic(&intel_crtc->base);
2812         intel_plane->disable_plane(primary, &intel_crtc->base);
2813
2814         return;
2815
2816 valid_fb:
2817         plane_state->src_x = 0;
2818         plane_state->src_y = 0;
2819         plane_state->src_w = fb->width << 16;
2820         plane_state->src_h = fb->height << 16;
2821
2822         plane_state->crtc_x = 0;
2823         plane_state->crtc_y = 0;
2824         plane_state->crtc_w = fb->width;
2825         plane_state->crtc_h = fb->height;
2826
2827         intel_state->base.src.x1 = plane_state->src_x;
2828         intel_state->base.src.y1 = plane_state->src_y;
2829         intel_state->base.src.x2 = plane_state->src_x + plane_state->src_w;
2830         intel_state->base.src.y2 = plane_state->src_y + plane_state->src_h;
2831         intel_state->base.dst.x1 = plane_state->crtc_x;
2832         intel_state->base.dst.y1 = plane_state->crtc_y;
2833         intel_state->base.dst.x2 = plane_state->crtc_x + plane_state->crtc_w;
2834         intel_state->base.dst.y2 = plane_state->crtc_y + plane_state->crtc_h;
2835
2836         obj = intel_fb_obj(fb);
2837         if (i915_gem_object_is_tiled(obj))
2838                 dev_priv->preserve_bios_swizzle = true;
2839
2840         drm_framebuffer_reference(fb);
2841         primary->fb = primary->state->fb = fb;
2842         primary->crtc = primary->state->crtc = &intel_crtc->base;
2843         intel_crtc->base.state->plane_mask |= (1 << drm_plane_index(primary));
2844         atomic_or(to_intel_plane(primary)->frontbuffer_bit,
2845                   &obj->frontbuffer_bits);
2846 }
2847
2848 static int skl_max_plane_width(const struct drm_framebuffer *fb, int plane,
2849                                unsigned int rotation)
2850 {
2851         int cpp = drm_format_plane_cpp(fb->pixel_format, plane);
2852
2853         switch (fb->modifier[plane]) {
2854         case DRM_FORMAT_MOD_NONE:
2855         case I915_FORMAT_MOD_X_TILED:
2856                 switch (cpp) {
2857                 case 8:
2858                         return 4096;
2859                 case 4:
2860                 case 2:
2861                 case 1:
2862                         return 8192;
2863                 default:
2864                         MISSING_CASE(cpp);
2865                         break;
2866                 }
2867                 break;
2868         case I915_FORMAT_MOD_Y_TILED:
2869         case I915_FORMAT_MOD_Yf_TILED:
2870                 switch (cpp) {
2871                 case 8:
2872                         return 2048;
2873                 case 4:
2874                         return 4096;
2875                 case 2:
2876                 case 1:
2877                         return 8192;
2878                 default:
2879                         MISSING_CASE(cpp);
2880                         break;
2881                 }
2882                 break;
2883         default:
2884                 MISSING_CASE(fb->modifier[plane]);
2885         }
2886
2887         return 2048;
2888 }
2889
2890 static int skl_check_main_surface(struct intel_plane_state *plane_state)
2891 {
2892         const struct drm_i915_private *dev_priv = to_i915(plane_state->base.plane->dev);
2893         const struct drm_framebuffer *fb = plane_state->base.fb;
2894         unsigned int rotation = plane_state->base.rotation;
2895         int x = plane_state->base.src.x1 >> 16;
2896         int y = plane_state->base.src.y1 >> 16;
2897         int w = drm_rect_width(&plane_state->base.src) >> 16;
2898         int h = drm_rect_height(&plane_state->base.src) >> 16;
2899         int max_width = skl_max_plane_width(fb, 0, rotation);
2900         int max_height = 4096;
2901         u32 alignment, offset, aux_offset = plane_state->aux.offset;
2902
2903         if (w > max_width || h > max_height) {
2904                 DRM_DEBUG_KMS("requested Y/RGB source size %dx%d too big (limit %dx%d)\n",
2905                               w, h, max_width, max_height);
2906                 return -EINVAL;
2907         }
2908
2909         intel_add_fb_offsets(&x, &y, plane_state, 0);
2910         offset = intel_compute_tile_offset(&x, &y, plane_state, 0);
2911
2912         alignment = intel_surf_alignment(dev_priv, fb->modifier[0]);
2913
2914         /*
2915          * AUX surface offset is specified as the distance from the
2916          * main surface offset, and it must be non-negative. Make
2917          * sure that is what we will get.
2918          */
2919         if (offset > aux_offset)
2920                 offset = intel_adjust_tile_offset(&x, &y, plane_state, 0,
2921                                                   offset, aux_offset & ~(alignment - 1));
2922
2923         /*
2924          * When using an X-tiled surface, the plane blows up
2925          * if the x offset + width exceed the stride.
2926          *
2927          * TODO: linear and Y-tiled seem fine, Yf untested,
2928          */
2929         if (fb->modifier[0] == I915_FORMAT_MOD_X_TILED) {
2930                 int cpp = drm_format_plane_cpp(fb->pixel_format, 0);
2931
2932                 while ((x + w) * cpp > fb->pitches[0]) {
2933                         if (offset == 0) {
2934                                 DRM_DEBUG_KMS("Unable to find suitable display surface offset\n");
2935                                 return -EINVAL;
2936                         }
2937
2938                         offset = intel_adjust_tile_offset(&x, &y, plane_state, 0,
2939                                                           offset, offset - alignment);
2940                 }
2941         }
2942
2943         plane_state->main.offset = offset;
2944         plane_state->main.x = x;
2945         plane_state->main.y = y;
2946
2947         return 0;
2948 }
2949
2950 static int skl_check_nv12_aux_surface(struct intel_plane_state *plane_state)
2951 {
2952         const struct drm_framebuffer *fb = plane_state->base.fb;
2953         unsigned int rotation = plane_state->base.rotation;
2954         int max_width = skl_max_plane_width(fb, 1, rotation);
2955         int max_height = 4096;
2956         int x = plane_state->base.src.x1 >> 17;
2957         int y = plane_state->base.src.y1 >> 17;
2958         int w = drm_rect_width(&plane_state->base.src) >> 17;
2959         int h = drm_rect_height(&plane_state->base.src) >> 17;
2960         u32 offset;
2961
2962         intel_add_fb_offsets(&x, &y, plane_state, 1);
2963         offset = intel_compute_tile_offset(&x, &y, plane_state, 1);
2964
2965         /* FIXME not quite sure how/if these apply to the chroma plane */
2966         if (w > max_width || h > max_height) {
2967                 DRM_DEBUG_KMS("CbCr source size %dx%d too big (limit %dx%d)\n",
2968                               w, h, max_width, max_height);
2969                 return -EINVAL;
2970         }
2971
2972         plane_state->aux.offset = offset;
2973         plane_state->aux.x = x;
2974         plane_state->aux.y = y;
2975
2976         return 0;
2977 }
2978
2979 int skl_check_plane_surface(struct intel_plane_state *plane_state)
2980 {
2981         const struct drm_framebuffer *fb = plane_state->base.fb;
2982         unsigned int rotation = plane_state->base.rotation;
2983         int ret;
2984
2985         /* Rotate src coordinates to match rotated GTT view */
2986         if (drm_rotation_90_or_270(rotation))
2987                 drm_rect_rotate(&plane_state->base.src,
2988                                 fb->width, fb->height, DRM_ROTATE_270);
2989
2990         /*
2991          * Handle the AUX surface first since
2992          * the main surface setup depends on it.
2993          */
2994         if (fb->pixel_format == DRM_FORMAT_NV12) {
2995                 ret = skl_check_nv12_aux_surface(plane_state);
2996                 if (ret)
2997                         return ret;
2998         } else {
2999                 plane_state->aux.offset = ~0xfff;
3000                 plane_state->aux.x = 0;
3001                 plane_state->aux.y = 0;
3002         }
3003
3004         ret = skl_check_main_surface(plane_state);
3005         if (ret)
3006                 return ret;
3007
3008         return 0;
3009 }
3010
3011 static void i9xx_update_primary_plane(struct drm_plane *primary,
3012                                       const struct intel_crtc_state *crtc_state,
3013                                       const struct intel_plane_state *plane_state)
3014 {
3015         struct drm_device *dev = primary->dev;
3016         struct drm_i915_private *dev_priv = to_i915(dev);
3017         struct intel_crtc *intel_crtc = to_intel_crtc(crtc_state->base.crtc);
3018         struct drm_framebuffer *fb = plane_state->base.fb;
3019         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
3020         int plane = intel_crtc->plane;
3021         u32 linear_offset;
3022         u32 dspcntr;
3023         i915_reg_t reg = DSPCNTR(plane);
3024         unsigned int rotation = plane_state->base.rotation;
3025         int x = plane_state->base.src.x1 >> 16;
3026         int y = plane_state->base.src.y1 >> 16;
3027
3028         dspcntr = DISPPLANE_GAMMA_ENABLE;
3029
3030         dspcntr |= DISPLAY_PLANE_ENABLE;
3031
3032         if (INTEL_INFO(dev)->gen < 4) {
3033                 if (intel_crtc->pipe == PIPE_B)
3034                         dspcntr |= DISPPLANE_SEL_PIPE_B;
3035
3036                 /* pipesrc and dspsize control the size that is scaled from,
3037                  * which should always be the user's requested size.
3038                  */
3039                 I915_WRITE(DSPSIZE(plane),
3040                            ((crtc_state->pipe_src_h - 1) << 16) |
3041                            (crtc_state->pipe_src_w - 1));
3042                 I915_WRITE(DSPPOS(plane), 0);
3043         } else if (IS_CHERRYVIEW(dev_priv) && plane == PLANE_B) {
3044                 I915_WRITE(PRIMSIZE(plane),
3045                            ((crtc_state->pipe_src_h - 1) << 16) |
3046                            (crtc_state->pipe_src_w - 1));
3047                 I915_WRITE(PRIMPOS(plane), 0);
3048                 I915_WRITE(PRIMCNSTALPHA(plane), 0);
3049         }
3050
3051         switch (fb->pixel_format) {
3052         case DRM_FORMAT_C8:
3053                 dspcntr |= DISPPLANE_8BPP;
3054                 break;
3055         case DRM_FORMAT_XRGB1555:
3056                 dspcntr |= DISPPLANE_BGRX555;
3057                 break;
3058         case DRM_FORMAT_RGB565:
3059                 dspcntr |= DISPPLANE_BGRX565;
3060                 break;
3061         case DRM_FORMAT_XRGB8888:
3062                 dspcntr |= DISPPLANE_BGRX888;
3063                 break;
3064         case DRM_FORMAT_XBGR8888:
3065                 dspcntr |= DISPPLANE_RGBX888;
3066                 break;
3067         case DRM_FORMAT_XRGB2101010:
3068                 dspcntr |= DISPPLANE_BGRX101010;
3069                 break;
3070         case DRM_FORMAT_XBGR2101010:
3071                 dspcntr |= DISPPLANE_RGBX101010;
3072                 break;
3073         default:
3074                 BUG();
3075         }
3076
3077         if (INTEL_GEN(dev_priv) >= 4 &&
3078             fb->modifier[0] == I915_FORMAT_MOD_X_TILED)
3079                 dspcntr |= DISPPLANE_TILED;
3080
3081         if (IS_G4X(dev_priv))
3082                 dspcntr |= DISPPLANE_TRICKLE_FEED_DISABLE;
3083
3084         intel_add_fb_offsets(&x, &y, plane_state, 0);
3085
3086         if (INTEL_INFO(dev)->gen >= 4)
3087                 intel_crtc->dspaddr_offset =
3088                         intel_compute_tile_offset(&x, &y, plane_state, 0);
3089
3090         if (rotation == DRM_ROTATE_180) {
3091                 dspcntr |= DISPPLANE_ROTATE_180;
3092
3093                 x += (crtc_state->pipe_src_w - 1);
3094                 y += (crtc_state->pipe_src_h - 1);
3095         }
3096
3097         linear_offset = intel_fb_xy_to_linear(x, y, plane_state, 0);
3098
3099         if (INTEL_INFO(dev)->gen < 4)
3100                 intel_crtc->dspaddr_offset = linear_offset;
3101
3102         intel_crtc->adjusted_x = x;
3103         intel_crtc->adjusted_y = y;
3104
3105         I915_WRITE(reg, dspcntr);
3106
3107         I915_WRITE(DSPSTRIDE(plane), fb->pitches[0]);
3108         if (INTEL_INFO(dev)->gen >= 4) {
3109                 I915_WRITE(DSPSURF(plane),
3110                            intel_fb_gtt_offset(fb, rotation) +
3111                            intel_crtc->dspaddr_offset);
3112                 I915_WRITE(DSPTILEOFF(plane), (y << 16) | x);
3113                 I915_WRITE(DSPLINOFF(plane), linear_offset);
3114         } else
3115                 I915_WRITE(DSPADDR(plane), i915_gem_object_ggtt_offset(obj, NULL) + linear_offset);
3116         POSTING_READ(reg);
3117 }
3118
3119 static void i9xx_disable_primary_plane(struct drm_plane *primary,
3120                                        struct drm_crtc *crtc)
3121 {
3122         struct drm_device *dev = crtc->dev;
3123         struct drm_i915_private *dev_priv = to_i915(dev);
3124         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3125         int plane = intel_crtc->plane;
3126
3127         I915_WRITE(DSPCNTR(plane), 0);
3128         if (INTEL_INFO(dev_priv)->gen >= 4)
3129                 I915_WRITE(DSPSURF(plane), 0);
3130         else
3131                 I915_WRITE(DSPADDR(plane), 0);
3132         POSTING_READ(DSPCNTR(plane));
3133 }
3134
3135 static void ironlake_update_primary_plane(struct drm_plane *primary,
3136                                           const struct intel_crtc_state *crtc_state,
3137                                           const struct intel_plane_state *plane_state)
3138 {
3139         struct drm_device *dev = primary->dev;
3140         struct drm_i915_private *dev_priv = to_i915(dev);
3141         struct intel_crtc *intel_crtc = to_intel_crtc(crtc_state->base.crtc);
3142         struct drm_framebuffer *fb = plane_state->base.fb;
3143         int plane = intel_crtc->plane;
3144         u32 linear_offset;
3145         u32 dspcntr;
3146         i915_reg_t reg = DSPCNTR(plane);
3147         unsigned int rotation = plane_state->base.rotation;
3148         int x = plane_state->base.src.x1 >> 16;
3149         int y = plane_state->base.src.y1 >> 16;
3150
3151         dspcntr = DISPPLANE_GAMMA_ENABLE;
3152         dspcntr |= DISPLAY_PLANE_ENABLE;
3153
3154         if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv))
3155                 dspcntr |= DISPPLANE_PIPE_CSC_ENABLE;
3156
3157         switch (fb->pixel_format) {
3158         case DRM_FORMAT_C8:
3159                 dspcntr |= DISPPLANE_8BPP;
3160                 break;
3161         case DRM_FORMAT_RGB565:
3162                 dspcntr |= DISPPLANE_BGRX565;
3163                 break;
3164         case DRM_FORMAT_XRGB8888:
3165                 dspcntr |= DISPPLANE_BGRX888;
3166                 break;
3167         case DRM_FORMAT_XBGR8888:
3168                 dspcntr |= DISPPLANE_RGBX888;
3169                 break;
3170         case DRM_FORMAT_XRGB2101010:
3171                 dspcntr |= DISPPLANE_BGRX101010;
3172                 break;
3173         case DRM_FORMAT_XBGR2101010:
3174                 dspcntr |= DISPPLANE_RGBX101010;
3175                 break;
3176         default:
3177                 BUG();
3178         }
3179
3180         if (fb->modifier[0] == I915_FORMAT_MOD_X_TILED)
3181                 dspcntr |= DISPPLANE_TILED;
3182
3183         if (!IS_HASWELL(dev_priv) && !IS_BROADWELL(dev_priv))
3184                 dspcntr |= DISPPLANE_TRICKLE_FEED_DISABLE;
3185
3186         intel_add_fb_offsets(&x, &y, plane_state, 0);
3187
3188         intel_crtc->dspaddr_offset =
3189                 intel_compute_tile_offset(&x, &y, plane_state, 0);
3190
3191         if (rotation == DRM_ROTATE_180) {
3192                 dspcntr |= DISPPLANE_ROTATE_180;
3193
3194                 if (!IS_HASWELL(dev_priv) && !IS_BROADWELL(dev_priv)) {
3195                         x += (crtc_state->pipe_src_w - 1);
3196                         y += (crtc_state->pipe_src_h - 1);
3197                 }
3198         }
3199
3200         linear_offset = intel_fb_xy_to_linear(x, y, plane_state, 0);
3201
3202         intel_crtc->adjusted_x = x;
3203         intel_crtc->adjusted_y = y;
3204
3205         I915_WRITE(reg, dspcntr);
3206
3207         I915_WRITE(DSPSTRIDE(plane), fb->pitches[0]);
3208         I915_WRITE(DSPSURF(plane),
3209                    intel_fb_gtt_offset(fb, rotation) +
3210                    intel_crtc->dspaddr_offset);
3211         if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv)) {
3212                 I915_WRITE(DSPOFFSET(plane), (y << 16) | x);
3213         } else {
3214                 I915_WRITE(DSPTILEOFF(plane), (y << 16) | x);
3215                 I915_WRITE(DSPLINOFF(plane), linear_offset);
3216         }
3217         POSTING_READ(reg);
3218 }
3219
3220 u32 intel_fb_stride_alignment(const struct drm_i915_private *dev_priv,
3221                               uint64_t fb_modifier, uint32_t pixel_format)
3222 {
3223         if (fb_modifier == DRM_FORMAT_MOD_NONE) {
3224                 return 64;
3225         } else {
3226                 int cpp = drm_format_plane_cpp(pixel_format, 0);
3227
3228                 return intel_tile_width_bytes(dev_priv, fb_modifier, cpp);
3229         }
3230 }
3231
3232 u32 intel_fb_gtt_offset(struct drm_framebuffer *fb,
3233                         unsigned int rotation)
3234 {
3235         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
3236         struct i915_ggtt_view view;
3237         struct i915_vma *vma;
3238
3239         intel_fill_fb_ggtt_view(&view, fb, rotation);
3240
3241         vma = i915_gem_object_to_ggtt(obj, &view);
3242         if (WARN(!vma, "ggtt vma for display object not found! (view=%u)\n",
3243                  view.type))
3244                 return -1;
3245
3246         return i915_ggtt_offset(vma);
3247 }
3248
3249 static void skl_detach_scaler(struct intel_crtc *intel_crtc, int id)
3250 {
3251         struct drm_device *dev = intel_crtc->base.dev;
3252         struct drm_i915_private *dev_priv = to_i915(dev);
3253
3254         I915_WRITE(SKL_PS_CTRL(intel_crtc->pipe, id), 0);
3255         I915_WRITE(SKL_PS_WIN_POS(intel_crtc->pipe, id), 0);
3256         I915_WRITE(SKL_PS_WIN_SZ(intel_crtc->pipe, id), 0);
3257 }
3258
3259 /*
3260  * This function detaches (aka. unbinds) unused scalers in hardware
3261  */
3262 static void skl_detach_scalers(struct intel_crtc *intel_crtc)
3263 {
3264         struct intel_crtc_scaler_state *scaler_state;
3265         int i;
3266
3267         scaler_state = &intel_crtc->config->scaler_state;
3268
3269         /* loop through and disable scalers that aren't in use */
3270         for (i = 0; i < intel_crtc->num_scalers; i++) {
3271                 if (!scaler_state->scalers[i].in_use)
3272                         skl_detach_scaler(intel_crtc, i);
3273         }
3274 }
3275
3276 u32 skl_plane_stride(const struct drm_framebuffer *fb, int plane,
3277                      unsigned int rotation)
3278 {
3279         const struct drm_i915_private *dev_priv = to_i915(fb->dev);
3280         u32 stride = intel_fb_pitch(fb, plane, rotation);
3281
3282         /*
3283          * The stride is either expressed as a multiple of 64 bytes chunks for
3284          * linear buffers or in number of tiles for tiled buffers.
3285          */
3286         if (drm_rotation_90_or_270(rotation)) {
3287                 int cpp = drm_format_plane_cpp(fb->pixel_format, plane);
3288
3289                 stride /= intel_tile_height(dev_priv, fb->modifier[0], cpp);
3290         } else {
3291                 stride /= intel_fb_stride_alignment(dev_priv, fb->modifier[0],
3292                                                     fb->pixel_format);
3293         }
3294
3295         return stride;
3296 }
3297
3298 u32 skl_plane_ctl_format(uint32_t pixel_format)
3299 {
3300         switch (pixel_format) {
3301         case DRM_FORMAT_C8:
3302                 return PLANE_CTL_FORMAT_INDEXED;
3303         case DRM_FORMAT_RGB565:
3304                 return PLANE_CTL_FORMAT_RGB_565;
3305         case DRM_FORMAT_XBGR8888:
3306                 return PLANE_CTL_FORMAT_XRGB_8888 | PLANE_CTL_ORDER_RGBX;
3307         case DRM_FORMAT_XRGB8888:
3308                 return PLANE_CTL_FORMAT_XRGB_8888;
3309         /*
3310          * XXX: For ARBG/ABGR formats we default to expecting scanout buffers
3311          * to be already pre-multiplied. We need to add a knob (or a different
3312          * DRM_FORMAT) for user-space to configure that.
3313          */
3314         case DRM_FORMAT_ABGR8888:
3315                 return PLANE_CTL_FORMAT_XRGB_8888 | PLANE_CTL_ORDER_RGBX |
3316                         PLANE_CTL_ALPHA_SW_PREMULTIPLY;
3317         case DRM_FORMAT_ARGB8888:
3318                 return PLANE_CTL_FORMAT_XRGB_8888 |
3319                         PLANE_CTL_ALPHA_SW_PREMULTIPLY;
3320         case DRM_FORMAT_XRGB2101010:
3321                 return PLANE_CTL_FORMAT_XRGB_2101010;
3322         case DRM_FORMAT_XBGR2101010:
3323                 return PLANE_CTL_ORDER_RGBX | PLANE_CTL_FORMAT_XRGB_2101010;
3324         case DRM_FORMAT_YUYV:
3325                 return PLANE_CTL_FORMAT_YUV422 | PLANE_CTL_YUV422_YUYV;
3326         case DRM_FORMAT_YVYU:
3327                 return PLANE_CTL_FORMAT_YUV422 | PLANE_CTL_YUV422_YVYU;
3328         case DRM_FORMAT_UYVY:
3329                 return PLANE_CTL_FORMAT_YUV422 | PLANE_CTL_YUV422_UYVY;
3330         case DRM_FORMAT_VYUY:
3331                 return PLANE_CTL_FORMAT_YUV422 | PLANE_CTL_YUV422_VYUY;
3332         default:
3333                 MISSING_CASE(pixel_format);
3334         }
3335
3336         return 0;
3337 }
3338
3339 u32 skl_plane_ctl_tiling(uint64_t fb_modifier)
3340 {
3341         switch (fb_modifier) {
3342         case DRM_FORMAT_MOD_NONE:
3343                 break;
3344         case I915_FORMAT_MOD_X_TILED:
3345                 return PLANE_CTL_TILED_X;
3346         case I915_FORMAT_MOD_Y_TILED:
3347                 return PLANE_CTL_TILED_Y;
3348         case I915_FORMAT_MOD_Yf_TILED:
3349                 return PLANE_CTL_TILED_YF;
3350         default:
3351                 MISSING_CASE(fb_modifier);
3352         }
3353
3354         return 0;
3355 }
3356
3357 u32 skl_plane_ctl_rotation(unsigned int rotation)
3358 {
3359         switch (rotation) {
3360         case DRM_ROTATE_0:
3361                 break;
3362         /*
3363          * DRM_ROTATE_ is counter clockwise to stay compatible with Xrandr
3364          * while i915 HW rotation is clockwise, thats why this swapping.
3365          */
3366         case DRM_ROTATE_90:
3367                 return PLANE_CTL_ROTATE_270;
3368         case DRM_ROTATE_180:
3369                 return PLANE_CTL_ROTATE_180;
3370         case DRM_ROTATE_270:
3371                 return PLANE_CTL_ROTATE_90;
3372         default:
3373                 MISSING_CASE(rotation);
3374         }
3375
3376         return 0;
3377 }
3378
3379 static void skylake_update_primary_plane(struct drm_plane *plane,
3380                                          const struct intel_crtc_state *crtc_state,
3381                                          const struct intel_plane_state *plane_state)
3382 {
3383         struct drm_device *dev = plane->dev;
3384         struct drm_i915_private *dev_priv = to_i915(dev);
3385         struct intel_crtc *intel_crtc = to_intel_crtc(crtc_state->base.crtc);
3386         struct drm_framebuffer *fb = plane_state->base.fb;
3387         const struct skl_wm_values *wm = &dev_priv->wm.skl_results;
3388         const struct skl_plane_wm *p_wm =
3389                 &crtc_state->wm.skl.optimal.planes[0];
3390         int pipe = intel_crtc->pipe;
3391         u32 plane_ctl;
3392         unsigned int rotation = plane_state->base.rotation;
3393         u32 stride = skl_plane_stride(fb, 0, rotation);
3394         u32 surf_addr = plane_state->main.offset;
3395         int scaler_id = plane_state->scaler_id;
3396         int src_x = plane_state->main.x;
3397         int src_y = plane_state->main.y;
3398         int src_w = drm_rect_width(&plane_state->base.src) >> 16;
3399         int src_h = drm_rect_height(&plane_state->base.src) >> 16;
3400         int dst_x = plane_state->base.dst.x1;
3401         int dst_y = plane_state->base.dst.y1;
3402         int dst_w = drm_rect_width(&plane_state->base.dst);
3403         int dst_h = drm_rect_height(&plane_state->base.dst);
3404
3405         plane_ctl = PLANE_CTL_ENABLE |
3406                     PLANE_CTL_PIPE_GAMMA_ENABLE |
3407                     PLANE_CTL_PIPE_CSC_ENABLE;
3408
3409         plane_ctl |= skl_plane_ctl_format(fb->pixel_format);
3410         plane_ctl |= skl_plane_ctl_tiling(fb->modifier[0]);
3411         plane_ctl |= PLANE_CTL_PLANE_GAMMA_DISABLE;
3412         plane_ctl |= skl_plane_ctl_rotation(rotation);
3413
3414         /* Sizes are 0 based */
3415         src_w--;
3416         src_h--;
3417         dst_w--;
3418         dst_h--;
3419
3420         intel_crtc->dspaddr_offset = surf_addr;
3421
3422         intel_crtc->adjusted_x = src_x;
3423         intel_crtc->adjusted_y = src_y;
3424
3425         if (wm->dirty_pipes & drm_crtc_mask(&intel_crtc->base))
3426                 skl_write_plane_wm(intel_crtc, p_wm, &wm->ddb, 0);
3427
3428         I915_WRITE(PLANE_CTL(pipe, 0), plane_ctl);
3429         I915_WRITE(PLANE_OFFSET(pipe, 0), (src_y << 16) | src_x);
3430         I915_WRITE(PLANE_STRIDE(pipe, 0), stride);
3431         I915_WRITE(PLANE_SIZE(pipe, 0), (src_h << 16) | src_w);
3432
3433         if (scaler_id >= 0) {
3434                 uint32_t ps_ctrl = 0;
3435
3436                 WARN_ON(!dst_w || !dst_h);
3437                 ps_ctrl = PS_SCALER_EN | PS_PLANE_SEL(0) |
3438                         crtc_state->scaler_state.scalers[scaler_id].mode;
3439                 I915_WRITE(SKL_PS_CTRL(pipe, scaler_id), ps_ctrl);
3440                 I915_WRITE(SKL_PS_PWR_GATE(pipe, scaler_id), 0);
3441                 I915_WRITE(SKL_PS_WIN_POS(pipe, scaler_id), (dst_x << 16) | dst_y);
3442                 I915_WRITE(SKL_PS_WIN_SZ(pipe, scaler_id), (dst_w << 16) | dst_h);
3443                 I915_WRITE(PLANE_POS(pipe, 0), 0);
3444         } else {
3445                 I915_WRITE(PLANE_POS(pipe, 0), (dst_y << 16) | dst_x);
3446         }
3447
3448         I915_WRITE(PLANE_SURF(pipe, 0),
3449                    intel_fb_gtt_offset(fb, rotation) + surf_addr);
3450
3451         POSTING_READ(PLANE_SURF(pipe, 0));
3452 }
3453
3454 static void skylake_disable_primary_plane(struct drm_plane *primary,
3455                                           struct drm_crtc *crtc)
3456 {
3457         struct drm_device *dev = crtc->dev;
3458         struct drm_i915_private *dev_priv = to_i915(dev);
3459         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3460         struct intel_crtc_state *cstate = to_intel_crtc_state(crtc->state);
3461         const struct skl_plane_wm *p_wm = &cstate->wm.skl.optimal.planes[0];
3462         int pipe = intel_crtc->pipe;
3463
3464         /*
3465          * We only populate skl_results on watermark updates, and if the
3466          * plane's visiblity isn't actually changing neither is its watermarks.
3467          */
3468         if (!crtc->primary->state->visible)
3469                 skl_write_plane_wm(intel_crtc, p_wm,
3470                                    &dev_priv->wm.skl_results.ddb, 0);
3471
3472         I915_WRITE(PLANE_CTL(pipe, 0), 0);
3473         I915_WRITE(PLANE_SURF(pipe, 0), 0);
3474         POSTING_READ(PLANE_SURF(pipe, 0));
3475 }
3476
3477 /* Assume fb object is pinned & idle & fenced and just update base pointers */
3478 static int
3479 intel_pipe_set_base_atomic(struct drm_crtc *crtc, struct drm_framebuffer *fb,
3480                            int x, int y, enum mode_set_atomic state)
3481 {
3482         /* Support for kgdboc is disabled, this needs a major rework. */
3483         DRM_ERROR("legacy panic handler not supported any more.\n");
3484
3485         return -ENODEV;
3486 }
3487
3488 static void intel_complete_page_flips(struct drm_i915_private *dev_priv)
3489 {
3490         struct intel_crtc *crtc;
3491
3492         for_each_intel_crtc(&dev_priv->drm, crtc)
3493                 intel_finish_page_flip_cs(dev_priv, crtc->pipe);
3494 }
3495
3496 static void intel_update_primary_planes(struct drm_device *dev)
3497 {
3498         struct drm_crtc *crtc;
3499
3500         for_each_crtc(dev, crtc) {
3501                 struct intel_plane *plane = to_intel_plane(crtc->primary);
3502                 struct intel_plane_state *plane_state =
3503                         to_intel_plane_state(plane->base.state);
3504
3505                 if (plane_state->base.visible)
3506                         plane->update_plane(&plane->base,
3507                                             to_intel_crtc_state(crtc->state),
3508                                             plane_state);
3509         }
3510 }
3511
3512 static int
3513 __intel_display_resume(struct drm_device *dev,
3514                        struct drm_atomic_state *state)
3515 {
3516         struct drm_crtc_state *crtc_state;
3517         struct drm_crtc *crtc;
3518         int i, ret;
3519
3520         intel_modeset_setup_hw_state(dev);
3521         i915_redisable_vga(dev);
3522
3523         if (!state)
3524                 return 0;
3525
3526         for_each_crtc_in_state(state, crtc, crtc_state, i) {
3527                 /*
3528                  * Force recalculation even if we restore
3529                  * current state. With fast modeset this may not result
3530                  * in a modeset when the state is compatible.
3531                  */
3532                 crtc_state->mode_changed = true;
3533         }
3534
3535         /* ignore any reset values/BIOS leftovers in the WM registers */
3536         to_intel_atomic_state(state)->skip_intermediate_wm = true;
3537
3538         ret = drm_atomic_commit(state);
3539
3540         WARN_ON(ret == -EDEADLK);
3541         return ret;
3542 }
3543
3544 static bool gpu_reset_clobbers_display(struct drm_i915_private *dev_priv)
3545 {
3546         return intel_has_gpu_reset(dev_priv) &&
3547                 INTEL_GEN(dev_priv) < 5 && !IS_G4X(dev_priv);
3548 }
3549
3550 void intel_prepare_reset(struct drm_i915_private *dev_priv)
3551 {
3552         struct drm_device *dev = &dev_priv->drm;
3553         struct drm_modeset_acquire_ctx *ctx = &dev_priv->reset_ctx;
3554         struct drm_atomic_state *state;
3555         int ret;
3556
3557         /*
3558          * Need mode_config.mutex so that we don't
3559          * trample ongoing ->detect() and whatnot.
3560          */
3561         mutex_lock(&dev->mode_config.mutex);
3562         drm_modeset_acquire_init(ctx, 0);
3563         while (1) {
3564                 ret = drm_modeset_lock_all_ctx(dev, ctx);
3565                 if (ret != -EDEADLK)
3566                         break;
3567
3568                 drm_modeset_backoff(ctx);
3569         }
3570
3571         /* reset doesn't touch the display, but flips might get nuked anyway, */
3572         if (!i915.force_reset_modeset_test &&
3573             !gpu_reset_clobbers_display(dev_priv))
3574                 return;
3575
3576         /*
3577          * Disabling the crtcs gracefully seems nicer. Also the
3578          * g33 docs say we should at least disable all the planes.
3579          */
3580         state = drm_atomic_helper_duplicate_state(dev, ctx);
3581         if (IS_ERR(state)) {
3582                 ret = PTR_ERR(state);
3583                 state = NULL;
3584                 DRM_ERROR("Duplicating state failed with %i\n", ret);
3585                 goto err;
3586         }
3587
3588         ret = drm_atomic_helper_disable_all(dev, ctx);
3589         if (ret) {
3590                 DRM_ERROR("Suspending crtc's failed with %i\n", ret);
3591                 goto err;
3592         }
3593
3594         dev_priv->modeset_restore_state = state;
3595         state->acquire_ctx = ctx;
3596         return;
3597
3598 err:
3599         drm_atomic_state_put(state);
3600 }
3601
3602 void intel_finish_reset(struct drm_i915_private *dev_priv)
3603 {
3604         struct drm_device *dev = &dev_priv->drm;
3605         struct drm_modeset_acquire_ctx *ctx = &dev_priv->reset_ctx;
3606         struct drm_atomic_state *state = dev_priv->modeset_restore_state;
3607         int ret;
3608
3609         /*
3610          * Flips in the rings will be nuked by the reset,
3611          * so complete all pending flips so that user space
3612          * will get its events and not get stuck.
3613          */
3614         intel_complete_page_flips(dev_priv);
3615
3616         dev_priv->modeset_restore_state = NULL;
3617
3618         /* reset doesn't touch the display */
3619         if (!gpu_reset_clobbers_display(dev_priv)) {
3620                 if (!state) {
3621                         /*
3622                          * Flips in the rings have been nuked by the reset,
3623                          * so update the base address of all primary
3624                          * planes to the the last fb to make sure we're
3625                          * showing the correct fb after a reset.
3626                          *
3627                          * FIXME: Atomic will make this obsolete since we won't schedule
3628                          * CS-based flips (which might get lost in gpu resets) any more.
3629                          */
3630                         intel_update_primary_planes(dev);
3631                 } else {
3632                         ret = __intel_display_resume(dev, state);
3633                         if (ret)
3634                                 DRM_ERROR("Restoring old state failed with %i\n", ret);
3635                 }
3636         } else {
3637                 /*
3638                  * The display has been reset as well,
3639                  * so need a full re-initialization.
3640                  */
3641                 intel_runtime_pm_disable_interrupts(dev_priv);
3642                 intel_runtime_pm_enable_interrupts(dev_priv);
3643
3644                 intel_pps_unlock_regs_wa(dev_priv);
3645                 intel_modeset_init_hw(dev);
3646
3647                 spin_lock_irq(&dev_priv->irq_lock);
3648                 if (dev_priv->display.hpd_irq_setup)
3649                         dev_priv->display.hpd_irq_setup(dev_priv);
3650                 spin_unlock_irq(&dev_priv->irq_lock);
3651
3652                 ret = __intel_display_resume(dev, state);
3653                 if (ret)
3654                         DRM_ERROR("Restoring old state failed with %i\n", ret);
3655
3656                 intel_hpd_init(dev_priv);
3657         }
3658
3659         if (state)
3660                 drm_atomic_state_put(state);
3661         drm_modeset_drop_locks(ctx);
3662         drm_modeset_acquire_fini(ctx);
3663         mutex_unlock(&dev->mode_config.mutex);
3664 }
3665
3666 static bool abort_flip_on_reset(struct intel_crtc *crtc)
3667 {
3668         struct i915_gpu_error *error = &to_i915(crtc->base.dev)->gpu_error;
3669
3670         if (i915_reset_in_progress(error))
3671                 return true;
3672
3673         if (crtc->reset_count != i915_reset_count(error))
3674                 return true;
3675
3676         return false;
3677 }
3678
3679 static bool intel_crtc_has_pending_flip(struct drm_crtc *crtc)
3680 {
3681         struct drm_device *dev = crtc->dev;
3682         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3683         bool pending;
3684
3685         if (abort_flip_on_reset(intel_crtc))
3686                 return false;
3687
3688         spin_lock_irq(&dev->event_lock);
3689         pending = to_intel_crtc(crtc)->flip_work != NULL;
3690         spin_unlock_irq(&dev->event_lock);
3691
3692         return pending;
3693 }
3694
3695 static void intel_update_pipe_config(struct intel_crtc *crtc,
3696                                      struct intel_crtc_state *old_crtc_state)
3697 {
3698         struct drm_device *dev = crtc->base.dev;
3699         struct drm_i915_private *dev_priv = to_i915(dev);
3700         struct intel_crtc_state *pipe_config =
3701                 to_intel_crtc_state(crtc->base.state);
3702
3703         /* drm_atomic_helper_update_legacy_modeset_state might not be called. */
3704         crtc->base.mode = crtc->base.state->mode;
3705
3706         DRM_DEBUG_KMS("Updating pipe size %ix%i -> %ix%i\n",
3707                       old_crtc_state->pipe_src_w, old_crtc_state->pipe_src_h,
3708                       pipe_config->pipe_src_w, pipe_config->pipe_src_h);
3709
3710         /*
3711          * Update pipe size and adjust fitter if needed: the reason for this is
3712          * that in compute_mode_changes we check the native mode (not the pfit
3713          * mode) to see if we can flip rather than do a full mode set. In the
3714          * fastboot case, we'll flip, but if we don't update the pipesrc and
3715          * pfit state, we'll end up with a big fb scanned out into the wrong
3716          * sized surface.
3717          */
3718
3719         I915_WRITE(PIPESRC(crtc->pipe),
3720                    ((pipe_config->pipe_src_w - 1) << 16) |
3721                    (pipe_config->pipe_src_h - 1));
3722
3723         /* on skylake this is done by detaching scalers */
3724         if (INTEL_INFO(dev)->gen >= 9) {
3725                 skl_detach_scalers(crtc);
3726
3727                 if (pipe_config->pch_pfit.enabled)
3728                         skylake_pfit_enable(crtc);
3729         } else if (HAS_PCH_SPLIT(dev_priv)) {
3730                 if (pipe_config->pch_pfit.enabled)
3731                         ironlake_pfit_enable(crtc);
3732                 else if (old_crtc_state->pch_pfit.enabled)
3733                         ironlake_pfit_disable(crtc, true);
3734         }
3735 }
3736
3737 static void intel_fdi_normal_train(struct drm_crtc *crtc)
3738 {
3739         struct drm_device *dev = crtc->dev;
3740         struct drm_i915_private *dev_priv = to_i915(dev);
3741         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3742         int pipe = intel_crtc->pipe;
3743         i915_reg_t reg;
3744         u32 temp;
3745
3746         /* enable normal train */
3747         reg = FDI_TX_CTL(pipe);
3748         temp = I915_READ(reg);
3749         if (IS_IVYBRIDGE(dev_priv)) {
3750                 temp &= ~FDI_LINK_TRAIN_NONE_IVB;
3751                 temp |= FDI_LINK_TRAIN_NONE_IVB | FDI_TX_ENHANCE_FRAME_ENABLE;
3752         } else {
3753                 temp &= ~FDI_LINK_TRAIN_NONE;
3754                 temp |= FDI_LINK_TRAIN_NONE | FDI_TX_ENHANCE_FRAME_ENABLE;
3755         }
3756         I915_WRITE(reg, temp);
3757
3758         reg = FDI_RX_CTL(pipe);
3759         temp = I915_READ(reg);
3760         if (HAS_PCH_CPT(dev_priv)) {
3761                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
3762                 temp |= FDI_LINK_TRAIN_NORMAL_CPT;
3763         } else {
3764                 temp &= ~FDI_LINK_TRAIN_NONE;
3765                 temp |= FDI_LINK_TRAIN_NONE;
3766         }
3767         I915_WRITE(reg, temp | FDI_RX_ENHANCE_FRAME_ENABLE);
3768
3769         /* wait one idle pattern time */
3770         POSTING_READ(reg);
3771         udelay(1000);
3772
3773         /* IVB wants error correction enabled */
3774         if (IS_IVYBRIDGE(dev_priv))
3775                 I915_WRITE(reg, I915_READ(reg) | FDI_FS_ERRC_ENABLE |
3776                            FDI_FE_ERRC_ENABLE);
3777 }
3778
3779 /* The FDI link training functions for ILK/Ibexpeak. */
3780 static void ironlake_fdi_link_train(struct drm_crtc *crtc)
3781 {
3782         struct drm_device *dev = crtc->dev;
3783         struct drm_i915_private *dev_priv = to_i915(dev);
3784         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3785         int pipe = intel_crtc->pipe;
3786         i915_reg_t reg;
3787         u32 temp, tries;
3788
3789         /* FDI needs bits from pipe first */
3790         assert_pipe_enabled(dev_priv, pipe);
3791
3792         /* Train 1: umask FDI RX Interrupt symbol_lock and bit_lock bit
3793            for train result */
3794         reg = FDI_RX_IMR(pipe);
3795         temp = I915_READ(reg);
3796         temp &= ~FDI_RX_SYMBOL_LOCK;
3797         temp &= ~FDI_RX_BIT_LOCK;
3798         I915_WRITE(reg, temp);
3799         I915_READ(reg);
3800         udelay(150);
3801
3802         /* enable CPU FDI TX and PCH FDI RX */
3803         reg = FDI_TX_CTL(pipe);
3804         temp = I915_READ(reg);
3805         temp &= ~FDI_DP_PORT_WIDTH_MASK;
3806         temp |= FDI_DP_PORT_WIDTH(intel_crtc->config->fdi_lanes);
3807         temp &= ~FDI_LINK_TRAIN_NONE;
3808         temp |= FDI_LINK_TRAIN_PATTERN_1;
3809         I915_WRITE(reg, temp | FDI_TX_ENABLE);
3810
3811         reg = FDI_RX_CTL(pipe);
3812         temp = I915_READ(reg);
3813         temp &= ~FDI_LINK_TRAIN_NONE;
3814         temp |= FDI_LINK_TRAIN_PATTERN_1;
3815         I915_WRITE(reg, temp | FDI_RX_ENABLE);
3816
3817         POSTING_READ(reg);
3818         udelay(150);
3819
3820         /* Ironlake workaround, enable clock pointer after FDI enable*/
3821         I915_WRITE(FDI_RX_CHICKEN(pipe), FDI_RX_PHASE_SYNC_POINTER_OVR);
3822         I915_WRITE(FDI_RX_CHICKEN(pipe), FDI_RX_PHASE_SYNC_POINTER_OVR |
3823                    FDI_RX_PHASE_SYNC_POINTER_EN);
3824
3825         reg = FDI_RX_IIR(pipe);
3826         for (tries = 0; tries < 5; tries++) {
3827                 temp = I915_READ(reg);
3828                 DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
3829
3830                 if ((temp & FDI_RX_BIT_LOCK)) {
3831                         DRM_DEBUG_KMS("FDI train 1 done.\n");
3832                         I915_WRITE(reg, temp | FDI_RX_BIT_LOCK);
3833                         break;
3834                 }
3835         }
3836         if (tries == 5)
3837                 DRM_ERROR("FDI train 1 fail!\n");
3838
3839         /* Train 2 */
3840         reg = FDI_TX_CTL(pipe);
3841         temp = I915_READ(reg);
3842         temp &= ~FDI_LINK_TRAIN_NONE;
3843         temp |= FDI_LINK_TRAIN_PATTERN_2;
3844         I915_WRITE(reg, temp);
3845
3846         reg = FDI_RX_CTL(pipe);
3847         temp = I915_READ(reg);
3848         temp &= ~FDI_LINK_TRAIN_NONE;
3849         temp |= FDI_LINK_TRAIN_PATTERN_2;
3850         I915_WRITE(reg, temp);
3851
3852         POSTING_READ(reg);
3853         udelay(150);
3854
3855         reg = FDI_RX_IIR(pipe);
3856         for (tries = 0; tries < 5; tries++) {
3857                 temp = I915_READ(reg);
3858                 DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
3859
3860                 if (temp & FDI_RX_SYMBOL_LOCK) {
3861                         I915_WRITE(reg, temp | FDI_RX_SYMBOL_LOCK);
3862                         DRM_DEBUG_KMS("FDI train 2 done.\n");
3863                         break;
3864                 }
3865         }
3866         if (tries == 5)
3867                 DRM_ERROR("FDI train 2 fail!\n");
3868
3869         DRM_DEBUG_KMS("FDI train done\n");
3870
3871 }
3872
3873 static const int snb_b_fdi_train_param[] = {
3874         FDI_LINK_TRAIN_400MV_0DB_SNB_B,
3875         FDI_LINK_TRAIN_400MV_6DB_SNB_B,
3876         FDI_LINK_TRAIN_600MV_3_5DB_SNB_B,
3877         FDI_LINK_TRAIN_800MV_0DB_SNB_B,
3878 };
3879
3880 /* The FDI link training functions for SNB/Cougarpoint. */
3881 static void gen6_fdi_link_train(struct drm_crtc *crtc)
3882 {
3883         struct drm_device *dev = crtc->dev;
3884         struct drm_i915_private *dev_priv = to_i915(dev);
3885         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3886         int pipe = intel_crtc->pipe;
3887         i915_reg_t reg;
3888         u32 temp, i, retry;
3889
3890         /* Train 1: umask FDI RX Interrupt symbol_lock and bit_lock bit
3891            for train result */
3892         reg = FDI_RX_IMR(pipe);
3893         temp = I915_READ(reg);
3894         temp &= ~FDI_RX_SYMBOL_LOCK;
3895         temp &= ~FDI_RX_BIT_LOCK;
3896         I915_WRITE(reg, temp);
3897
3898         POSTING_READ(reg);
3899         udelay(150);
3900
3901         /* enable CPU FDI TX and PCH FDI RX */
3902         reg = FDI_TX_CTL(pipe);
3903         temp = I915_READ(reg);
3904         temp &= ~FDI_DP_PORT_WIDTH_MASK;
3905         temp |= FDI_DP_PORT_WIDTH(intel_crtc->config->fdi_lanes);
3906         temp &= ~FDI_LINK_TRAIN_NONE;
3907         temp |= FDI_LINK_TRAIN_PATTERN_1;
3908         temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
3909         /* SNB-B */
3910         temp |= FDI_LINK_TRAIN_400MV_0DB_SNB_B;
3911         I915_WRITE(reg, temp | FDI_TX_ENABLE);
3912
3913         I915_WRITE(FDI_RX_MISC(pipe),
3914                    FDI_RX_TP1_TO_TP2_48 | FDI_RX_FDI_DELAY_90);
3915
3916         reg = FDI_RX_CTL(pipe);
3917         temp = I915_READ(reg);
3918         if (HAS_PCH_CPT(dev_priv)) {
3919                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
3920                 temp |= FDI_LINK_TRAIN_PATTERN_1_CPT;
3921         } else {
3922                 temp &= ~FDI_LINK_TRAIN_NONE;
3923                 temp |= FDI_LINK_TRAIN_PATTERN_1;
3924         }
3925         I915_WRITE(reg, temp | FDI_RX_ENABLE);
3926
3927         POSTING_READ(reg);
3928         udelay(150);
3929
3930         for (i = 0; i < 4; i++) {
3931                 reg = FDI_TX_CTL(pipe);
3932                 temp = I915_READ(reg);
3933                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
3934                 temp |= snb_b_fdi_train_param[i];
3935                 I915_WRITE(reg, temp);
3936
3937                 POSTING_READ(reg);
3938                 udelay(500);
3939
3940                 for (retry = 0; retry < 5; retry++) {
3941                         reg = FDI_RX_IIR(pipe);
3942                         temp = I915_READ(reg);
3943                         DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
3944                         if (temp & FDI_RX_BIT_LOCK) {
3945                                 I915_WRITE(reg, temp | FDI_RX_BIT_LOCK);
3946                                 DRM_DEBUG_KMS("FDI train 1 done.\n");
3947                                 break;
3948                         }
3949                         udelay(50);
3950                 }
3951                 if (retry < 5)
3952                         break;
3953         }
3954         if (i == 4)
3955                 DRM_ERROR("FDI train 1 fail!\n");
3956
3957         /* Train 2 */
3958         reg = FDI_TX_CTL(pipe);
3959         temp = I915_READ(reg);
3960         temp &= ~FDI_LINK_TRAIN_NONE;
3961         temp |= FDI_LINK_TRAIN_PATTERN_2;
3962         if (IS_GEN6(dev_priv)) {
3963                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
3964                 /* SNB-B */
3965                 temp |= FDI_LINK_TRAIN_400MV_0DB_SNB_B;
3966         }
3967         I915_WRITE(reg, temp);
3968
3969         reg = FDI_RX_CTL(pipe);
3970         temp = I915_READ(reg);
3971         if (HAS_PCH_CPT(dev_priv)) {
3972                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
3973                 temp |= FDI_LINK_TRAIN_PATTERN_2_CPT;
3974         } else {
3975                 temp &= ~FDI_LINK_TRAIN_NONE;
3976                 temp |= FDI_LINK_TRAIN_PATTERN_2;
3977         }
3978         I915_WRITE(reg, temp);
3979
3980         POSTING_READ(reg);
3981         udelay(150);
3982
3983         for (i = 0; i < 4; i++) {
3984                 reg = FDI_TX_CTL(pipe);
3985                 temp = I915_READ(reg);
3986                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
3987                 temp |= snb_b_fdi_train_param[i];
3988                 I915_WRITE(reg, temp);
3989
3990                 POSTING_READ(reg);
3991                 udelay(500);
3992
3993                 for (retry = 0; retry < 5; retry++) {
3994                         reg = FDI_RX_IIR(pipe);
3995                         temp = I915_READ(reg);
3996                         DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
3997                         if (temp & FDI_RX_SYMBOL_LOCK) {
3998                                 I915_WRITE(reg, temp | FDI_RX_SYMBOL_LOCK);
3999                                 DRM_DEBUG_KMS("FDI train 2 done.\n");
4000                                 break;
4001                         }
4002                         udelay(50);
4003                 }
4004                 if (retry < 5)
4005                         break;
4006         }
4007         if (i == 4)
4008                 DRM_ERROR("FDI train 2 fail!\n");
4009
4010         DRM_DEBUG_KMS("FDI train done.\n");
4011 }
4012
4013 /* Manual link training for Ivy Bridge A0 parts */
4014 static void ivb_manual_fdi_link_train(struct drm_crtc *crtc)
4015 {
4016         struct drm_device *dev = crtc->dev;
4017         struct drm_i915_private *dev_priv = to_i915(dev);
4018         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4019         int pipe = intel_crtc->pipe;
4020         i915_reg_t reg;
4021         u32 temp, i, j;
4022
4023         /* Train 1: umask FDI RX Interrupt symbol_lock and bit_lock bit
4024            for train result */
4025         reg = FDI_RX_IMR(pipe);
4026         temp = I915_READ(reg);
4027         temp &= ~FDI_RX_SYMBOL_LOCK;
4028         temp &= ~FDI_RX_BIT_LOCK;
4029         I915_WRITE(reg, temp);
4030
4031         POSTING_READ(reg);
4032         udelay(150);
4033
4034         DRM_DEBUG_KMS("FDI_RX_IIR before link train 0x%x\n",
4035                       I915_READ(FDI_RX_IIR(pipe)));
4036
4037         /* Try each vswing and preemphasis setting twice before moving on */
4038         for (j = 0; j < ARRAY_SIZE(snb_b_fdi_train_param) * 2; j++) {
4039                 /* disable first in case we need to retry */
4040                 reg = FDI_TX_CTL(pipe);
4041                 temp = I915_READ(reg);
4042                 temp &= ~(FDI_LINK_TRAIN_AUTO | FDI_LINK_TRAIN_NONE_IVB);
4043                 temp &= ~FDI_TX_ENABLE;
4044                 I915_WRITE(reg, temp);
4045
4046                 reg = FDI_RX_CTL(pipe);
4047                 temp = I915_READ(reg);
4048                 temp &= ~FDI_LINK_TRAIN_AUTO;
4049                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
4050                 temp &= ~FDI_RX_ENABLE;
4051                 I915_WRITE(reg, temp);
4052
4053                 /* enable CPU FDI TX and PCH FDI RX */
4054                 reg = FDI_TX_CTL(pipe);
4055                 temp = I915_READ(reg);
4056                 temp &= ~FDI_DP_PORT_WIDTH_MASK;
4057                 temp |= FDI_DP_PORT_WIDTH(intel_crtc->config->fdi_lanes);
4058                 temp |= FDI_LINK_TRAIN_PATTERN_1_IVB;
4059                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
4060                 temp |= snb_b_fdi_train_param[j/2];
4061                 temp |= FDI_COMPOSITE_SYNC;
4062                 I915_WRITE(reg, temp | FDI_TX_ENABLE);
4063
4064                 I915_WRITE(FDI_RX_MISC(pipe),
4065                            FDI_RX_TP1_TO_TP2_48 | FDI_RX_FDI_DELAY_90);
4066
4067                 reg = FDI_RX_CTL(pipe);
4068                 temp = I915_READ(reg);
4069                 temp |= FDI_LINK_TRAIN_PATTERN_1_CPT;
4070                 temp |= FDI_COMPOSITE_SYNC;
4071                 I915_WRITE(reg, temp | FDI_RX_ENABLE);
4072
4073                 POSTING_READ(reg);
4074                 udelay(1); /* should be 0.5us */
4075
4076                 for (i = 0; i < 4; i++) {
4077                         reg = FDI_RX_IIR(pipe);
4078                         temp = I915_READ(reg);
4079                         DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
4080
4081                         if (temp & FDI_RX_BIT_LOCK ||
4082                             (I915_READ(reg) & FDI_RX_BIT_LOCK)) {
4083                                 I915_WRITE(reg, temp | FDI_RX_BIT_LOCK);
4084                                 DRM_DEBUG_KMS("FDI train 1 done, level %i.\n",
4085                                               i);
4086                                 break;
4087                         }
4088                         udelay(1); /* should be 0.5us */
4089                 }
4090                 if (i == 4) {
4091                         DRM_DEBUG_KMS("FDI train 1 fail on vswing %d\n", j / 2);
4092                         continue;
4093                 }
4094
4095                 /* Train 2 */
4096                 reg = FDI_TX_CTL(pipe);
4097                 temp = I915_READ(reg);
4098                 temp &= ~FDI_LINK_TRAIN_NONE_IVB;
4099                 temp |= FDI_LINK_TRAIN_PATTERN_2_IVB;
4100                 I915_WRITE(reg, temp);
4101
4102                 reg = FDI_RX_CTL(pipe);
4103                 temp = I915_READ(reg);
4104                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
4105                 temp |= FDI_LINK_TRAIN_PATTERN_2_CPT;
4106                 I915_WRITE(reg, temp);
4107
4108                 POSTING_READ(reg);
4109                 udelay(2); /* should be 1.5us */
4110
4111                 for (i = 0; i < 4; i++) {
4112                         reg = FDI_RX_IIR(pipe);
4113                         temp = I915_READ(reg);
4114                         DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
4115
4116                         if (temp & FDI_RX_SYMBOL_LOCK ||
4117                             (I915_READ(reg) & FDI_RX_SYMBOL_LOCK)) {
4118                                 I915_WRITE(reg, temp | FDI_RX_SYMBOL_LOCK);
4119                                 DRM_DEBUG_KMS("FDI train 2 done, level %i.\n",
4120                                               i);
4121                                 goto train_done;
4122                         }
4123                         udelay(2); /* should be 1.5us */
4124                 }
4125                 if (i == 4)
4126                         DRM_DEBUG_KMS("FDI train 2 fail on vswing %d\n", j / 2);
4127         }
4128
4129 train_done:
4130         DRM_DEBUG_KMS("FDI train done.\n");
4131 }
4132
4133 static void ironlake_fdi_pll_enable(struct intel_crtc *intel_crtc)
4134 {
4135         struct drm_device *dev = intel_crtc->base.dev;
4136         struct drm_i915_private *dev_priv = to_i915(dev);
4137         int pipe = intel_crtc->pipe;
4138         i915_reg_t reg;
4139         u32 temp;
4140
4141         /* enable PCH FDI RX PLL, wait warmup plus DMI latency */
4142         reg = FDI_RX_CTL(pipe);
4143         temp = I915_READ(reg);
4144         temp &= ~(FDI_DP_PORT_WIDTH_MASK | (0x7 << 16));
4145         temp |= FDI_DP_PORT_WIDTH(intel_crtc->config->fdi_lanes);
4146         temp |= (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) << 11;
4147         I915_WRITE(reg, temp | FDI_RX_PLL_ENABLE);
4148
4149         POSTING_READ(reg);
4150         udelay(200);
4151
4152         /* Switch from Rawclk to PCDclk */
4153         temp = I915_READ(reg);
4154         I915_WRITE(reg, temp | FDI_PCDCLK);
4155
4156         POSTING_READ(reg);
4157         udelay(200);
4158
4159         /* Enable CPU FDI TX PLL, always on for Ironlake */
4160         reg = FDI_TX_CTL(pipe);
4161         temp = I915_READ(reg);
4162         if ((temp & FDI_TX_PLL_ENABLE) == 0) {
4163                 I915_WRITE(reg, temp | FDI_TX_PLL_ENABLE);
4164
4165                 POSTING_READ(reg);
4166                 udelay(100);
4167         }
4168 }
4169
4170 static void ironlake_fdi_pll_disable(struct intel_crtc *intel_crtc)
4171 {
4172         struct drm_device *dev = intel_crtc->base.dev;
4173         struct drm_i915_private *dev_priv = to_i915(dev);
4174         int pipe = intel_crtc->pipe;
4175         i915_reg_t reg;
4176         u32 temp;
4177
4178         /* Switch from PCDclk to Rawclk */
4179         reg = FDI_RX_CTL(pipe);
4180         temp = I915_READ(reg);
4181         I915_WRITE(reg, temp & ~FDI_PCDCLK);
4182
4183         /* Disable CPU FDI TX PLL */
4184         reg = FDI_TX_CTL(pipe);
4185         temp = I915_READ(reg);
4186         I915_WRITE(reg, temp & ~FDI_TX_PLL_ENABLE);
4187
4188         POSTING_READ(reg);
4189         udelay(100);
4190
4191         reg = FDI_RX_CTL(pipe);
4192         temp = I915_READ(reg);
4193         I915_WRITE(reg, temp & ~FDI_RX_PLL_ENABLE);
4194
4195         /* Wait for the clocks to turn off. */
4196         POSTING_READ(reg);
4197         udelay(100);
4198 }
4199
4200 static void ironlake_fdi_disable(struct drm_crtc *crtc)
4201 {
4202         struct drm_device *dev = crtc->dev;
4203         struct drm_i915_private *dev_priv = to_i915(dev);
4204         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4205         int pipe = intel_crtc->pipe;
4206         i915_reg_t reg;
4207         u32 temp;
4208
4209         /* disable CPU FDI tx and PCH FDI rx */
4210         reg = FDI_TX_CTL(pipe);
4211         temp = I915_READ(reg);
4212         I915_WRITE(reg, temp & ~FDI_TX_ENABLE);
4213         POSTING_READ(reg);
4214
4215         reg = FDI_RX_CTL(pipe);
4216         temp = I915_READ(reg);
4217         temp &= ~(0x7 << 16);
4218         temp |= (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) << 11;
4219         I915_WRITE(reg, temp & ~FDI_RX_ENABLE);
4220
4221         POSTING_READ(reg);
4222         udelay(100);
4223
4224         /* Ironlake workaround, disable clock pointer after downing FDI */
4225         if (HAS_PCH_IBX(dev_priv))
4226                 I915_WRITE(FDI_RX_CHICKEN(pipe), FDI_RX_PHASE_SYNC_POINTER_OVR);
4227
4228         /* still set train pattern 1 */
4229         reg = FDI_TX_CTL(pipe);
4230         temp = I915_READ(reg);
4231         temp &= ~FDI_LINK_TRAIN_NONE;
4232         temp |= FDI_LINK_TRAIN_PATTERN_1;
4233         I915_WRITE(reg, temp);
4234
4235         reg = FDI_RX_CTL(pipe);
4236         temp = I915_READ(reg);
4237         if (HAS_PCH_CPT(dev_priv)) {
4238                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
4239                 temp |= FDI_LINK_TRAIN_PATTERN_1_CPT;
4240         } else {
4241                 temp &= ~FDI_LINK_TRAIN_NONE;
4242                 temp |= FDI_LINK_TRAIN_PATTERN_1;
4243         }
4244         /* BPC in FDI rx is consistent with that in PIPECONF */
4245         temp &= ~(0x07 << 16);
4246         temp |= (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) << 11;
4247         I915_WRITE(reg, temp);
4248
4249         POSTING_READ(reg);
4250         udelay(100);
4251 }
4252
4253 bool intel_has_pending_fb_unpin(struct drm_device *dev)
4254 {
4255         struct intel_crtc *crtc;
4256
4257         /* Note that we don't need to be called with mode_config.lock here
4258          * as our list of CRTC objects is static for the lifetime of the
4259          * device and so cannot disappear as we iterate. Similarly, we can
4260          * happily treat the predicates as racy, atomic checks as userspace
4261          * cannot claim and pin a new fb without at least acquring the
4262          * struct_mutex and so serialising with us.
4263          */
4264         for_each_intel_crtc(dev, crtc) {
4265                 if (atomic_read(&crtc->unpin_work_count) == 0)
4266                         continue;
4267
4268                 if (crtc->flip_work)
4269                         intel_wait_for_vblank(dev, crtc->pipe);
4270
4271                 return true;
4272         }
4273
4274         return false;
4275 }
4276
4277 static void page_flip_completed(struct intel_crtc *intel_crtc)
4278 {
4279         struct drm_i915_private *dev_priv = to_i915(intel_crtc->base.dev);
4280         struct intel_flip_work *work = intel_crtc->flip_work;
4281
4282         intel_crtc->flip_work = NULL;
4283
4284         if (work->event)
4285                 drm_crtc_send_vblank_event(&intel_crtc->base, work->event);
4286
4287         drm_crtc_vblank_put(&intel_crtc->base);
4288
4289         wake_up_all(&dev_priv->pending_flip_queue);
4290         queue_work(dev_priv->wq, &work->unpin_work);
4291
4292         trace_i915_flip_complete(intel_crtc->plane,
4293                                  work->pending_flip_obj);
4294 }
4295
4296 static int intel_crtc_wait_for_pending_flips(struct drm_crtc *crtc)
4297 {
4298         struct drm_device *dev = crtc->dev;
4299         struct drm_i915_private *dev_priv = to_i915(dev);
4300         long ret;
4301
4302         WARN_ON(waitqueue_active(&dev_priv->pending_flip_queue));
4303
4304         ret = wait_event_interruptible_timeout(
4305                                         dev_priv->pending_flip_queue,
4306                                         !intel_crtc_has_pending_flip(crtc),
4307                                         60*HZ);
4308
4309         if (ret < 0)
4310                 return ret;
4311
4312         if (ret == 0) {
4313                 struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4314                 struct intel_flip_work *work;
4315
4316                 spin_lock_irq(&dev->event_lock);
4317                 work = intel_crtc->flip_work;
4318                 if (work && !is_mmio_work(work)) {
4319                         WARN_ONCE(1, "Removing stuck page flip\n");
4320                         page_flip_completed(intel_crtc);
4321                 }
4322                 spin_unlock_irq(&dev->event_lock);
4323         }
4324
4325         return 0;
4326 }
4327
4328 void lpt_disable_iclkip(struct drm_i915_private *dev_priv)
4329 {
4330         u32 temp;
4331
4332         I915_WRITE(PIXCLK_GATE, PIXCLK_GATE_GATE);
4333
4334         mutex_lock(&dev_priv->sb_lock);
4335
4336         temp = intel_sbi_read(dev_priv, SBI_SSCCTL6, SBI_ICLK);
4337         temp |= SBI_SSCCTL_DISABLE;
4338         intel_sbi_write(dev_priv, SBI_SSCCTL6, temp, SBI_ICLK);
4339
4340         mutex_unlock(&dev_priv->sb_lock);
4341 }
4342
4343 /* Program iCLKIP clock to the desired frequency */
4344 static void lpt_program_iclkip(struct drm_crtc *crtc)
4345 {
4346         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
4347         int clock = to_intel_crtc(crtc)->config->base.adjusted_mode.crtc_clock;
4348         u32 divsel, phaseinc, auxdiv, phasedir = 0;
4349         u32 temp;
4350
4351         lpt_disable_iclkip(dev_priv);
4352
4353         /* The iCLK virtual clock root frequency is in MHz,
4354          * but the adjusted_mode->crtc_clock in in KHz. To get the
4355          * divisors, it is necessary to divide one by another, so we
4356          * convert the virtual clock precision to KHz here for higher
4357          * precision.
4358          */
4359         for (auxdiv = 0; auxdiv < 2; auxdiv++) {
4360                 u32 iclk_virtual_root_freq = 172800 * 1000;
4361                 u32 iclk_pi_range = 64;
4362                 u32 desired_divisor;
4363
4364                 desired_divisor = DIV_ROUND_CLOSEST(iclk_virtual_root_freq,
4365                                                     clock << auxdiv);
4366                 divsel = (desired_divisor / iclk_pi_range) - 2;
4367                 phaseinc = desired_divisor % iclk_pi_range;
4368
4369                 /*
4370                  * Near 20MHz is a corner case which is
4371                  * out of range for the 7-bit divisor
4372                  */
4373                 if (divsel <= 0x7f)
4374                         break;
4375         }
4376
4377         /* This should not happen with any sane values */
4378         WARN_ON(SBI_SSCDIVINTPHASE_DIVSEL(divsel) &
4379                 ~SBI_SSCDIVINTPHASE_DIVSEL_MASK);
4380         WARN_ON(SBI_SSCDIVINTPHASE_DIR(phasedir) &
4381                 ~SBI_SSCDIVINTPHASE_INCVAL_MASK);
4382
4383         DRM_DEBUG_KMS("iCLKIP clock: found settings for %dKHz refresh rate: auxdiv=%x, divsel=%x, phasedir=%x, phaseinc=%x\n",
4384                         clock,
4385                         auxdiv,
4386                         divsel,
4387                         phasedir,
4388                         phaseinc);
4389
4390         mutex_lock(&dev_priv->sb_lock);
4391
4392         /* Program SSCDIVINTPHASE6 */
4393         temp = intel_sbi_read(dev_priv, SBI_SSCDIVINTPHASE6, SBI_ICLK);
4394         temp &= ~SBI_SSCDIVINTPHASE_DIVSEL_MASK;
4395         temp |= SBI_SSCDIVINTPHASE_DIVSEL(divsel);
4396         temp &= ~SBI_SSCDIVINTPHASE_INCVAL_MASK;
4397         temp |= SBI_SSCDIVINTPHASE_INCVAL(phaseinc);
4398         temp |= SBI_SSCDIVINTPHASE_DIR(phasedir);
4399         temp |= SBI_SSCDIVINTPHASE_PROPAGATE;
4400         intel_sbi_write(dev_priv, SBI_SSCDIVINTPHASE6, temp, SBI_ICLK);
4401
4402         /* Program SSCAUXDIV */
4403         temp = intel_sbi_read(dev_priv, SBI_SSCAUXDIV6, SBI_ICLK);
4404         temp &= ~SBI_SSCAUXDIV_FINALDIV2SEL(1);
4405         temp |= SBI_SSCAUXDIV_FINALDIV2SEL(auxdiv);
4406         intel_sbi_write(dev_priv, SBI_SSCAUXDIV6, temp, SBI_ICLK);
4407
4408         /* Enable modulator and associated divider */
4409         temp = intel_sbi_read(dev_priv, SBI_SSCCTL6, SBI_ICLK);
4410         temp &= ~SBI_SSCCTL_DISABLE;
4411         intel_sbi_write(dev_priv, SBI_SSCCTL6, temp, SBI_ICLK);
4412
4413         mutex_unlock(&dev_priv->sb_lock);
4414
4415         /* Wait for initialization time */
4416         udelay(24);
4417
4418         I915_WRITE(PIXCLK_GATE, PIXCLK_GATE_UNGATE);
4419 }
4420
4421 int lpt_get_iclkip(struct drm_i915_private *dev_priv)
4422 {
4423         u32 divsel, phaseinc, auxdiv;
4424         u32 iclk_virtual_root_freq = 172800 * 1000;
4425         u32 iclk_pi_range = 64;
4426         u32 desired_divisor;
4427         u32 temp;
4428
4429         if ((I915_READ(PIXCLK_GATE) & PIXCLK_GATE_UNGATE) == 0)
4430                 return 0;
4431
4432         mutex_lock(&dev_priv->sb_lock);
4433
4434         temp = intel_sbi_read(dev_priv, SBI_SSCCTL6, SBI_ICLK);
4435         if (temp & SBI_SSCCTL_DISABLE) {
4436                 mutex_unlock(&dev_priv->sb_lock);
4437                 return 0;
4438         }
4439
4440         temp = intel_sbi_read(dev_priv, SBI_SSCDIVINTPHASE6, SBI_ICLK);
4441         divsel = (temp & SBI_SSCDIVINTPHASE_DIVSEL_MASK) >>
4442                 SBI_SSCDIVINTPHASE_DIVSEL_SHIFT;
4443         phaseinc = (temp & SBI_SSCDIVINTPHASE_INCVAL_MASK) >>
4444                 SBI_SSCDIVINTPHASE_INCVAL_SHIFT;
4445
4446         temp = intel_sbi_read(dev_priv, SBI_SSCAUXDIV6, SBI_ICLK);
4447         auxdiv = (temp & SBI_SSCAUXDIV_FINALDIV2SEL_MASK) >>
4448                 SBI_SSCAUXDIV_FINALDIV2SEL_SHIFT;
4449
4450         mutex_unlock(&dev_priv->sb_lock);
4451
4452         desired_divisor = (divsel + 2) * iclk_pi_range + phaseinc;
4453
4454         return DIV_ROUND_CLOSEST(iclk_virtual_root_freq,
4455                                  desired_divisor << auxdiv);
4456 }
4457
4458 static void ironlake_pch_transcoder_set_timings(struct intel_crtc *crtc,
4459                                                 enum pipe pch_transcoder)
4460 {
4461         struct drm_device *dev = crtc->base.dev;
4462         struct drm_i915_private *dev_priv = to_i915(dev);
4463         enum transcoder cpu_transcoder = crtc->config->cpu_transcoder;
4464
4465         I915_WRITE(PCH_TRANS_HTOTAL(pch_transcoder),
4466                    I915_READ(HTOTAL(cpu_transcoder)));
4467         I915_WRITE(PCH_TRANS_HBLANK(pch_transcoder),
4468                    I915_READ(HBLANK(cpu_transcoder)));
4469         I915_WRITE(PCH_TRANS_HSYNC(pch_transcoder),
4470                    I915_READ(HSYNC(cpu_transcoder)));
4471
4472         I915_WRITE(PCH_TRANS_VTOTAL(pch_transcoder),
4473                    I915_READ(VTOTAL(cpu_transcoder)));
4474         I915_WRITE(PCH_TRANS_VBLANK(pch_transcoder),
4475                    I915_READ(VBLANK(cpu_transcoder)));
4476         I915_WRITE(PCH_TRANS_VSYNC(pch_transcoder),
4477                    I915_READ(VSYNC(cpu_transcoder)));
4478         I915_WRITE(PCH_TRANS_VSYNCSHIFT(pch_transcoder),
4479                    I915_READ(VSYNCSHIFT(cpu_transcoder)));
4480 }
4481
4482 static void cpt_set_fdi_bc_bifurcation(struct drm_device *dev, bool enable)
4483 {
4484         struct drm_i915_private *dev_priv = to_i915(dev);
4485         uint32_t temp;
4486
4487         temp = I915_READ(SOUTH_CHICKEN1);
4488         if (!!(temp & FDI_BC_BIFURCATION_SELECT) == enable)
4489                 return;
4490
4491         WARN_ON(I915_READ(FDI_RX_CTL(PIPE_B)) & FDI_RX_ENABLE);
4492         WARN_ON(I915_READ(FDI_RX_CTL(PIPE_C)) & FDI_RX_ENABLE);
4493
4494         temp &= ~FDI_BC_BIFURCATION_SELECT;
4495         if (enable)
4496                 temp |= FDI_BC_BIFURCATION_SELECT;
4497
4498         DRM_DEBUG_KMS("%sabling fdi C rx\n", enable ? "en" : "dis");
4499         I915_WRITE(SOUTH_CHICKEN1, temp);
4500         POSTING_READ(SOUTH_CHICKEN1);
4501 }
4502
4503 static void ivybridge_update_fdi_bc_bifurcation(struct intel_crtc *intel_crtc)
4504 {
4505         struct drm_device *dev = intel_crtc->base.dev;
4506
4507         switch (intel_crtc->pipe) {
4508         case PIPE_A:
4509                 break;
4510         case PIPE_B:
4511                 if (intel_crtc->config->fdi_lanes > 2)
4512                         cpt_set_fdi_bc_bifurcation(dev, false);
4513                 else
4514                         cpt_set_fdi_bc_bifurcation(dev, true);
4515
4516                 break;
4517         case PIPE_C:
4518                 cpt_set_fdi_bc_bifurcation(dev, true);
4519
4520                 break;
4521         default:
4522                 BUG();
4523         }
4524 }
4525
4526 /* Return which DP Port should be selected for Transcoder DP control */
4527 static enum port
4528 intel_trans_dp_port_sel(struct drm_crtc *crtc)
4529 {
4530         struct drm_device *dev = crtc->dev;
4531         struct intel_encoder *encoder;
4532
4533         for_each_encoder_on_crtc(dev, crtc, encoder) {
4534                 if (encoder->type == INTEL_OUTPUT_DP ||
4535                     encoder->type == INTEL_OUTPUT_EDP)
4536                         return enc_to_dig_port(&encoder->base)->port;
4537         }
4538
4539         return -1;
4540 }
4541
4542 /*
4543  * Enable PCH resources required for PCH ports:
4544  *   - PCH PLLs
4545  *   - FDI training & RX/TX
4546  *   - update transcoder timings
4547  *   - DP transcoding bits
4548  *   - transcoder
4549  */
4550 static void ironlake_pch_enable(struct drm_crtc *crtc)
4551 {
4552         struct drm_device *dev = crtc->dev;
4553         struct drm_i915_private *dev_priv = to_i915(dev);
4554         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4555         int pipe = intel_crtc->pipe;
4556         u32 temp;
4557
4558         assert_pch_transcoder_disabled(dev_priv, pipe);
4559
4560         if (IS_IVYBRIDGE(dev_priv))
4561                 ivybridge_update_fdi_bc_bifurcation(intel_crtc);
4562
4563         /* Write the TU size bits before fdi link training, so that error
4564          * detection works. */
4565         I915_WRITE(FDI_RX_TUSIZE1(pipe),
4566                    I915_READ(PIPE_DATA_M1(pipe)) & TU_SIZE_MASK);
4567
4568         /* For PCH output, training FDI link */
4569         dev_priv->display.fdi_link_train(crtc);
4570
4571         /* We need to program the right clock selection before writing the pixel
4572          * mutliplier into the DPLL. */
4573         if (HAS_PCH_CPT(dev_priv)) {
4574                 u32 sel;
4575
4576                 temp = I915_READ(PCH_DPLL_SEL);
4577                 temp |= TRANS_DPLL_ENABLE(pipe);
4578                 sel = TRANS_DPLLB_SEL(pipe);
4579                 if (intel_crtc->config->shared_dpll ==
4580                     intel_get_shared_dpll_by_id(dev_priv, DPLL_ID_PCH_PLL_B))
4581                         temp |= sel;
4582                 else
4583                         temp &= ~sel;
4584                 I915_WRITE(PCH_DPLL_SEL, temp);
4585         }
4586
4587         /* XXX: pch pll's can be enabled any time before we enable the PCH
4588          * transcoder, and we actually should do this to not upset any PCH
4589          * transcoder that already use the clock when we share it.
4590          *
4591          * Note that enable_shared_dpll tries to do the right thing, but
4592          * get_shared_dpll unconditionally resets the pll - we need that to have
4593          * the right LVDS enable sequence. */
4594         intel_enable_shared_dpll(intel_crtc);
4595
4596         /* set transcoder timing, panel must allow it */
4597         assert_panel_unlocked(dev_priv, pipe);
4598         ironlake_pch_transcoder_set_timings(intel_crtc, pipe);
4599
4600         intel_fdi_normal_train(crtc);
4601
4602         /* For PCH DP, enable TRANS_DP_CTL */
4603         if (HAS_PCH_CPT(dev_priv) &&
4604             intel_crtc_has_dp_encoder(intel_crtc->config)) {
4605                 const struct drm_display_mode *adjusted_mode =
4606                         &intel_crtc->config->base.adjusted_mode;
4607                 u32 bpc = (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) >> 5;
4608                 i915_reg_t reg = TRANS_DP_CTL(pipe);
4609                 temp = I915_READ(reg);
4610                 temp &= ~(TRANS_DP_PORT_SEL_MASK |
4611                           TRANS_DP_SYNC_MASK |
4612                           TRANS_DP_BPC_MASK);
4613                 temp |= TRANS_DP_OUTPUT_ENABLE;
4614                 temp |= bpc << 9; /* same format but at 11:9 */
4615
4616                 if (adjusted_mode->flags & DRM_MODE_FLAG_PHSYNC)
4617                         temp |= TRANS_DP_HSYNC_ACTIVE_HIGH;
4618                 if (adjusted_mode->flags & DRM_MODE_FLAG_PVSYNC)
4619                         temp |= TRANS_DP_VSYNC_ACTIVE_HIGH;
4620
4621                 switch (intel_trans_dp_port_sel(crtc)) {
4622                 case PORT_B:
4623                         temp |= TRANS_DP_PORT_SEL_B;
4624                         break;
4625                 case PORT_C:
4626                         temp |= TRANS_DP_PORT_SEL_C;
4627                         break;
4628                 case PORT_D:
4629                         temp |= TRANS_DP_PORT_SEL_D;
4630                         break;
4631                 default:
4632                         BUG();
4633                 }
4634
4635                 I915_WRITE(reg, temp);
4636         }
4637
4638         ironlake_enable_pch_transcoder(dev_priv, pipe);
4639 }
4640
4641 static void lpt_pch_enable(struct drm_crtc *crtc)
4642 {
4643         struct drm_device *dev = crtc->dev;
4644         struct drm_i915_private *dev_priv = to_i915(dev);
4645         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4646         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
4647
4648         assert_pch_transcoder_disabled(dev_priv, TRANSCODER_A);
4649
4650         lpt_program_iclkip(crtc);
4651
4652         /* Set transcoder timing. */
4653         ironlake_pch_transcoder_set_timings(intel_crtc, PIPE_A);
4654
4655         lpt_enable_pch_transcoder(dev_priv, cpu_transcoder);
4656 }
4657
4658 static void cpt_verify_modeset(struct drm_device *dev, int pipe)
4659 {
4660         struct drm_i915_private *dev_priv = to_i915(dev);
4661         i915_reg_t dslreg = PIPEDSL(pipe);
4662         u32 temp;
4663
4664         temp = I915_READ(dslreg);
4665         udelay(500);
4666         if (wait_for(I915_READ(dslreg) != temp, 5)) {
4667                 if (wait_for(I915_READ(dslreg) != temp, 5))
4668                         DRM_ERROR("mode set failed: pipe %c stuck\n", pipe_name(pipe));
4669         }
4670 }
4671
4672 static int
4673 skl_update_scaler(struct intel_crtc_state *crtc_state, bool force_detach,
4674                   unsigned scaler_user, int *scaler_id, unsigned int rotation,
4675                   int src_w, int src_h, int dst_w, int dst_h)
4676 {
4677         struct intel_crtc_scaler_state *scaler_state =
4678                 &crtc_state->scaler_state;
4679         struct intel_crtc *intel_crtc =
4680                 to_intel_crtc(crtc_state->base.crtc);
4681         int need_scaling;
4682
4683         need_scaling = drm_rotation_90_or_270(rotation) ?
4684                 (src_h != dst_w || src_w != dst_h):
4685                 (src_w != dst_w || src_h != dst_h);
4686
4687         /*
4688          * if plane is being disabled or scaler is no more required or force detach
4689          *  - free scaler binded to this plane/crtc
4690          *  - in order to do this, update crtc->scaler_usage
4691          *
4692          * Here scaler state in crtc_state is set free so that
4693          * scaler can be assigned to other user. Actual register
4694          * update to free the scaler is done in plane/panel-fit programming.
4695          * For this purpose crtc/plane_state->scaler_id isn't reset here.
4696          */
4697         if (force_detach || !need_scaling) {
4698                 if (*scaler_id >= 0) {
4699                         scaler_state->scaler_users &= ~(1 << scaler_user);
4700                         scaler_state->scalers[*scaler_id].in_use = 0;
4701
4702                         DRM_DEBUG_KMS("scaler_user index %u.%u: "
4703                                 "Staged freeing scaler id %d scaler_users = 0x%x\n",
4704                                 intel_crtc->pipe, scaler_user, *scaler_id,
4705                                 scaler_state->scaler_users);
4706                         *scaler_id = -1;
4707                 }
4708                 return 0;
4709         }
4710
4711         /* range checks */
4712         if (src_w < SKL_MIN_SRC_W || src_h < SKL_MIN_SRC_H ||
4713                 dst_w < SKL_MIN_DST_W || dst_h < SKL_MIN_DST_H ||
4714
4715                 src_w > SKL_MAX_SRC_W || src_h > SKL_MAX_SRC_H ||
4716                 dst_w > SKL_MAX_DST_W || dst_h > SKL_MAX_DST_H) {
4717                 DRM_DEBUG_KMS("scaler_user index %u.%u: src %ux%u dst %ux%u "
4718                         "size is out of scaler range\n",
4719                         intel_crtc->pipe, scaler_user, src_w, src_h, dst_w, dst_h);
4720                 return -EINVAL;
4721         }
4722
4723         /* mark this plane as a scaler user in crtc_state */
4724         scaler_state->scaler_users |= (1 << scaler_user);
4725         DRM_DEBUG_KMS("scaler_user index %u.%u: "
4726                 "staged scaling request for %ux%u->%ux%u scaler_users = 0x%x\n",
4727                 intel_crtc->pipe, scaler_user, src_w, src_h, dst_w, dst_h,
4728                 scaler_state->scaler_users);
4729
4730         return 0;
4731 }
4732
4733 /**
4734  * skl_update_scaler_crtc - Stages update to scaler state for a given crtc.
4735  *
4736  * @state: crtc's scaler state
4737  *
4738  * Return
4739  *     0 - scaler_usage updated successfully
4740  *    error - requested scaling cannot be supported or other error condition
4741  */
4742 int skl_update_scaler_crtc(struct intel_crtc_state *state)
4743 {
4744         struct intel_crtc *intel_crtc = to_intel_crtc(state->base.crtc);
4745         const struct drm_display_mode *adjusted_mode = &state->base.adjusted_mode;
4746
4747         DRM_DEBUG_KMS("Updating scaler for [CRTC:%d:%s] scaler_user index %u.%u\n",
4748                       intel_crtc->base.base.id, intel_crtc->base.name,
4749                       intel_crtc->pipe, SKL_CRTC_INDEX);
4750
4751         return skl_update_scaler(state, !state->base.active, SKL_CRTC_INDEX,
4752                 &state->scaler_state.scaler_id, DRM_ROTATE_0,
4753                 state->pipe_src_w, state->pipe_src_h,
4754                 adjusted_mode->crtc_hdisplay, adjusted_mode->crtc_vdisplay);
4755 }
4756
4757 /**
4758  * skl_update_scaler_plane - Stages update to scaler state for a given plane.
4759  *
4760  * @state: crtc's scaler state
4761  * @plane_state: atomic plane state to update
4762  *
4763  * Return
4764  *     0 - scaler_usage updated successfully
4765  *    error - requested scaling cannot be supported or other error condition
4766  */
4767 static int skl_update_scaler_plane(struct intel_crtc_state *crtc_state,
4768                                    struct intel_plane_state *plane_state)
4769 {
4770
4771         struct intel_crtc *intel_crtc = to_intel_crtc(crtc_state->base.crtc);
4772         struct intel_plane *intel_plane =
4773                 to_intel_plane(plane_state->base.plane);
4774         struct drm_framebuffer *fb = plane_state->base.fb;
4775         int ret;
4776
4777         bool force_detach = !fb || !plane_state->base.visible;
4778
4779         DRM_DEBUG_KMS("Updating scaler for [PLANE:%d:%s] scaler_user index %u.%u\n",
4780                       intel_plane->base.base.id, intel_plane->base.name,
4781                       intel_crtc->pipe, drm_plane_index(&intel_plane->base));
4782
4783         ret = skl_update_scaler(crtc_state, force_detach,
4784                                 drm_plane_index(&intel_plane->base),
4785                                 &plane_state->scaler_id,
4786                                 plane_state->base.rotation,
4787                                 drm_rect_width(&plane_state->base.src) >> 16,
4788                                 drm_rect_height(&plane_state->base.src) >> 16,
4789                                 drm_rect_width(&plane_state->base.dst),
4790                                 drm_rect_height(&plane_state->base.dst));
4791
4792         if (ret || plane_state->scaler_id < 0)
4793                 return ret;
4794
4795         /* check colorkey */
4796         if (plane_state->ckey.flags != I915_SET_COLORKEY_NONE) {
4797                 DRM_DEBUG_KMS("[PLANE:%d:%s] scaling with color key not allowed",
4798                               intel_plane->base.base.id,
4799                               intel_plane->base.name);
4800                 return -EINVAL;
4801         }
4802
4803         /* Check src format */
4804         switch (fb->pixel_format) {
4805         case DRM_FORMAT_RGB565:
4806         case DRM_FORMAT_XBGR8888:
4807         case DRM_FORMAT_XRGB8888:
4808         case DRM_FORMAT_ABGR8888:
4809         case DRM_FORMAT_ARGB8888:
4810         case DRM_FORMAT_XRGB2101010:
4811         case DRM_FORMAT_XBGR2101010:
4812         case DRM_FORMAT_YUYV:
4813         case DRM_FORMAT_YVYU:
4814         case DRM_FORMAT_UYVY:
4815         case DRM_FORMAT_VYUY:
4816                 break;
4817         default:
4818                 DRM_DEBUG_KMS("[PLANE:%d:%s] FB:%d unsupported scaling format 0x%x\n",
4819                               intel_plane->base.base.id, intel_plane->base.name,
4820                               fb->base.id, fb->pixel_format);
4821                 return -EINVAL;
4822         }
4823
4824         return 0;
4825 }
4826
4827 static void skylake_scaler_disable(struct intel_crtc *crtc)
4828 {
4829         int i;
4830
4831         for (i = 0; i < crtc->num_scalers; i++)
4832                 skl_detach_scaler(crtc, i);
4833 }
4834
4835 static void skylake_pfit_enable(struct intel_crtc *crtc)
4836 {
4837         struct drm_device *dev = crtc->base.dev;
4838         struct drm_i915_private *dev_priv = to_i915(dev);
4839         int pipe = crtc->pipe;
4840         struct intel_crtc_scaler_state *scaler_state =
4841                 &crtc->config->scaler_state;
4842
4843         DRM_DEBUG_KMS("for crtc_state = %p\n", crtc->config);
4844
4845         if (crtc->config->pch_pfit.enabled) {
4846                 int id;
4847
4848                 if (WARN_ON(crtc->config->scaler_state.scaler_id < 0)) {
4849                         DRM_ERROR("Requesting pfit without getting a scaler first\n");
4850                         return;
4851                 }
4852
4853                 id = scaler_state->scaler_id;
4854                 I915_WRITE(SKL_PS_CTRL(pipe, id), PS_SCALER_EN |
4855                         PS_FILTER_MEDIUM | scaler_state->scalers[id].mode);
4856                 I915_WRITE(SKL_PS_WIN_POS(pipe, id), crtc->config->pch_pfit.pos);
4857                 I915_WRITE(SKL_PS_WIN_SZ(pipe, id), crtc->config->pch_pfit.size);
4858
4859                 DRM_DEBUG_KMS("for crtc_state = %p scaler_id = %d\n", crtc->config, id);
4860         }
4861 }
4862
4863 static void ironlake_pfit_enable(struct intel_crtc *crtc)
4864 {
4865         struct drm_device *dev = crtc->base.dev;
4866         struct drm_i915_private *dev_priv = to_i915(dev);
4867         int pipe = crtc->pipe;
4868
4869         if (crtc->config->pch_pfit.enabled) {
4870                 /* Force use of hard-coded filter coefficients
4871                  * as some pre-programmed values are broken,
4872                  * e.g. x201.
4873                  */
4874                 if (IS_IVYBRIDGE(dev_priv) || IS_HASWELL(dev_priv))
4875                         I915_WRITE(PF_CTL(pipe), PF_ENABLE | PF_FILTER_MED_3x3 |
4876                                                  PF_PIPE_SEL_IVB(pipe));
4877                 else
4878                         I915_WRITE(PF_CTL(pipe), PF_ENABLE | PF_FILTER_MED_3x3);
4879                 I915_WRITE(PF_WIN_POS(pipe), crtc->config->pch_pfit.pos);
4880                 I915_WRITE(PF_WIN_SZ(pipe), crtc->config->pch_pfit.size);
4881         }
4882 }
4883
4884 void hsw_enable_ips(struct intel_crtc *crtc)
4885 {
4886         struct drm_device *dev = crtc->base.dev;
4887         struct drm_i915_private *dev_priv = to_i915(dev);
4888
4889         if (!crtc->config->ips_enabled)
4890                 return;
4891
4892         /*
4893          * We can only enable IPS after we enable a plane and wait for a vblank
4894          * This function is called from post_plane_update, which is run after
4895          * a vblank wait.
4896          */
4897
4898         assert_plane_enabled(dev_priv, crtc->plane);
4899         if (IS_BROADWELL(dev_priv)) {
4900                 mutex_lock(&dev_priv->rps.hw_lock);
4901                 WARN_ON(sandybridge_pcode_write(dev_priv, DISPLAY_IPS_CONTROL, 0xc0000000));
4902                 mutex_unlock(&dev_priv->rps.hw_lock);
4903                 /* Quoting Art Runyan: "its not safe to expect any particular
4904                  * value in IPS_CTL bit 31 after enabling IPS through the
4905                  * mailbox." Moreover, the mailbox may return a bogus state,
4906                  * so we need to just enable it and continue on.
4907                  */
4908         } else {
4909                 I915_WRITE(IPS_CTL, IPS_ENABLE);
4910                 /* The bit only becomes 1 in the next vblank, so this wait here
4911                  * is essentially intel_wait_for_vblank. If we don't have this
4912                  * and don't wait for vblanks until the end of crtc_enable, then
4913                  * the HW state readout code will complain that the expected
4914                  * IPS_CTL value is not the one we read. */
4915                 if (intel_wait_for_register(dev_priv,
4916                                             IPS_CTL, IPS_ENABLE, IPS_ENABLE,
4917                                             50))
4918                         DRM_ERROR("Timed out waiting for IPS enable\n");
4919         }
4920 }
4921
4922 void hsw_disable_ips(struct intel_crtc *crtc)
4923 {
4924         struct drm_device *dev = crtc->base.dev;
4925         struct drm_i915_private *dev_priv = to_i915(dev);
4926
4927         if (!crtc->config->ips_enabled)
4928                 return;
4929
4930         assert_plane_enabled(dev_priv, crtc->plane);
4931         if (IS_BROADWELL(dev_priv)) {
4932                 mutex_lock(&dev_priv->rps.hw_lock);
4933                 WARN_ON(sandybridge_pcode_write(dev_priv, DISPLAY_IPS_CONTROL, 0));
4934                 mutex_unlock(&dev_priv->rps.hw_lock);
4935                 /* wait for pcode to finish disabling IPS, which may take up to 42ms */
4936                 if (intel_wait_for_register(dev_priv,
4937                                             IPS_CTL, IPS_ENABLE, 0,
4938                                             42))
4939                         DRM_ERROR("Timed out waiting for IPS disable\n");
4940         } else {
4941                 I915_WRITE(IPS_CTL, 0);
4942                 POSTING_READ(IPS_CTL);
4943         }
4944
4945         /* We need to wait for a vblank before we can disable the plane. */
4946         intel_wait_for_vblank(dev, crtc->pipe);
4947 }
4948
4949 static void intel_crtc_dpms_overlay_disable(struct intel_crtc *intel_crtc)
4950 {
4951         if (intel_crtc->overlay) {
4952                 struct drm_device *dev = intel_crtc->base.dev;
4953                 struct drm_i915_private *dev_priv = to_i915(dev);
4954
4955                 mutex_lock(&dev->struct_mutex);
4956                 dev_priv->mm.interruptible = false;
4957                 (void) intel_overlay_switch_off(intel_crtc->overlay);
4958                 dev_priv->mm.interruptible = true;
4959                 mutex_unlock(&dev->struct_mutex);
4960         }
4961
4962         /* Let userspace switch the overlay on again. In most cases userspace
4963          * has to recompute where to put it anyway.
4964          */
4965 }
4966
4967 /**
4968  * intel_post_enable_primary - Perform operations after enabling primary plane
4969  * @crtc: the CRTC whose primary plane was just enabled
4970  *
4971  * Performs potentially sleeping operations that must be done after the primary
4972  * plane is enabled, such as updating FBC and IPS.  Note that this may be
4973  * called due to an explicit primary plane update, or due to an implicit
4974  * re-enable that is caused when a sprite plane is updated to no longer
4975  * completely hide the primary plane.
4976  */
4977 static void
4978 intel_post_enable_primary(struct drm_crtc *crtc)
4979 {
4980         struct drm_device *dev = crtc->dev;
4981         struct drm_i915_private *dev_priv = to_i915(dev);
4982         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4983         int pipe = intel_crtc->pipe;
4984
4985         /*
4986          * FIXME IPS should be fine as long as one plane is
4987          * enabled, but in practice it seems to have problems
4988          * when going from primary only to sprite only and vice
4989          * versa.
4990          */
4991         hsw_enable_ips(intel_crtc);
4992
4993         /*
4994          * Gen2 reports pipe underruns whenever all planes are disabled.
4995          * So don't enable underrun reporting before at least some planes
4996          * are enabled.
4997          * FIXME: Need to fix the logic to work when we turn off all planes
4998          * but leave the pipe running.
4999          */
5000         if (IS_GEN2(dev_priv))
5001                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
5002
5003         /* Underruns don't always raise interrupts, so check manually. */
5004         intel_check_cpu_fifo_underruns(dev_priv);
5005         intel_check_pch_fifo_underruns(dev_priv);
5006 }
5007
5008 /* FIXME move all this to pre_plane_update() with proper state tracking */
5009 static void
5010 intel_pre_disable_primary(struct drm_crtc *crtc)
5011 {
5012         struct drm_device *dev = crtc->dev;
5013         struct drm_i915_private *dev_priv = to_i915(dev);
5014         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5015         int pipe = intel_crtc->pipe;
5016
5017         /*
5018          * Gen2 reports pipe underruns whenever all planes are disabled.
5019          * So diasble underrun reporting before all the planes get disabled.
5020          * FIXME: Need to fix the logic to work when we turn off all planes
5021          * but leave the pipe running.
5022          */
5023         if (IS_GEN2(dev_priv))
5024                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
5025
5026         /*
5027          * FIXME IPS should be fine as long as one plane is
5028          * enabled, but in practice it seems to have problems
5029          * when going from primary only to sprite only and vice
5030          * versa.
5031          */
5032         hsw_disable_ips(intel_crtc);
5033 }
5034
5035 /* FIXME get rid of this and use pre_plane_update */
5036 static void
5037 intel_pre_disable_primary_noatomic(struct drm_crtc *crtc)
5038 {
5039         struct drm_device *dev = crtc->dev;
5040         struct drm_i915_private *dev_priv = to_i915(dev);
5041         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5042         int pipe = intel_crtc->pipe;
5043
5044         intel_pre_disable_primary(crtc);
5045
5046         /*
5047          * Vblank time updates from the shadow to live plane control register
5048          * are blocked if the memory self-refresh mode is active at that
5049          * moment. So to make sure the plane gets truly disabled, disable
5050          * first the self-refresh mode. The self-refresh enable bit in turn
5051          * will be checked/applied by the HW only at the next frame start
5052          * event which is after the vblank start event, so we need to have a
5053          * wait-for-vblank between disabling the plane and the pipe.
5054          */
5055         if (HAS_GMCH_DISPLAY(dev_priv)) {
5056                 intel_set_memory_cxsr(dev_priv, false);
5057                 dev_priv->wm.vlv.cxsr = false;
5058                 intel_wait_for_vblank(dev, pipe);
5059         }
5060 }
5061
5062 static void intel_post_plane_update(struct intel_crtc_state *old_crtc_state)
5063 {
5064         struct intel_crtc *crtc = to_intel_crtc(old_crtc_state->base.crtc);
5065         struct drm_atomic_state *old_state = old_crtc_state->base.state;
5066         struct intel_crtc_state *pipe_config =
5067                 to_intel_crtc_state(crtc->base.state);
5068         struct drm_plane *primary = crtc->base.primary;
5069         struct drm_plane_state *old_pri_state =
5070                 drm_atomic_get_existing_plane_state(old_state, primary);
5071
5072         intel_frontbuffer_flip(to_i915(crtc->base.dev), pipe_config->fb_bits);
5073
5074         crtc->wm.cxsr_allowed = true;
5075
5076         if (pipe_config->update_wm_post && pipe_config->base.active)
5077                 intel_update_watermarks(&crtc->base);
5078
5079         if (old_pri_state) {
5080                 struct intel_plane_state *primary_state =
5081                         to_intel_plane_state(primary->state);
5082                 struct intel_plane_state *old_primary_state =
5083                         to_intel_plane_state(old_pri_state);
5084
5085                 intel_fbc_post_update(crtc);
5086
5087                 if (primary_state->base.visible &&
5088                     (needs_modeset(&pipe_config->base) ||
5089                      !old_primary_state->base.visible))
5090                         intel_post_enable_primary(&crtc->base);
5091         }
5092 }
5093
5094 static void intel_pre_plane_update(struct intel_crtc_state *old_crtc_state)
5095 {
5096         struct intel_crtc *crtc = to_intel_crtc(old_crtc_state->base.crtc);
5097         struct drm_device *dev = crtc->base.dev;
5098         struct drm_i915_private *dev_priv = to_i915(dev);
5099         struct intel_crtc_state *pipe_config =
5100                 to_intel_crtc_state(crtc->base.state);
5101         struct drm_atomic_state *old_state = old_crtc_state->base.state;
5102         struct drm_plane *primary = crtc->base.primary;
5103         struct drm_plane_state *old_pri_state =
5104                 drm_atomic_get_existing_plane_state(old_state, primary);
5105         bool modeset = needs_modeset(&pipe_config->base);
5106
5107         if (old_pri_state) {
5108                 struct intel_plane_state *primary_state =
5109                         to_intel_plane_state(primary->state);
5110                 struct intel_plane_state *old_primary_state =
5111                         to_intel_plane_state(old_pri_state);
5112
5113                 intel_fbc_pre_update(crtc, pipe_config, primary_state);
5114
5115                 if (old_primary_state->base.visible &&
5116                     (modeset || !primary_state->base.visible))
5117                         intel_pre_disable_primary(&crtc->base);
5118         }
5119
5120         if (pipe_config->disable_cxsr && HAS_GMCH_DISPLAY(dev_priv)) {
5121                 crtc->wm.cxsr_allowed = false;
5122
5123                 /*
5124                  * Vblank time updates from the shadow to live plane control register
5125                  * are blocked if the memory self-refresh mode is active at that
5126                  * moment. So to make sure the plane gets truly disabled, disable
5127                  * first the self-refresh mode. The self-refresh enable bit in turn
5128                  * will be checked/applied by the HW only at the next frame start
5129                  * event which is after the vblank start event, so we need to have a
5130                  * wait-for-vblank between disabling the plane and the pipe.
5131                  */
5132                 if (old_crtc_state->base.active) {
5133                         intel_set_memory_cxsr(dev_priv, false);
5134                         dev_priv->wm.vlv.cxsr = false;
5135                         intel_wait_for_vblank(dev, crtc->pipe);
5136                 }
5137         }
5138
5139         /*
5140          * IVB workaround: must disable low power watermarks for at least
5141          * one frame before enabling scaling.  LP watermarks can be re-enabled
5142          * when scaling is disabled.
5143          *
5144          * WaCxSRDisabledForSpriteScaling:ivb
5145          */
5146         if (pipe_config->disable_lp_wm) {
5147                 ilk_disable_lp_wm(dev);
5148                 intel_wait_for_vblank(dev, crtc->pipe);
5149         }
5150
5151         /*
5152          * If we're doing a modeset, we're done.  No need to do any pre-vblank
5153          * watermark programming here.
5154          */
5155         if (needs_modeset(&pipe_config->base))
5156                 return;
5157
5158         /*
5159          * For platforms that support atomic watermarks, program the
5160          * 'intermediate' watermarks immediately.  On pre-gen9 platforms, these
5161          * will be the intermediate values that are safe for both pre- and
5162          * post- vblank; when vblank happens, the 'active' values will be set
5163          * to the final 'target' values and we'll do this again to get the
5164          * optimal watermarks.  For gen9+ platforms, the values we program here
5165          * will be the final target values which will get automatically latched
5166          * at vblank time; no further programming will be necessary.
5167          *
5168          * If a platform hasn't been transitioned to atomic watermarks yet,
5169          * we'll continue to update watermarks the old way, if flags tell
5170          * us to.
5171          */
5172         if (dev_priv->display.initial_watermarks != NULL)
5173                 dev_priv->display.initial_watermarks(pipe_config);
5174         else if (pipe_config->update_wm_pre)
5175                 intel_update_watermarks(&crtc->base);
5176 }
5177
5178 static void intel_crtc_disable_planes(struct drm_crtc *crtc, unsigned plane_mask)
5179 {
5180         struct drm_device *dev = crtc->dev;
5181         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5182         struct drm_plane *p;
5183         int pipe = intel_crtc->pipe;
5184
5185         intel_crtc_dpms_overlay_disable(intel_crtc);
5186
5187         drm_for_each_plane_mask(p, dev, plane_mask)
5188                 to_intel_plane(p)->disable_plane(p, crtc);
5189
5190         /*
5191          * FIXME: Once we grow proper nuclear flip support out of this we need
5192          * to compute the mask of flip planes precisely. For the time being
5193          * consider this a flip to a NULL plane.
5194          */
5195         intel_frontbuffer_flip(to_i915(dev), INTEL_FRONTBUFFER_ALL_MASK(pipe));
5196 }
5197
5198 static void intel_encoders_pre_pll_enable(struct drm_crtc *crtc,
5199                                           struct intel_crtc_state *crtc_state,
5200                                           struct drm_atomic_state *old_state)
5201 {
5202         struct drm_connector_state *old_conn_state;
5203         struct drm_connector *conn;
5204         int i;
5205
5206         for_each_connector_in_state(old_state, conn, old_conn_state, i) {
5207                 struct drm_connector_state *conn_state = conn->state;
5208                 struct intel_encoder *encoder =
5209                         to_intel_encoder(conn_state->best_encoder);
5210
5211                 if (conn_state->crtc != crtc)
5212                         continue;
5213
5214                 if (encoder->pre_pll_enable)
5215                         encoder->pre_pll_enable(encoder, crtc_state, conn_state);
5216         }
5217 }
5218
5219 static void intel_encoders_pre_enable(struct drm_crtc *crtc,
5220                                       struct intel_crtc_state *crtc_state,
5221                                       struct drm_atomic_state *old_state)
5222 {
5223         struct drm_connector_state *old_conn_state;
5224         struct drm_connector *conn;
5225         int i;
5226
5227         for_each_connector_in_state(old_state, conn, old_conn_state, i) {
5228                 struct drm_connector_state *conn_state = conn->state;
5229                 struct intel_encoder *encoder =
5230                         to_intel_encoder(conn_state->best_encoder);
5231
5232                 if (conn_state->crtc != crtc)
5233                         continue;
5234
5235                 if (encoder->pre_enable)
5236                         encoder->pre_enable(encoder, crtc_state, conn_state);
5237         }
5238 }
5239
5240 static void intel_encoders_enable(struct drm_crtc *crtc,
5241                                   struct intel_crtc_state *crtc_state,
5242                                   struct drm_atomic_state *old_state)
5243 {
5244         struct drm_connector_state *old_conn_state;
5245         struct drm_connector *conn;
5246         int i;
5247
5248         for_each_connector_in_state(old_state, conn, old_conn_state, i) {
5249                 struct drm_connector_state *conn_state = conn->state;
5250                 struct intel_encoder *encoder =
5251                         to_intel_encoder(conn_state->best_encoder);
5252
5253                 if (conn_state->crtc != crtc)
5254                         continue;
5255
5256                 encoder->enable(encoder, crtc_state, conn_state);
5257                 intel_opregion_notify_encoder(encoder, true);
5258         }
5259 }
5260
5261 static void intel_encoders_disable(struct drm_crtc *crtc,
5262                                    struct intel_crtc_state *old_crtc_state,
5263                                    struct drm_atomic_state *old_state)
5264 {
5265         struct drm_connector_state *old_conn_state;
5266         struct drm_connector *conn;
5267         int i;
5268
5269         for_each_connector_in_state(old_state, conn, old_conn_state, i) {
5270                 struct intel_encoder *encoder =
5271                         to_intel_encoder(old_conn_state->best_encoder);
5272
5273                 if (old_conn_state->crtc != crtc)
5274                         continue;
5275
5276                 intel_opregion_notify_encoder(encoder, false);
5277                 encoder->disable(encoder, old_crtc_state, old_conn_state);
5278         }
5279 }
5280
5281 static void intel_encoders_post_disable(struct drm_crtc *crtc,
5282                                         struct intel_crtc_state *old_crtc_state,
5283                                         struct drm_atomic_state *old_state)
5284 {
5285         struct drm_connector_state *old_conn_state;
5286         struct drm_connector *conn;
5287         int i;
5288
5289         for_each_connector_in_state(old_state, conn, old_conn_state, i) {
5290                 struct intel_encoder *encoder =
5291                         to_intel_encoder(old_conn_state->best_encoder);
5292
5293                 if (old_conn_state->crtc != crtc)
5294                         continue;
5295
5296                 if (encoder->post_disable)
5297                         encoder->post_disable(encoder, old_crtc_state, old_conn_state);
5298         }
5299 }
5300
5301 static void intel_encoders_post_pll_disable(struct drm_crtc *crtc,
5302                                             struct intel_crtc_state *old_crtc_state,
5303                                             struct drm_atomic_state *old_state)
5304 {
5305         struct drm_connector_state *old_conn_state;
5306         struct drm_connector *conn;
5307         int i;
5308
5309         for_each_connector_in_state(old_state, conn, old_conn_state, i) {
5310                 struct intel_encoder *encoder =
5311                         to_intel_encoder(old_conn_state->best_encoder);
5312
5313                 if (old_conn_state->crtc != crtc)
5314                         continue;
5315
5316                 if (encoder->post_pll_disable)
5317                         encoder->post_pll_disable(encoder, old_crtc_state, old_conn_state);
5318         }
5319 }
5320
5321 static void ironlake_crtc_enable(struct intel_crtc_state *pipe_config,
5322                                  struct drm_atomic_state *old_state)
5323 {
5324         struct drm_crtc *crtc = pipe_config->base.crtc;
5325         struct drm_device *dev = crtc->dev;
5326         struct drm_i915_private *dev_priv = to_i915(dev);
5327         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5328         int pipe = intel_crtc->pipe;
5329
5330         if (WARN_ON(intel_crtc->active))
5331                 return;
5332
5333         /*
5334          * Sometimes spurious CPU pipe underruns happen during FDI
5335          * training, at least with VGA+HDMI cloning. Suppress them.
5336          *
5337          * On ILK we get an occasional spurious CPU pipe underruns
5338          * between eDP port A enable and vdd enable. Also PCH port
5339          * enable seems to result in the occasional CPU pipe underrun.
5340          *
5341          * Spurious PCH underruns also occur during PCH enabling.
5342          */
5343         if (intel_crtc->config->has_pch_encoder || IS_GEN5(dev_priv))
5344                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
5345         if (intel_crtc->config->has_pch_encoder)
5346                 intel_set_pch_fifo_underrun_reporting(dev_priv, pipe, false);
5347
5348         if (intel_crtc->config->has_pch_encoder)
5349                 intel_prepare_shared_dpll(intel_crtc);
5350
5351         if (intel_crtc_has_dp_encoder(intel_crtc->config))
5352                 intel_dp_set_m_n(intel_crtc, M1_N1);
5353
5354         intel_set_pipe_timings(intel_crtc);
5355         intel_set_pipe_src_size(intel_crtc);
5356
5357         if (intel_crtc->config->has_pch_encoder) {
5358                 intel_cpu_transcoder_set_m_n(intel_crtc,
5359                                      &intel_crtc->config->fdi_m_n, NULL);
5360         }
5361
5362         ironlake_set_pipeconf(crtc);
5363
5364         intel_crtc->active = true;
5365
5366         intel_encoders_pre_enable(crtc, pipe_config, old_state);
5367
5368         if (intel_crtc->config->has_pch_encoder) {
5369                 /* Note: FDI PLL enabling _must_ be done before we enable the
5370                  * cpu pipes, hence this is separate from all the other fdi/pch
5371                  * enabling. */
5372                 ironlake_fdi_pll_enable(intel_crtc);
5373         } else {
5374                 assert_fdi_tx_disabled(dev_priv, pipe);
5375                 assert_fdi_rx_disabled(dev_priv, pipe);
5376         }
5377
5378         ironlake_pfit_enable(intel_crtc);
5379
5380         /*
5381          * On ILK+ LUT must be loaded before the pipe is running but with
5382          * clocks enabled
5383          */
5384         intel_color_load_luts(&pipe_config->base);
5385
5386         if (dev_priv->display.initial_watermarks != NULL)
5387                 dev_priv->display.initial_watermarks(intel_crtc->config);
5388         intel_enable_pipe(intel_crtc);
5389
5390         if (intel_crtc->config->has_pch_encoder)
5391                 ironlake_pch_enable(crtc);
5392
5393         assert_vblank_disabled(crtc);
5394         drm_crtc_vblank_on(crtc);
5395
5396         intel_encoders_enable(crtc, pipe_config, old_state);
5397
5398         if (HAS_PCH_CPT(dev_priv))
5399                 cpt_verify_modeset(dev, intel_crtc->pipe);
5400
5401         /* Must wait for vblank to avoid spurious PCH FIFO underruns */
5402         if (intel_crtc->config->has_pch_encoder)
5403                 intel_wait_for_vblank(dev, pipe);
5404         intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
5405         intel_set_pch_fifo_underrun_reporting(dev_priv, pipe, true);
5406 }
5407
5408 /* IPS only exists on ULT machines and is tied to pipe A. */
5409 static bool hsw_crtc_supports_ips(struct intel_crtc *crtc)
5410 {
5411         return HAS_IPS(to_i915(crtc->base.dev)) && crtc->pipe == PIPE_A;
5412 }
5413
5414 static void haswell_crtc_enable(struct intel_crtc_state *pipe_config,
5415                                 struct drm_atomic_state *old_state)
5416 {
5417         struct drm_crtc *crtc = pipe_config->base.crtc;
5418         struct drm_device *dev = crtc->dev;
5419         struct drm_i915_private *dev_priv = to_i915(dev);
5420         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5421         int pipe = intel_crtc->pipe, hsw_workaround_pipe;
5422         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
5423
5424         if (WARN_ON(intel_crtc->active))
5425                 return;
5426
5427         if (intel_crtc->config->has_pch_encoder)
5428                 intel_set_pch_fifo_underrun_reporting(dev_priv, TRANSCODER_A,
5429                                                       false);
5430
5431         intel_encoders_pre_pll_enable(crtc, pipe_config, old_state);
5432
5433         if (intel_crtc->config->shared_dpll)
5434                 intel_enable_shared_dpll(intel_crtc);
5435
5436         if (intel_crtc_has_dp_encoder(intel_crtc->config))
5437                 intel_dp_set_m_n(intel_crtc, M1_N1);
5438
5439         if (!transcoder_is_dsi(cpu_transcoder))
5440                 intel_set_pipe_timings(intel_crtc);
5441
5442         intel_set_pipe_src_size(intel_crtc);
5443
5444         if (cpu_transcoder != TRANSCODER_EDP &&
5445             !transcoder_is_dsi(cpu_transcoder)) {
5446                 I915_WRITE(PIPE_MULT(cpu_transcoder),
5447                            intel_crtc->config->pixel_multiplier - 1);
5448         }
5449
5450         if (intel_crtc->config->has_pch_encoder) {
5451                 intel_cpu_transcoder_set_m_n(intel_crtc,
5452                                      &intel_crtc->config->fdi_m_n, NULL);
5453         }
5454
5455         if (!transcoder_is_dsi(cpu_transcoder))
5456                 haswell_set_pipeconf(crtc);
5457
5458         haswell_set_pipemisc(crtc);
5459
5460         intel_color_set_csc(&pipe_config->base);
5461
5462         intel_crtc->active = true;
5463
5464         if (intel_crtc->config->has_pch_encoder)
5465                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
5466         else
5467                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
5468
5469         intel_encoders_pre_enable(crtc, pipe_config, old_state);
5470
5471         if (intel_crtc->config->has_pch_encoder)
5472                 dev_priv->display.fdi_link_train(crtc);
5473
5474         if (!transcoder_is_dsi(cpu_transcoder))
5475                 intel_ddi_enable_pipe_clock(intel_crtc);
5476
5477         if (INTEL_INFO(dev)->gen >= 9)
5478                 skylake_pfit_enable(intel_crtc);
5479         else
5480                 ironlake_pfit_enable(intel_crtc);
5481
5482         /*
5483          * On ILK+ LUT must be loaded before the pipe is running but with
5484          * clocks enabled
5485          */
5486         intel_color_load_luts(&pipe_config->base);
5487
5488         intel_ddi_set_pipe_settings(crtc);
5489         if (!transcoder_is_dsi(cpu_transcoder))
5490                 intel_ddi_enable_transcoder_func(crtc);
5491
5492         if (dev_priv->display.initial_watermarks != NULL)
5493                 dev_priv->display.initial_watermarks(pipe_config);
5494         else
5495                 intel_update_watermarks(crtc);
5496
5497         /* XXX: Do the pipe assertions at the right place for BXT DSI. */
5498         if (!transcoder_is_dsi(cpu_transcoder))
5499                 intel_enable_pipe(intel_crtc);
5500
5501         if (intel_crtc->config->has_pch_encoder)
5502                 lpt_pch_enable(crtc);
5503
5504         if (intel_crtc->config->dp_encoder_is_mst)
5505                 intel_ddi_set_vc_payload_alloc(crtc, true);
5506
5507         assert_vblank_disabled(crtc);
5508         drm_crtc_vblank_on(crtc);
5509
5510         intel_encoders_enable(crtc, pipe_config, old_state);
5511
5512         if (intel_crtc->config->has_pch_encoder) {
5513                 intel_wait_for_vblank(dev, pipe);
5514                 intel_wait_for_vblank(dev, pipe);
5515                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
5516                 intel_set_pch_fifo_underrun_reporting(dev_priv, TRANSCODER_A,
5517                                                       true);
5518         }
5519
5520         /* If we change the relative order between pipe/planes enabling, we need
5521          * to change the workaround. */
5522         hsw_workaround_pipe = pipe_config->hsw_workaround_pipe;
5523         if (IS_HASWELL(dev_priv) && hsw_workaround_pipe != INVALID_PIPE) {
5524                 intel_wait_for_vblank(dev, hsw_workaround_pipe);
5525                 intel_wait_for_vblank(dev, hsw_workaround_pipe);
5526         }
5527 }
5528
5529 static void ironlake_pfit_disable(struct intel_crtc *crtc, bool force)
5530 {
5531         struct drm_device *dev = crtc->base.dev;
5532         struct drm_i915_private *dev_priv = to_i915(dev);
5533         int pipe = crtc->pipe;
5534
5535         /* To avoid upsetting the power well on haswell only disable the pfit if
5536          * it's in use. The hw state code will make sure we get this right. */
5537         if (force || crtc->config->pch_pfit.enabled) {
5538                 I915_WRITE(PF_CTL(pipe), 0);
5539                 I915_WRITE(PF_WIN_POS(pipe), 0);
5540                 I915_WRITE(PF_WIN_SZ(pipe), 0);
5541         }
5542 }
5543
5544 static void ironlake_crtc_disable(struct intel_crtc_state *old_crtc_state,
5545                                   struct drm_atomic_state *old_state)
5546 {
5547         struct drm_crtc *crtc = old_crtc_state->base.crtc;
5548         struct drm_device *dev = crtc->dev;
5549         struct drm_i915_private *dev_priv = to_i915(dev);
5550         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5551         int pipe = intel_crtc->pipe;
5552
5553         /*
5554          * Sometimes spurious CPU pipe underruns happen when the
5555          * pipe is already disabled, but FDI RX/TX is still enabled.
5556          * Happens at least with VGA+HDMI cloning. Suppress them.
5557          */
5558         if (intel_crtc->config->has_pch_encoder) {
5559                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
5560                 intel_set_pch_fifo_underrun_reporting(dev_priv, pipe, false);
5561         }
5562
5563         intel_encoders_disable(crtc, old_crtc_state, old_state);
5564
5565         drm_crtc_vblank_off(crtc);
5566         assert_vblank_disabled(crtc);
5567
5568         intel_disable_pipe(intel_crtc);
5569
5570         ironlake_pfit_disable(intel_crtc, false);
5571
5572         if (intel_crtc->config->has_pch_encoder)
5573                 ironlake_fdi_disable(crtc);
5574
5575         intel_encoders_post_disable(crtc, old_crtc_state, old_state);
5576
5577         if (intel_crtc->config->has_pch_encoder) {
5578                 ironlake_disable_pch_transcoder(dev_priv, pipe);
5579
5580                 if (HAS_PCH_CPT(dev_priv)) {
5581                         i915_reg_t reg;
5582                         u32 temp;
5583
5584                         /* disable TRANS_DP_CTL */
5585                         reg = TRANS_DP_CTL(pipe);
5586                         temp = I915_READ(reg);
5587                         temp &= ~(TRANS_DP_OUTPUT_ENABLE |
5588                                   TRANS_DP_PORT_SEL_MASK);
5589                         temp |= TRANS_DP_PORT_SEL_NONE;
5590                         I915_WRITE(reg, temp);
5591
5592                         /* disable DPLL_SEL */
5593                         temp = I915_READ(PCH_DPLL_SEL);
5594                         temp &= ~(TRANS_DPLL_ENABLE(pipe) | TRANS_DPLLB_SEL(pipe));
5595                         I915_WRITE(PCH_DPLL_SEL, temp);
5596                 }
5597
5598                 ironlake_fdi_pll_disable(intel_crtc);
5599         }
5600
5601         intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
5602         intel_set_pch_fifo_underrun_reporting(dev_priv, pipe, true);
5603 }
5604
5605 static void haswell_crtc_disable(struct intel_crtc_state *old_crtc_state,
5606                                  struct drm_atomic_state *old_state)
5607 {
5608         struct drm_crtc *crtc = old_crtc_state->base.crtc;
5609         struct drm_device *dev = crtc->dev;
5610         struct drm_i915_private *dev_priv = to_i915(dev);
5611         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5612         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
5613
5614         if (intel_crtc->config->has_pch_encoder)
5615                 intel_set_pch_fifo_underrun_reporting(dev_priv, TRANSCODER_A,
5616                                                       false);
5617
5618         intel_encoders_disable(crtc, old_crtc_state, old_state);
5619
5620         drm_crtc_vblank_off(crtc);
5621         assert_vblank_disabled(crtc);
5622
5623         /* XXX: Do the pipe assertions at the right place for BXT DSI. */
5624         if (!transcoder_is_dsi(cpu_transcoder))
5625                 intel_disable_pipe(intel_crtc);
5626
5627         if (intel_crtc->config->dp_encoder_is_mst)
5628                 intel_ddi_set_vc_payload_alloc(crtc, false);
5629
5630         if (!transcoder_is_dsi(cpu_transcoder))
5631                 intel_ddi_disable_transcoder_func(dev_priv, cpu_transcoder);
5632
5633         if (INTEL_INFO(dev)->gen >= 9)
5634                 skylake_scaler_disable(intel_crtc);
5635         else
5636                 ironlake_pfit_disable(intel_crtc, false);
5637
5638         if (!transcoder_is_dsi(cpu_transcoder))
5639                 intel_ddi_disable_pipe_clock(intel_crtc);
5640
5641         intel_encoders_post_disable(crtc, old_crtc_state, old_state);
5642
5643         if (old_crtc_state->has_pch_encoder)
5644                 intel_set_pch_fifo_underrun_reporting(dev_priv, TRANSCODER_A,
5645                                                       true);
5646 }
5647
5648 static void i9xx_pfit_enable(struct intel_crtc *crtc)
5649 {
5650         struct drm_device *dev = crtc->base.dev;
5651         struct drm_i915_private *dev_priv = to_i915(dev);
5652         struct intel_crtc_state *pipe_config = crtc->config;
5653
5654         if (!pipe_config->gmch_pfit.control)
5655                 return;
5656
5657         /*
5658          * The panel fitter should only be adjusted whilst the pipe is disabled,
5659          * according to register description and PRM.
5660          */
5661         WARN_ON(I915_READ(PFIT_CONTROL) & PFIT_ENABLE);
5662         assert_pipe_disabled(dev_priv, crtc->pipe);
5663
5664         I915_WRITE(PFIT_PGM_RATIOS, pipe_config->gmch_pfit.pgm_ratios);
5665         I915_WRITE(PFIT_CONTROL, pipe_config->gmch_pfit.control);
5666
5667         /* Border color in case we don't scale up to the full screen. Black by
5668          * default, change to something else for debugging. */
5669         I915_WRITE(BCLRPAT(crtc->pipe), 0);
5670 }
5671
5672 static enum intel_display_power_domain port_to_power_domain(enum port port)
5673 {
5674         switch (port) {
5675         case PORT_A:
5676                 return POWER_DOMAIN_PORT_DDI_A_LANES;
5677         case PORT_B:
5678                 return POWER_DOMAIN_PORT_DDI_B_LANES;
5679         case PORT_C:
5680                 return POWER_DOMAIN_PORT_DDI_C_LANES;
5681         case PORT_D:
5682                 return POWER_DOMAIN_PORT_DDI_D_LANES;
5683         case PORT_E:
5684                 return POWER_DOMAIN_PORT_DDI_E_LANES;
5685         default:
5686                 MISSING_CASE(port);
5687                 return POWER_DOMAIN_PORT_OTHER;
5688         }
5689 }
5690
5691 static enum intel_display_power_domain port_to_aux_power_domain(enum port port)
5692 {
5693         switch (port) {
5694         case PORT_A:
5695                 return POWER_DOMAIN_AUX_A;
5696         case PORT_B:
5697                 return POWER_DOMAIN_AUX_B;
5698         case PORT_C:
5699                 return POWER_DOMAIN_AUX_C;
5700         case PORT_D:
5701                 return POWER_DOMAIN_AUX_D;
5702         case PORT_E:
5703                 /* FIXME: Check VBT for actual wiring of PORT E */
5704                 return POWER_DOMAIN_AUX_D;
5705         default:
5706                 MISSING_CASE(port);
5707                 return POWER_DOMAIN_AUX_A;
5708         }
5709 }
5710
5711 enum intel_display_power_domain
5712 intel_display_port_power_domain(struct intel_encoder *intel_encoder)
5713 {
5714         struct drm_i915_private *dev_priv = to_i915(intel_encoder->base.dev);
5715         struct intel_digital_port *intel_dig_port;
5716
5717         switch (intel_encoder->type) {
5718         case INTEL_OUTPUT_UNKNOWN:
5719                 /* Only DDI platforms should ever use this output type */
5720                 WARN_ON_ONCE(!HAS_DDI(dev_priv));
5721         case INTEL_OUTPUT_DP:
5722         case INTEL_OUTPUT_HDMI:
5723         case INTEL_OUTPUT_EDP:
5724                 intel_dig_port = enc_to_dig_port(&intel_encoder->base);
5725                 return port_to_power_domain(intel_dig_port->port);
5726         case INTEL_OUTPUT_DP_MST:
5727                 intel_dig_port = enc_to_mst(&intel_encoder->base)->primary;
5728                 return port_to_power_domain(intel_dig_port->port);
5729         case INTEL_OUTPUT_ANALOG:
5730                 return POWER_DOMAIN_PORT_CRT;
5731         case INTEL_OUTPUT_DSI:
5732                 return POWER_DOMAIN_PORT_DSI;
5733         default:
5734                 return POWER_DOMAIN_PORT_OTHER;
5735         }
5736 }
5737
5738 enum intel_display_power_domain
5739 intel_display_port_aux_power_domain(struct intel_encoder *intel_encoder)
5740 {
5741         struct drm_i915_private *dev_priv = to_i915(intel_encoder->base.dev);
5742         struct intel_digital_port *intel_dig_port;
5743
5744         switch (intel_encoder->type) {
5745         case INTEL_OUTPUT_UNKNOWN:
5746         case INTEL_OUTPUT_HDMI:
5747                 /*
5748                  * Only DDI platforms should ever use these output types.
5749                  * We can get here after the HDMI detect code has already set
5750                  * the type of the shared encoder. Since we can't be sure
5751                  * what's the status of the given connectors, play safe and
5752                  * run the DP detection too.
5753                  */
5754                 WARN_ON_ONCE(!HAS_DDI(dev_priv));
5755         case INTEL_OUTPUT_DP:
5756         case INTEL_OUTPUT_EDP:
5757                 intel_dig_port = enc_to_dig_port(&intel_encoder->base);
5758                 return port_to_aux_power_domain(intel_dig_port->port);
5759         case INTEL_OUTPUT_DP_MST:
5760                 intel_dig_port = enc_to_mst(&intel_encoder->base)->primary;
5761                 return port_to_aux_power_domain(intel_dig_port->port);
5762         default:
5763                 MISSING_CASE(intel_encoder->type);
5764                 return POWER_DOMAIN_AUX_A;
5765         }
5766 }
5767
5768 static unsigned long get_crtc_power_domains(struct drm_crtc *crtc,
5769                                             struct intel_crtc_state *crtc_state)
5770 {
5771         struct drm_device *dev = crtc->dev;
5772         struct drm_encoder *encoder;
5773         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5774         enum pipe pipe = intel_crtc->pipe;
5775         unsigned long mask;
5776         enum transcoder transcoder = crtc_state->cpu_transcoder;
5777
5778         if (!crtc_state->base.active)
5779                 return 0;
5780
5781         mask = BIT(POWER_DOMAIN_PIPE(pipe));
5782         mask |= BIT(POWER_DOMAIN_TRANSCODER(transcoder));
5783         if (crtc_state->pch_pfit.enabled ||
5784             crtc_state->pch_pfit.force_thru)
5785                 mask |= BIT(POWER_DOMAIN_PIPE_PANEL_FITTER(pipe));
5786
5787         drm_for_each_encoder_mask(encoder, dev, crtc_state->base.encoder_mask) {
5788                 struct intel_encoder *intel_encoder = to_intel_encoder(encoder);
5789
5790                 mask |= BIT(intel_display_port_power_domain(intel_encoder));
5791         }
5792
5793         if (crtc_state->shared_dpll)
5794                 mask |= BIT(POWER_DOMAIN_PLLS);
5795
5796         return mask;
5797 }
5798
5799 static unsigned long
5800 modeset_get_crtc_power_domains(struct drm_crtc *crtc,
5801                                struct intel_crtc_state *crtc_state)
5802 {
5803         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
5804         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5805         enum intel_display_power_domain domain;
5806         unsigned long domains, new_domains, old_domains;
5807
5808         old_domains = intel_crtc->enabled_power_domains;
5809         intel_crtc->enabled_power_domains = new_domains =
5810                 get_crtc_power_domains(crtc, crtc_state);
5811
5812         domains = new_domains & ~old_domains;
5813
5814         for_each_power_domain(domain, domains)
5815                 intel_display_power_get(dev_priv, domain);
5816
5817         return old_domains & ~new_domains;
5818 }
5819
5820 static void modeset_put_power_domains(struct drm_i915_private *dev_priv,
5821                                       unsigned long domains)
5822 {
5823         enum intel_display_power_domain domain;
5824
5825         for_each_power_domain(domain, domains)
5826                 intel_display_power_put(dev_priv, domain);
5827 }
5828
5829 static int intel_compute_max_dotclk(struct drm_i915_private *dev_priv)
5830 {
5831         int max_cdclk_freq = dev_priv->max_cdclk_freq;
5832
5833         if (INTEL_INFO(dev_priv)->gen >= 9 ||
5834             IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv))
5835                 return max_cdclk_freq;
5836         else if (IS_CHERRYVIEW(dev_priv))
5837                 return max_cdclk_freq*95/100;
5838         else if (INTEL_INFO(dev_priv)->gen < 4)
5839                 return 2*max_cdclk_freq*90/100;
5840         else
5841                 return max_cdclk_freq*90/100;
5842 }
5843
5844 static int skl_calc_cdclk(int max_pixclk, int vco);
5845
5846 static void intel_update_max_cdclk(struct drm_device *dev)
5847 {
5848         struct drm_i915_private *dev_priv = to_i915(dev);
5849
5850         if (IS_SKYLAKE(dev_priv) || IS_KABYLAKE(dev_priv)) {
5851                 u32 limit = I915_READ(SKL_DFSM) & SKL_DFSM_CDCLK_LIMIT_MASK;
5852                 int max_cdclk, vco;
5853
5854                 vco = dev_priv->skl_preferred_vco_freq;
5855                 WARN_ON(vco != 8100000 && vco != 8640000);
5856
5857                 /*
5858                  * Use the lower (vco 8640) cdclk values as a
5859                  * first guess. skl_calc_cdclk() will correct it
5860                  * if the preferred vco is 8100 instead.
5861                  */
5862                 if (limit == SKL_DFSM_CDCLK_LIMIT_675)
5863                         max_cdclk = 617143;
5864                 else if (limit == SKL_DFSM_CDCLK_LIMIT_540)
5865                         max_cdclk = 540000;
5866                 else if (limit == SKL_DFSM_CDCLK_LIMIT_450)
5867                         max_cdclk = 432000;
5868                 else
5869                         max_cdclk = 308571;
5870
5871                 dev_priv->max_cdclk_freq = skl_calc_cdclk(max_cdclk, vco);
5872         } else if (IS_BROXTON(dev_priv)) {
5873                 dev_priv->max_cdclk_freq = 624000;
5874         } else if (IS_BROADWELL(dev_priv))  {
5875                 /*
5876                  * FIXME with extra cooling we can allow
5877                  * 540 MHz for ULX and 675 Mhz for ULT.
5878                  * How can we know if extra cooling is
5879                  * available? PCI ID, VTB, something else?
5880                  */
5881                 if (I915_READ(FUSE_STRAP) & HSW_CDCLK_LIMIT)
5882                         dev_priv->max_cdclk_freq = 450000;
5883                 else if (IS_BDW_ULX(dev_priv))
5884                         dev_priv->max_cdclk_freq = 450000;
5885                 else if (IS_BDW_ULT(dev_priv))
5886                         dev_priv->max_cdclk_freq = 540000;
5887                 else
5888                         dev_priv->max_cdclk_freq = 675000;
5889         } else if (IS_CHERRYVIEW(dev_priv)) {
5890                 dev_priv->max_cdclk_freq = 320000;
5891         } else if (IS_VALLEYVIEW(dev_priv)) {
5892                 dev_priv->max_cdclk_freq = 400000;
5893         } else {
5894                 /* otherwise assume cdclk is fixed */
5895                 dev_priv->max_cdclk_freq = dev_priv->cdclk_freq;
5896         }
5897
5898         dev_priv->max_dotclk_freq = intel_compute_max_dotclk(dev_priv);
5899
5900         DRM_DEBUG_DRIVER("Max CD clock rate: %d kHz\n",
5901                          dev_priv->max_cdclk_freq);
5902
5903         DRM_DEBUG_DRIVER("Max dotclock rate: %d kHz\n",
5904                          dev_priv->max_dotclk_freq);
5905 }
5906
5907 static void intel_update_cdclk(struct drm_device *dev)
5908 {
5909         struct drm_i915_private *dev_priv = to_i915(dev);
5910
5911         dev_priv->cdclk_freq = dev_priv->display.get_display_clock_speed(dev);
5912
5913         if (INTEL_GEN(dev_priv) >= 9)
5914                 DRM_DEBUG_DRIVER("Current CD clock rate: %d kHz, VCO: %d kHz, ref: %d kHz\n",
5915                                  dev_priv->cdclk_freq, dev_priv->cdclk_pll.vco,
5916                                  dev_priv->cdclk_pll.ref);
5917         else
5918                 DRM_DEBUG_DRIVER("Current CD clock rate: %d kHz\n",
5919                                  dev_priv->cdclk_freq);
5920
5921         /*
5922          * 9:0 CMBUS [sic] CDCLK frequency (cdfreq):
5923          * Programmng [sic] note: bit[9:2] should be programmed to the number
5924          * of cdclk that generates 4MHz reference clock freq which is used to
5925          * generate GMBus clock. This will vary with the cdclk freq.
5926          */
5927         if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
5928                 I915_WRITE(GMBUSFREQ_VLV, DIV_ROUND_UP(dev_priv->cdclk_freq, 1000));
5929 }
5930
5931 /* convert from kHz to .1 fixpoint MHz with -1MHz offset */
5932 static int skl_cdclk_decimal(int cdclk)
5933 {
5934         return DIV_ROUND_CLOSEST(cdclk - 1000, 500);
5935 }
5936
5937 static int bxt_de_pll_vco(struct drm_i915_private *dev_priv, int cdclk)
5938 {
5939         int ratio;
5940
5941         if (cdclk == dev_priv->cdclk_pll.ref)
5942                 return 0;
5943
5944         switch (cdclk) {
5945         default:
5946                 MISSING_CASE(cdclk);
5947         case 144000:
5948         case 288000:
5949         case 384000:
5950         case 576000:
5951                 ratio = 60;
5952                 break;
5953         case 624000:
5954                 ratio = 65;
5955                 break;
5956         }
5957
5958         return dev_priv->cdclk_pll.ref * ratio;
5959 }
5960
5961 static void bxt_de_pll_disable(struct drm_i915_private *dev_priv)
5962 {
5963         I915_WRITE(BXT_DE_PLL_ENABLE, 0);
5964
5965         /* Timeout 200us */
5966         if (intel_wait_for_register(dev_priv,
5967                                     BXT_DE_PLL_ENABLE, BXT_DE_PLL_LOCK, 0,
5968                                     1))
5969                 DRM_ERROR("timeout waiting for DE PLL unlock\n");
5970
5971         dev_priv->cdclk_pll.vco = 0;
5972 }
5973
5974 static void bxt_de_pll_enable(struct drm_i915_private *dev_priv, int vco)
5975 {
5976         int ratio = DIV_ROUND_CLOSEST(vco, dev_priv->cdclk_pll.ref);
5977         u32 val;
5978
5979         val = I915_READ(BXT_DE_PLL_CTL);
5980         val &= ~BXT_DE_PLL_RATIO_MASK;
5981         val |= BXT_DE_PLL_RATIO(ratio);
5982         I915_WRITE(BXT_DE_PLL_CTL, val);
5983
5984         I915_WRITE(BXT_DE_PLL_ENABLE, BXT_DE_PLL_PLL_ENABLE);
5985
5986         /* Timeout 200us */
5987         if (intel_wait_for_register(dev_priv,
5988                                     BXT_DE_PLL_ENABLE,
5989                                     BXT_DE_PLL_LOCK,
5990                                     BXT_DE_PLL_LOCK,
5991                                     1))
5992                 DRM_ERROR("timeout waiting for DE PLL lock\n");
5993
5994         dev_priv->cdclk_pll.vco = vco;
5995 }
5996
5997 static void bxt_set_cdclk(struct drm_i915_private *dev_priv, int cdclk)
5998 {
5999         u32 val, divider;
6000         int vco, ret;
6001
6002         vco = bxt_de_pll_vco(dev_priv, cdclk);
6003
6004         DRM_DEBUG_DRIVER("Changing CDCLK to %d kHz (VCO %d kHz)\n", cdclk, vco);
6005
6006         /* cdclk = vco / 2 / div{1,1.5,2,4} */
6007         switch (DIV_ROUND_CLOSEST(vco, cdclk)) {
6008         case 8:
6009                 divider = BXT_CDCLK_CD2X_DIV_SEL_4;
6010                 break;
6011         case 4:
6012                 divider = BXT_CDCLK_CD2X_DIV_SEL_2;
6013                 break;
6014         case 3:
6015                 divider = BXT_CDCLK_CD2X_DIV_SEL_1_5;
6016                 break;
6017         case 2:
6018                 divider = BXT_CDCLK_CD2X_DIV_SEL_1;
6019                 break;
6020         default:
6021                 WARN_ON(cdclk != dev_priv->cdclk_pll.ref);
6022                 WARN_ON(vco != 0);
6023
6024                 divider = BXT_CDCLK_CD2X_DIV_SEL_1;
6025                 break;
6026         }
6027
6028         /* Inform power controller of upcoming frequency change */
6029         mutex_lock(&dev_priv->rps.hw_lock);
6030         ret = sandybridge_pcode_write(dev_priv, HSW_PCODE_DE_WRITE_FREQ_REQ,
6031                                       0x80000000);
6032         mutex_unlock(&dev_priv->rps.hw_lock);
6033
6034         if (ret) {
6035                 DRM_ERROR("PCode CDCLK freq change notify failed (err %d, freq %d)\n",
6036                           ret, cdclk);
6037                 return;
6038         }
6039
6040         if (dev_priv->cdclk_pll.vco != 0 &&
6041             dev_priv->cdclk_pll.vco != vco)
6042                 bxt_de_pll_disable(dev_priv);
6043
6044         if (dev_priv->cdclk_pll.vco != vco)
6045                 bxt_de_pll_enable(dev_priv, vco);
6046
6047         val = divider | skl_cdclk_decimal(cdclk);
6048         /*
6049          * FIXME if only the cd2x divider needs changing, it could be done
6050          * without shutting off the pipe (if only one pipe is active).
6051          */
6052         val |= BXT_CDCLK_CD2X_PIPE_NONE;
6053         /*
6054          * Disable SSA Precharge when CD clock frequency < 500 MHz,
6055          * enable otherwise.
6056          */
6057         if (cdclk >= 500000)
6058                 val |= BXT_CDCLK_SSA_PRECHARGE_ENABLE;
6059         I915_WRITE(CDCLK_CTL, val);
6060
6061         mutex_lock(&dev_priv->rps.hw_lock);
6062         ret = sandybridge_pcode_write(dev_priv, HSW_PCODE_DE_WRITE_FREQ_REQ,
6063                                       DIV_ROUND_UP(cdclk, 25000));
6064         mutex_unlock(&dev_priv->rps.hw_lock);
6065
6066         if (ret) {
6067                 DRM_ERROR("PCode CDCLK freq set failed, (err %d, freq %d)\n",
6068                           ret, cdclk);
6069                 return;
6070         }
6071
6072         intel_update_cdclk(&dev_priv->drm);
6073 }
6074
6075 static void bxt_sanitize_cdclk(struct drm_i915_private *dev_priv)
6076 {
6077         u32 cdctl, expected;
6078
6079         intel_update_cdclk(&dev_priv->drm);
6080
6081         if (dev_priv->cdclk_pll.vco == 0 ||
6082             dev_priv->cdclk_freq == dev_priv->cdclk_pll.ref)
6083                 goto sanitize;
6084
6085         /* DPLL okay; verify the cdclock
6086          *
6087          * Some BIOS versions leave an incorrect decimal frequency value and
6088          * set reserved MBZ bits in CDCLK_CTL at least during exiting from S4,
6089          * so sanitize this register.
6090          */
6091         cdctl = I915_READ(CDCLK_CTL);
6092         /*
6093          * Let's ignore the pipe field, since BIOS could have configured the
6094          * dividers both synching to an active pipe, or asynchronously
6095          * (PIPE_NONE).
6096          */
6097         cdctl &= ~BXT_CDCLK_CD2X_PIPE_NONE;
6098
6099         expected = (cdctl & BXT_CDCLK_CD2X_DIV_SEL_MASK) |
6100                    skl_cdclk_decimal(dev_priv->cdclk_freq);
6101         /*
6102          * Disable SSA Precharge when CD clock frequency < 500 MHz,
6103          * enable otherwise.
6104          */
6105         if (dev_priv->cdclk_freq >= 500000)
6106                 expected |= BXT_CDCLK_SSA_PRECHARGE_ENABLE;
6107
6108         if (cdctl == expected)
6109                 /* All well; nothing to sanitize */
6110                 return;
6111
6112 sanitize:
6113         DRM_DEBUG_KMS("Sanitizing cdclk programmed by pre-os\n");
6114
6115         /* force cdclk programming */
6116         dev_priv->cdclk_freq = 0;
6117
6118         /* force full PLL disable + enable */
6119         dev_priv->cdclk_pll.vco = -1;
6120 }
6121
6122 void bxt_init_cdclk(struct drm_i915_private *dev_priv)
6123 {
6124         bxt_sanitize_cdclk(dev_priv);
6125
6126         if (dev_priv->cdclk_freq != 0 && dev_priv->cdclk_pll.vco != 0)
6127                 return;
6128
6129         /*
6130          * FIXME:
6131          * - The initial CDCLK needs to be read from VBT.
6132          *   Need to make this change after VBT has changes for BXT.
6133          */
6134         bxt_set_cdclk(dev_priv, bxt_calc_cdclk(0));
6135 }
6136
6137 void bxt_uninit_cdclk(struct drm_i915_private *dev_priv)
6138 {
6139         bxt_set_cdclk(dev_priv, dev_priv->cdclk_pll.ref);
6140 }
6141
6142 static int skl_calc_cdclk(int max_pixclk, int vco)
6143 {
6144         if (vco == 8640000) {
6145                 if (max_pixclk > 540000)
6146                         return 617143;
6147                 else if (max_pixclk > 432000)
6148                         return 540000;
6149                 else if (max_pixclk > 308571)
6150                         return 432000;
6151                 else
6152                         return 308571;
6153         } else {
6154                 if (max_pixclk > 540000)
6155                         return 675000;
6156                 else if (max_pixclk > 450000)
6157                         return 540000;
6158                 else if (max_pixclk > 337500)
6159                         return 450000;
6160                 else
6161                         return 337500;
6162         }
6163 }
6164
6165 static void
6166 skl_dpll0_update(struct drm_i915_private *dev_priv)
6167 {
6168         u32 val;
6169
6170         dev_priv->cdclk_pll.ref = 24000;
6171         dev_priv->cdclk_pll.vco = 0;
6172
6173         val = I915_READ(LCPLL1_CTL);
6174         if ((val & LCPLL_PLL_ENABLE) == 0)
6175                 return;
6176
6177         if (WARN_ON((val & LCPLL_PLL_LOCK) == 0))
6178                 return;
6179
6180         val = I915_READ(DPLL_CTRL1);
6181
6182         if (WARN_ON((val & (DPLL_CTRL1_HDMI_MODE(SKL_DPLL0) |
6183                             DPLL_CTRL1_SSC(SKL_DPLL0) |
6184                             DPLL_CTRL1_OVERRIDE(SKL_DPLL0))) !=
6185                     DPLL_CTRL1_OVERRIDE(SKL_DPLL0)))
6186                 return;
6187
6188         switch (val & DPLL_CTRL1_LINK_RATE_MASK(SKL_DPLL0)) {
6189         case DPLL_CTRL1_LINK_RATE(DPLL_CTRL1_LINK_RATE_810, SKL_DPLL0):
6190         case DPLL_CTRL1_LINK_RATE(DPLL_CTRL1_LINK_RATE_1350, SKL_DPLL0):
6191         case DPLL_CTRL1_LINK_RATE(DPLL_CTRL1_LINK_RATE_1620, SKL_DPLL0):
6192         case DPLL_CTRL1_LINK_RATE(DPLL_CTRL1_LINK_RATE_2700, SKL_DPLL0):
6193                 dev_priv->cdclk_pll.vco = 8100000;
6194                 break;
6195         case DPLL_CTRL1_LINK_RATE(DPLL_CTRL1_LINK_RATE_1080, SKL_DPLL0):
6196         case DPLL_CTRL1_LINK_RATE(DPLL_CTRL1_LINK_RATE_2160, SKL_DPLL0):
6197                 dev_priv->cdclk_pll.vco = 8640000;
6198                 break;
6199         default:
6200                 MISSING_CASE(val & DPLL_CTRL1_LINK_RATE_MASK(SKL_DPLL0));
6201                 break;
6202         }
6203 }
6204
6205 void skl_set_preferred_cdclk_vco(struct drm_i915_private *dev_priv, int vco)
6206 {
6207         bool changed = dev_priv->skl_preferred_vco_freq != vco;
6208
6209         dev_priv->skl_preferred_vco_freq = vco;
6210
6211         if (changed)
6212                 intel_update_max_cdclk(&dev_priv->drm);
6213 }
6214
6215 static void
6216 skl_dpll0_enable(struct drm_i915_private *dev_priv, int vco)
6217 {
6218         int min_cdclk = skl_calc_cdclk(0, vco);
6219         u32 val;
6220
6221         WARN_ON(vco != 8100000 && vco != 8640000);
6222
6223         /* select the minimum CDCLK before enabling DPLL 0 */
6224         val = CDCLK_FREQ_337_308 | skl_cdclk_decimal(min_cdclk);
6225         I915_WRITE(CDCLK_CTL, val);
6226         POSTING_READ(CDCLK_CTL);
6227
6228         /*
6229          * We always enable DPLL0 with the lowest link rate possible, but still
6230          * taking into account the VCO required to operate the eDP panel at the
6231          * desired frequency. The usual DP link rates operate with a VCO of
6232          * 8100 while the eDP 1.4 alternate link rates need a VCO of 8640.
6233          * The modeset code is responsible for the selection of the exact link
6234          * rate later on, with the constraint of choosing a frequency that
6235          * works with vco.
6236          */
6237         val = I915_READ(DPLL_CTRL1);
6238
6239         val &= ~(DPLL_CTRL1_HDMI_MODE(SKL_DPLL0) | DPLL_CTRL1_SSC(SKL_DPLL0) |
6240                  DPLL_CTRL1_LINK_RATE_MASK(SKL_DPLL0));
6241         val |= DPLL_CTRL1_OVERRIDE(SKL_DPLL0);
6242         if (vco == 8640000)
6243                 val |= DPLL_CTRL1_LINK_RATE(DPLL_CTRL1_LINK_RATE_1080,
6244                                             SKL_DPLL0);
6245         else
6246                 val |= DPLL_CTRL1_LINK_RATE(DPLL_CTRL1_LINK_RATE_810,
6247                                             SKL_DPLL0);
6248
6249         I915_WRITE(DPLL_CTRL1, val);
6250         POSTING_READ(DPLL_CTRL1);
6251
6252         I915_WRITE(LCPLL1_CTL, I915_READ(LCPLL1_CTL) | LCPLL_PLL_ENABLE);
6253
6254         if (intel_wait_for_register(dev_priv,
6255                                     LCPLL1_CTL, LCPLL_PLL_LOCK, LCPLL_PLL_LOCK,
6256                                     5))
6257                 DRM_ERROR("DPLL0 not locked\n");
6258
6259         dev_priv->cdclk_pll.vco = vco;
6260
6261         /* We'll want to keep using the current vco from now on. */
6262         skl_set_preferred_cdclk_vco(dev_priv, vco);
6263 }
6264
6265 static void
6266 skl_dpll0_disable(struct drm_i915_private *dev_priv)
6267 {
6268         I915_WRITE(LCPLL1_CTL, I915_READ(LCPLL1_CTL) & ~LCPLL_PLL_ENABLE);
6269         if (intel_wait_for_register(dev_priv,
6270                                    LCPLL1_CTL, LCPLL_PLL_LOCK, 0,
6271                                    1))
6272                 DRM_ERROR("Couldn't disable DPLL0\n");
6273
6274         dev_priv->cdclk_pll.vco = 0;
6275 }
6276
6277 static bool skl_cdclk_pcu_ready(struct drm_i915_private *dev_priv)
6278 {
6279         int ret;
6280         u32 val;
6281
6282         /* inform PCU we want to change CDCLK */
6283         val = SKL_CDCLK_PREPARE_FOR_CHANGE;
6284         mutex_lock(&dev_priv->rps.hw_lock);
6285         ret = sandybridge_pcode_read(dev_priv, SKL_PCODE_CDCLK_CONTROL, &val);
6286         mutex_unlock(&dev_priv->rps.hw_lock);
6287
6288         return ret == 0 && (val & SKL_CDCLK_READY_FOR_CHANGE);
6289 }
6290
6291 static bool skl_cdclk_wait_for_pcu_ready(struct drm_i915_private *dev_priv)
6292 {
6293         return _wait_for(skl_cdclk_pcu_ready(dev_priv), 3000, 10) == 0;
6294 }
6295
6296 static void skl_set_cdclk(struct drm_i915_private *dev_priv, int cdclk, int vco)
6297 {
6298         struct drm_device *dev = &dev_priv->drm;
6299         u32 freq_select, pcu_ack;
6300
6301         WARN_ON((cdclk == 24000) != (vco == 0));
6302
6303         DRM_DEBUG_DRIVER("Changing CDCLK to %d kHz (VCO %d kHz)\n", cdclk, vco);
6304
6305         if (!skl_cdclk_wait_for_pcu_ready(dev_priv)) {
6306                 DRM_ERROR("failed to inform PCU about cdclk change\n");
6307                 return;
6308         }
6309
6310         /* set CDCLK_CTL */
6311         switch (cdclk) {
6312         case 450000:
6313         case 432000:
6314                 freq_select = CDCLK_FREQ_450_432;
6315                 pcu_ack = 1;
6316                 break;
6317         case 540000:
6318                 freq_select = CDCLK_FREQ_540;
6319                 pcu_ack = 2;
6320                 break;
6321         case 308571:
6322         case 337500:
6323         default:
6324                 freq_select = CDCLK_FREQ_337_308;
6325                 pcu_ack = 0;
6326                 break;
6327         case 617143:
6328         case 675000:
6329                 freq_select = CDCLK_FREQ_675_617;
6330                 pcu_ack = 3;
6331                 break;
6332         }
6333
6334         if (dev_priv->cdclk_pll.vco != 0 &&
6335             dev_priv->cdclk_pll.vco != vco)
6336                 skl_dpll0_disable(dev_priv);
6337
6338         if (dev_priv->cdclk_pll.vco != vco)
6339                 skl_dpll0_enable(dev_priv, vco);
6340
6341         I915_WRITE(CDCLK_CTL, freq_select | skl_cdclk_decimal(cdclk));
6342         POSTING_READ(CDCLK_CTL);
6343
6344         /* inform PCU of the change */
6345         mutex_lock(&dev_priv->rps.hw_lock);
6346         sandybridge_pcode_write(dev_priv, SKL_PCODE_CDCLK_CONTROL, pcu_ack);
6347         mutex_unlock(&dev_priv->rps.hw_lock);
6348
6349         intel_update_cdclk(dev);
6350 }
6351
6352 static void skl_sanitize_cdclk(struct drm_i915_private *dev_priv);
6353
6354 void skl_uninit_cdclk(struct drm_i915_private *dev_priv)
6355 {
6356         skl_set_cdclk(dev_priv, dev_priv->cdclk_pll.ref, 0);
6357 }
6358
6359 void skl_init_cdclk(struct drm_i915_private *dev_priv)
6360 {
6361         int cdclk, vco;
6362
6363         skl_sanitize_cdclk(dev_priv);
6364
6365         if (dev_priv->cdclk_freq != 0 && dev_priv->cdclk_pll.vco != 0) {
6366                 /*
6367                  * Use the current vco as our initial
6368                  * guess as to what the preferred vco is.
6369                  */
6370                 if (dev_priv->skl_preferred_vco_freq == 0)
6371                         skl_set_preferred_cdclk_vco(dev_priv,
6372                                                     dev_priv->cdclk_pll.vco);
6373                 return;
6374         }
6375
6376         vco = dev_priv->skl_preferred_vco_freq;
6377         if (vco == 0)
6378                 vco = 8100000;
6379         cdclk = skl_calc_cdclk(0, vco);
6380
6381         skl_set_cdclk(dev_priv, cdclk, vco);
6382 }
6383
6384 static void skl_sanitize_cdclk(struct drm_i915_private *dev_priv)
6385 {
6386         uint32_t cdctl, expected;
6387
6388         /*
6389          * check if the pre-os intialized the display
6390          * There is SWF18 scratchpad register defined which is set by the
6391          * pre-os which can be used by the OS drivers to check the status
6392          */
6393         if ((I915_READ(SWF_ILK(0x18)) & 0x00FFFFFF) == 0)
6394                 goto sanitize;
6395
6396         intel_update_cdclk(&dev_priv->drm);
6397         /* Is PLL enabled and locked ? */
6398         if (dev_priv->cdclk_pll.vco == 0 ||
6399             dev_priv->cdclk_freq == dev_priv->cdclk_pll.ref)
6400                 goto sanitize;
6401
6402         /* DPLL okay; verify the cdclock
6403          *
6404          * Noticed in some instances that the freq selection is correct but
6405          * decimal part is programmed wrong from BIOS where pre-os does not
6406          * enable display. Verify the same as well.
6407          */
6408         cdctl = I915_READ(CDCLK_CTL);
6409         expected = (cdctl & CDCLK_FREQ_SEL_MASK) |
6410                 skl_cdclk_decimal(dev_priv->cdclk_freq);
6411         if (cdctl == expected)
6412                 /* All well; nothing to sanitize */
6413                 return;
6414
6415 sanitize:
6416         DRM_DEBUG_KMS("Sanitizing cdclk programmed by pre-os\n");
6417
6418         /* force cdclk programming */
6419         dev_priv->cdclk_freq = 0;
6420         /* force full PLL disable + enable */
6421         dev_priv->cdclk_pll.vco = -1;
6422 }
6423
6424 /* Adjust CDclk dividers to allow high res or save power if possible */
6425 static void valleyview_set_cdclk(struct drm_device *dev, int cdclk)
6426 {
6427         struct drm_i915_private *dev_priv = to_i915(dev);
6428         u32 val, cmd;
6429
6430         WARN_ON(dev_priv->display.get_display_clock_speed(dev)
6431                                         != dev_priv->cdclk_freq);
6432
6433         if (cdclk >= 320000) /* jump to highest voltage for 400MHz too */
6434                 cmd = 2;
6435         else if (cdclk == 266667)
6436                 cmd = 1;
6437         else
6438                 cmd = 0;
6439
6440         mutex_lock(&dev_priv->rps.hw_lock);
6441         val = vlv_punit_read(dev_priv, PUNIT_REG_DSPFREQ);
6442         val &= ~DSPFREQGUAR_MASK;
6443         val |= (cmd << DSPFREQGUAR_SHIFT);
6444         vlv_punit_write(dev_priv, PUNIT_REG_DSPFREQ, val);
6445         if (wait_for((vlv_punit_read(dev_priv, PUNIT_REG_DSPFREQ) &
6446                       DSPFREQSTAT_MASK) == (cmd << DSPFREQSTAT_SHIFT),
6447                      50)) {
6448                 DRM_ERROR("timed out waiting for CDclk change\n");
6449         }
6450         mutex_unlock(&dev_priv->rps.hw_lock);
6451
6452         mutex_lock(&dev_priv->sb_lock);
6453
6454         if (cdclk == 400000) {
6455                 u32 divider;
6456
6457                 divider = DIV_ROUND_CLOSEST(dev_priv->hpll_freq << 1, cdclk) - 1;
6458
6459                 /* adjust cdclk divider */
6460                 val = vlv_cck_read(dev_priv, CCK_DISPLAY_CLOCK_CONTROL);
6461                 val &= ~CCK_FREQUENCY_VALUES;
6462                 val |= divider;
6463                 vlv_cck_write(dev_priv, CCK_DISPLAY_CLOCK_CONTROL, val);
6464
6465                 if (wait_for((vlv_cck_read(dev_priv, CCK_DISPLAY_CLOCK_CONTROL) &
6466                               CCK_FREQUENCY_STATUS) == (divider << CCK_FREQUENCY_STATUS_SHIFT),
6467                              50))
6468                         DRM_ERROR("timed out waiting for CDclk change\n");
6469         }
6470
6471         /* adjust self-refresh exit latency value */
6472         val = vlv_bunit_read(dev_priv, BUNIT_REG_BISOC);
6473         val &= ~0x7f;
6474
6475         /*
6476          * For high bandwidth configs, we set a higher latency in the bunit
6477          * so that the core display fetch happens in time to avoid underruns.
6478          */
6479         if (cdclk == 400000)
6480                 val |= 4500 / 250; /* 4.5 usec */
6481         else
6482                 val |= 3000 / 250; /* 3.0 usec */
6483         vlv_bunit_write(dev_priv, BUNIT_REG_BISOC, val);
6484
6485         mutex_unlock(&dev_priv->sb_lock);
6486
6487         intel_update_cdclk(dev);
6488 }
6489
6490 static void cherryview_set_cdclk(struct drm_device *dev, int cdclk)
6491 {
6492         struct drm_i915_private *dev_priv = to_i915(dev);
6493         u32 val, cmd;
6494
6495         WARN_ON(dev_priv->display.get_display_clock_speed(dev)
6496                                                 != dev_priv->cdclk_freq);
6497
6498         switch (cdclk) {
6499         case 333333:
6500         case 320000:
6501         case 266667:
6502         case 200000:
6503                 break;
6504         default:
6505                 MISSING_CASE(cdclk);
6506                 return;
6507         }
6508
6509         /*
6510          * Specs are full of misinformation, but testing on actual
6511          * hardware has shown that we just need to write the desired
6512          * CCK divider into the Punit register.
6513          */
6514         cmd = DIV_ROUND_CLOSEST(dev_priv->hpll_freq << 1, cdclk) - 1;
6515
6516         mutex_lock(&dev_priv->rps.hw_lock);
6517         val = vlv_punit_read(dev_priv, PUNIT_REG_DSPFREQ);
6518         val &= ~DSPFREQGUAR_MASK_CHV;
6519         val |= (cmd << DSPFREQGUAR_SHIFT_CHV);
6520         vlv_punit_write(dev_priv, PUNIT_REG_DSPFREQ, val);
6521         if (wait_for((vlv_punit_read(dev_priv, PUNIT_REG_DSPFREQ) &
6522                       DSPFREQSTAT_MASK_CHV) == (cmd << DSPFREQSTAT_SHIFT_CHV),
6523                      50)) {
6524                 DRM_ERROR("timed out waiting for CDclk change\n");
6525         }
6526         mutex_unlock(&dev_priv->rps.hw_lock);
6527
6528         intel_update_cdclk(dev);
6529 }
6530
6531 static int valleyview_calc_cdclk(struct drm_i915_private *dev_priv,
6532                                  int max_pixclk)
6533 {
6534         int freq_320 = (dev_priv->hpll_freq <<  1) % 320000 != 0 ? 333333 : 320000;
6535         int limit = IS_CHERRYVIEW(dev_priv) ? 95 : 90;
6536
6537         /*
6538          * Really only a few cases to deal with, as only 4 CDclks are supported:
6539          *   200MHz
6540          *   267MHz
6541          *   320/333MHz (depends on HPLL freq)
6542          *   400MHz (VLV only)
6543          * So we check to see whether we're above 90% (VLV) or 95% (CHV)
6544          * of the lower bin and adjust if needed.
6545          *
6546          * We seem to get an unstable or solid color picture at 200MHz.
6547          * Not sure what's wrong. For now use 200MHz only when all pipes
6548          * are off.
6549          */
6550         if (!IS_CHERRYVIEW(dev_priv) &&
6551             max_pixclk > freq_320*limit/100)
6552                 return 400000;
6553         else if (max_pixclk > 266667*limit/100)
6554                 return freq_320;
6555         else if (max_pixclk > 0)
6556                 return 266667;
6557         else
6558                 return 200000;
6559 }
6560
6561 static int bxt_calc_cdclk(int max_pixclk)
6562 {
6563         if (max_pixclk > 576000)
6564                 return 624000;
6565         else if (max_pixclk > 384000)
6566                 return 576000;
6567         else if (max_pixclk > 288000)
6568                 return 384000;
6569         else if (max_pixclk > 144000)
6570                 return 288000;
6571         else
6572                 return 144000;
6573 }
6574
6575 /* Compute the max pixel clock for new configuration. */
6576 static int intel_mode_max_pixclk(struct drm_device *dev,
6577                                  struct drm_atomic_state *state)
6578 {
6579         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
6580         struct drm_i915_private *dev_priv = to_i915(dev);
6581         struct drm_crtc *crtc;
6582         struct drm_crtc_state *crtc_state;
6583         unsigned max_pixclk = 0, i;
6584         enum pipe pipe;
6585
6586         memcpy(intel_state->min_pixclk, dev_priv->min_pixclk,
6587                sizeof(intel_state->min_pixclk));
6588
6589         for_each_crtc_in_state(state, crtc, crtc_state, i) {
6590                 int pixclk = 0;
6591
6592                 if (crtc_state->enable)
6593                         pixclk = crtc_state->adjusted_mode.crtc_clock;
6594
6595                 intel_state->min_pixclk[i] = pixclk;
6596         }
6597
6598         for_each_pipe(dev_priv, pipe)
6599                 max_pixclk = max(intel_state->min_pixclk[pipe], max_pixclk);
6600
6601         return max_pixclk;
6602 }
6603
6604 static int valleyview_modeset_calc_cdclk(struct drm_atomic_state *state)
6605 {
6606         struct drm_device *dev = state->dev;
6607         struct drm_i915_private *dev_priv = to_i915(dev);
6608         int max_pixclk = intel_mode_max_pixclk(dev, state);
6609         struct intel_atomic_state *intel_state =
6610                 to_intel_atomic_state(state);
6611
6612         intel_state->cdclk = intel_state->dev_cdclk =
6613                 valleyview_calc_cdclk(dev_priv, max_pixclk);
6614
6615         if (!intel_state->active_crtcs)
6616                 intel_state->dev_cdclk = valleyview_calc_cdclk(dev_priv, 0);
6617
6618         return 0;
6619 }
6620
6621 static int bxt_modeset_calc_cdclk(struct drm_atomic_state *state)
6622 {
6623         int max_pixclk = ilk_max_pixel_rate(state);
6624         struct intel_atomic_state *intel_state =
6625                 to_intel_atomic_state(state);
6626
6627         intel_state->cdclk = intel_state->dev_cdclk =
6628                 bxt_calc_cdclk(max_pixclk);
6629
6630         if (!intel_state->active_crtcs)
6631                 intel_state->dev_cdclk = bxt_calc_cdclk(0);
6632
6633         return 0;
6634 }
6635
6636 static void vlv_program_pfi_credits(struct drm_i915_private *dev_priv)
6637 {
6638         unsigned int credits, default_credits;
6639
6640         if (IS_CHERRYVIEW(dev_priv))
6641                 default_credits = PFI_CREDIT(12);
6642         else
6643                 default_credits = PFI_CREDIT(8);
6644
6645         if (dev_priv->cdclk_freq >= dev_priv->czclk_freq) {
6646                 /* CHV suggested value is 31 or 63 */
6647                 if (IS_CHERRYVIEW(dev_priv))
6648                         credits = PFI_CREDIT_63;
6649                 else
6650                         credits = PFI_CREDIT(15);
6651         } else {
6652                 credits = default_credits;
6653         }
6654
6655         /*
6656          * WA - write default credits before re-programming
6657          * FIXME: should we also set the resend bit here?
6658          */
6659         I915_WRITE(GCI_CONTROL, VGA_FAST_MODE_DISABLE |
6660                    default_credits);
6661
6662         I915_WRITE(GCI_CONTROL, VGA_FAST_MODE_DISABLE |
6663                    credits | PFI_CREDIT_RESEND);
6664
6665         /*
6666          * FIXME is this guaranteed to clear
6667          * immediately or should we poll for it?
6668          */
6669         WARN_ON(I915_READ(GCI_CONTROL) & PFI_CREDIT_RESEND);
6670 }
6671
6672 static void valleyview_modeset_commit_cdclk(struct drm_atomic_state *old_state)
6673 {
6674         struct drm_device *dev = old_state->dev;
6675         struct drm_i915_private *dev_priv = to_i915(dev);
6676         struct intel_atomic_state *old_intel_state =
6677                 to_intel_atomic_state(old_state);
6678         unsigned req_cdclk = old_intel_state->dev_cdclk;
6679
6680         /*
6681          * FIXME: We can end up here with all power domains off, yet
6682          * with a CDCLK frequency other than the minimum. To account
6683          * for this take the PIPE-A power domain, which covers the HW
6684          * blocks needed for the following programming. This can be
6685          * removed once it's guaranteed that we get here either with
6686          * the minimum CDCLK set, or the required power domains
6687          * enabled.
6688          */
6689         intel_display_power_get(dev_priv, POWER_DOMAIN_PIPE_A);
6690
6691         if (IS_CHERRYVIEW(dev_priv))
6692                 cherryview_set_cdclk(dev, req_cdclk);
6693         else
6694                 valleyview_set_cdclk(dev, req_cdclk);
6695
6696         vlv_program_pfi_credits(dev_priv);
6697
6698         intel_display_power_put(dev_priv, POWER_DOMAIN_PIPE_A);
6699 }
6700
6701 static void valleyview_crtc_enable(struct intel_crtc_state *pipe_config,
6702                                    struct drm_atomic_state *old_state)
6703 {
6704         struct drm_crtc *crtc = pipe_config->base.crtc;
6705         struct drm_device *dev = crtc->dev;
6706         struct drm_i915_private *dev_priv = to_i915(dev);
6707         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
6708         int pipe = intel_crtc->pipe;
6709
6710         if (WARN_ON(intel_crtc->active))
6711                 return;
6712
6713         if (intel_crtc_has_dp_encoder(intel_crtc->config))
6714                 intel_dp_set_m_n(intel_crtc, M1_N1);
6715
6716         intel_set_pipe_timings(intel_crtc);
6717         intel_set_pipe_src_size(intel_crtc);
6718
6719         if (IS_CHERRYVIEW(dev_priv) && pipe == PIPE_B) {
6720                 struct drm_i915_private *dev_priv = to_i915(dev);
6721
6722                 I915_WRITE(CHV_BLEND(pipe), CHV_BLEND_LEGACY);
6723                 I915_WRITE(CHV_CANVAS(pipe), 0);
6724         }
6725
6726         i9xx_set_pipeconf(intel_crtc);
6727
6728         intel_crtc->active = true;
6729
6730         intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
6731
6732         intel_encoders_pre_pll_enable(crtc, pipe_config, old_state);
6733
6734         if (IS_CHERRYVIEW(dev_priv)) {
6735                 chv_prepare_pll(intel_crtc, intel_crtc->config);
6736                 chv_enable_pll(intel_crtc, intel_crtc->config);
6737         } else {
6738                 vlv_prepare_pll(intel_crtc, intel_crtc->config);
6739                 vlv_enable_pll(intel_crtc, intel_crtc->config);
6740         }
6741
6742         intel_encoders_pre_enable(crtc, pipe_config, old_state);
6743
6744         i9xx_pfit_enable(intel_crtc);
6745
6746         intel_color_load_luts(&pipe_config->base);
6747
6748         intel_update_watermarks(crtc);
6749         intel_enable_pipe(intel_crtc);
6750
6751         assert_vblank_disabled(crtc);
6752         drm_crtc_vblank_on(crtc);
6753
6754         intel_encoders_enable(crtc, pipe_config, old_state);
6755 }
6756
6757 static void i9xx_set_pll_dividers(struct intel_crtc *crtc)
6758 {
6759         struct drm_device *dev = crtc->base.dev;
6760         struct drm_i915_private *dev_priv = to_i915(dev);
6761
6762         I915_WRITE(FP0(crtc->pipe), crtc->config->dpll_hw_state.fp0);
6763         I915_WRITE(FP1(crtc->pipe), crtc->config->dpll_hw_state.fp1);
6764 }
6765
6766 static void i9xx_crtc_enable(struct intel_crtc_state *pipe_config,
6767                              struct drm_atomic_state *old_state)
6768 {
6769         struct drm_crtc *crtc = pipe_config->base.crtc;
6770         struct drm_device *dev = crtc->dev;
6771         struct drm_i915_private *dev_priv = to_i915(dev);
6772         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
6773         enum pipe pipe = intel_crtc->pipe;
6774
6775         if (WARN_ON(intel_crtc->active))
6776                 return;
6777
6778         i9xx_set_pll_dividers(intel_crtc);
6779
6780         if (intel_crtc_has_dp_encoder(intel_crtc->config))
6781                 intel_dp_set_m_n(intel_crtc, M1_N1);
6782
6783         intel_set_pipe_timings(intel_crtc);
6784         intel_set_pipe_src_size(intel_crtc);
6785
6786         i9xx_set_pipeconf(intel_crtc);
6787
6788         intel_crtc->active = true;
6789
6790         if (!IS_GEN2(dev_priv))
6791                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
6792
6793         intel_encoders_pre_enable(crtc, pipe_config, old_state);
6794
6795         i9xx_enable_pll(intel_crtc);
6796
6797         i9xx_pfit_enable(intel_crtc);
6798
6799         intel_color_load_luts(&pipe_config->base);
6800
6801         intel_update_watermarks(crtc);
6802         intel_enable_pipe(intel_crtc);
6803
6804         assert_vblank_disabled(crtc);
6805         drm_crtc_vblank_on(crtc);
6806
6807         intel_encoders_enable(crtc, pipe_config, old_state);
6808 }
6809
6810 static void i9xx_pfit_disable(struct intel_crtc *crtc)
6811 {
6812         struct drm_device *dev = crtc->base.dev;
6813         struct drm_i915_private *dev_priv = to_i915(dev);
6814
6815         if (!crtc->config->gmch_pfit.control)
6816                 return;
6817
6818         assert_pipe_disabled(dev_priv, crtc->pipe);
6819
6820         DRM_DEBUG_DRIVER("disabling pfit, current: 0x%08x\n",
6821                          I915_READ(PFIT_CONTROL));
6822         I915_WRITE(PFIT_CONTROL, 0);
6823 }
6824
6825 static void i9xx_crtc_disable(struct intel_crtc_state *old_crtc_state,
6826                               struct drm_atomic_state *old_state)
6827 {
6828         struct drm_crtc *crtc = old_crtc_state->base.crtc;
6829         struct drm_device *dev = crtc->dev;
6830         struct drm_i915_private *dev_priv = to_i915(dev);
6831         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
6832         int pipe = intel_crtc->pipe;
6833
6834         /*
6835          * On gen2 planes are double buffered but the pipe isn't, so we must
6836          * wait for planes to fully turn off before disabling the pipe.
6837          */
6838         if (IS_GEN2(dev_priv))
6839                 intel_wait_for_vblank(dev, pipe);
6840
6841         intel_encoders_disable(crtc, old_crtc_state, old_state);
6842
6843         drm_crtc_vblank_off(crtc);
6844         assert_vblank_disabled(crtc);
6845
6846         intel_disable_pipe(intel_crtc);
6847
6848         i9xx_pfit_disable(intel_crtc);
6849
6850         intel_encoders_post_disable(crtc, old_crtc_state, old_state);
6851
6852         if (!intel_crtc_has_type(intel_crtc->config, INTEL_OUTPUT_DSI)) {
6853                 if (IS_CHERRYVIEW(dev_priv))
6854                         chv_disable_pll(dev_priv, pipe);
6855                 else if (IS_VALLEYVIEW(dev_priv))
6856                         vlv_disable_pll(dev_priv, pipe);
6857                 else
6858                         i9xx_disable_pll(intel_crtc);
6859         }
6860
6861         intel_encoders_post_pll_disable(crtc, old_crtc_state, old_state);
6862
6863         if (!IS_GEN2(dev_priv))
6864                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
6865 }
6866
6867 static void intel_crtc_disable_noatomic(struct drm_crtc *crtc)
6868 {
6869         struct intel_encoder *encoder;
6870         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
6871         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
6872         enum intel_display_power_domain domain;
6873         unsigned long domains;
6874         struct drm_atomic_state *state;
6875         struct intel_crtc_state *crtc_state;
6876         int ret;
6877
6878         if (!intel_crtc->active)
6879                 return;
6880
6881         if (to_intel_plane_state(crtc->primary->state)->base.visible) {
6882                 WARN_ON(intel_crtc->flip_work);
6883
6884                 intel_pre_disable_primary_noatomic(crtc);
6885
6886                 intel_crtc_disable_planes(crtc, 1 << drm_plane_index(crtc->primary));
6887                 to_intel_plane_state(crtc->primary->state)->base.visible = false;
6888         }
6889
6890         state = drm_atomic_state_alloc(crtc->dev);
6891         state->acquire_ctx = crtc->dev->mode_config.acquire_ctx;
6892
6893         /* Everything's already locked, -EDEADLK can't happen. */
6894         crtc_state = intel_atomic_get_crtc_state(state, intel_crtc);
6895         ret = drm_atomic_add_affected_connectors(state, crtc);
6896
6897         WARN_ON(IS_ERR(crtc_state) || ret);
6898
6899         dev_priv->display.crtc_disable(crtc_state, state);
6900
6901         drm_atomic_state_put(state);
6902
6903         DRM_DEBUG_KMS("[CRTC:%d:%s] hw state adjusted, was enabled, now disabled\n",
6904                       crtc->base.id, crtc->name);
6905
6906         WARN_ON(drm_atomic_set_mode_for_crtc(crtc->state, NULL) < 0);
6907         crtc->state->active = false;
6908         intel_crtc->active = false;
6909         crtc->enabled = false;
6910         crtc->state->connector_mask = 0;
6911         crtc->state->encoder_mask = 0;
6912
6913         for_each_encoder_on_crtc(crtc->dev, crtc, encoder)
6914                 encoder->base.crtc = NULL;
6915
6916         intel_fbc_disable(intel_crtc);
6917         intel_update_watermarks(crtc);
6918         intel_disable_shared_dpll(intel_crtc);
6919
6920         domains = intel_crtc->enabled_power_domains;
6921         for_each_power_domain(domain, domains)
6922                 intel_display_power_put(dev_priv, domain);
6923         intel_crtc->enabled_power_domains = 0;
6924
6925         dev_priv->active_crtcs &= ~(1 << intel_crtc->pipe);
6926         dev_priv->min_pixclk[intel_crtc->pipe] = 0;
6927 }
6928
6929 /*
6930  * turn all crtc's off, but do not adjust state
6931  * This has to be paired with a call to intel_modeset_setup_hw_state.
6932  */
6933 int intel_display_suspend(struct drm_device *dev)
6934 {
6935         struct drm_i915_private *dev_priv = to_i915(dev);
6936         struct drm_atomic_state *state;
6937         int ret;
6938
6939         state = drm_atomic_helper_suspend(dev);
6940         ret = PTR_ERR_OR_ZERO(state);
6941         if (ret)
6942                 DRM_ERROR("Suspending crtc's failed with %i\n", ret);
6943         else
6944                 dev_priv->modeset_restore_state = state;
6945         return ret;
6946 }
6947
6948 void intel_encoder_destroy(struct drm_encoder *encoder)
6949 {
6950         struct intel_encoder *intel_encoder = to_intel_encoder(encoder);
6951
6952         drm_encoder_cleanup(encoder);
6953         kfree(intel_encoder);
6954 }
6955
6956 /* Cross check the actual hw state with our own modeset state tracking (and it's
6957  * internal consistency). */
6958 static void intel_connector_verify_state(struct intel_connector *connector)
6959 {
6960         struct drm_crtc *crtc = connector->base.state->crtc;
6961
6962         DRM_DEBUG_KMS("[CONNECTOR:%d:%s]\n",
6963                       connector->base.base.id,
6964                       connector->base.name);
6965
6966         if (connector->get_hw_state(connector)) {
6967                 struct intel_encoder *encoder = connector->encoder;
6968                 struct drm_connector_state *conn_state = connector->base.state;
6969
6970                 I915_STATE_WARN(!crtc,
6971                          "connector enabled without attached crtc\n");
6972
6973                 if (!crtc)
6974                         return;
6975
6976                 I915_STATE_WARN(!crtc->state->active,
6977                       "connector is active, but attached crtc isn't\n");
6978
6979                 if (!encoder || encoder->type == INTEL_OUTPUT_DP_MST)
6980                         return;
6981
6982                 I915_STATE_WARN(conn_state->best_encoder != &encoder->base,
6983                         "atomic encoder doesn't match attached encoder\n");
6984
6985                 I915_STATE_WARN(conn_state->crtc != encoder->base.crtc,
6986                         "attached encoder crtc differs from connector crtc\n");
6987         } else {
6988                 I915_STATE_WARN(crtc && crtc->state->active,
6989                         "attached crtc is active, but connector isn't\n");
6990                 I915_STATE_WARN(!crtc && connector->base.state->best_encoder,
6991                         "best encoder set without crtc!\n");
6992         }
6993 }
6994
6995 int intel_connector_init(struct intel_connector *connector)
6996 {
6997         drm_atomic_helper_connector_reset(&connector->base);
6998
6999         if (!connector->base.state)
7000                 return -ENOMEM;
7001
7002         return 0;
7003 }
7004
7005 struct intel_connector *intel_connector_alloc(void)
7006 {
7007         struct intel_connector *connector;
7008
7009         connector = kzalloc(sizeof *connector, GFP_KERNEL);
7010         if (!connector)
7011                 return NULL;
7012
7013         if (intel_connector_init(connector) < 0) {
7014                 kfree(connector);
7015                 return NULL;
7016         }
7017
7018         return connector;
7019 }
7020
7021 /* Simple connector->get_hw_state implementation for encoders that support only
7022  * one connector and no cloning and hence the encoder state determines the state
7023  * of the connector. */
7024 bool intel_connector_get_hw_state(struct intel_connector *connector)
7025 {
7026         enum pipe pipe = 0;
7027         struct intel_encoder *encoder = connector->encoder;
7028
7029         return encoder->get_hw_state(encoder, &pipe);
7030 }
7031
7032 static int pipe_required_fdi_lanes(struct intel_crtc_state *crtc_state)
7033 {
7034         if (crtc_state->base.enable && crtc_state->has_pch_encoder)
7035                 return crtc_state->fdi_lanes;
7036
7037         return 0;
7038 }
7039
7040 static int ironlake_check_fdi_lanes(struct drm_device *dev, enum pipe pipe,
7041                                      struct intel_crtc_state *pipe_config)
7042 {
7043         struct drm_i915_private *dev_priv = to_i915(dev);
7044         struct drm_atomic_state *state = pipe_config->base.state;
7045         struct intel_crtc *other_crtc;
7046         struct intel_crtc_state *other_crtc_state;
7047
7048         DRM_DEBUG_KMS("checking fdi config on pipe %c, lanes %i\n",
7049                       pipe_name(pipe), pipe_config->fdi_lanes);
7050         if (pipe_config->fdi_lanes > 4) {
7051                 DRM_DEBUG_KMS("invalid fdi lane config on pipe %c: %i lanes\n",
7052                               pipe_name(pipe), pipe_config->fdi_lanes);
7053                 return -EINVAL;
7054         }
7055
7056         if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv)) {
7057                 if (pipe_config->fdi_lanes > 2) {
7058                         DRM_DEBUG_KMS("only 2 lanes on haswell, required: %i lanes\n",
7059                                       pipe_config->fdi_lanes);
7060                         return -EINVAL;
7061                 } else {
7062                         return 0;
7063                 }
7064         }
7065
7066         if (INTEL_INFO(dev)->num_pipes == 2)
7067                 return 0;
7068
7069         /* Ivybridge 3 pipe is really complicated */
7070         switch (pipe) {
7071         case PIPE_A:
7072                 return 0;
7073         case PIPE_B:
7074                 if (pipe_config->fdi_lanes <= 2)
7075                         return 0;
7076
7077                 other_crtc = to_intel_crtc(intel_get_crtc_for_pipe(dev, PIPE_C));
7078                 other_crtc_state =
7079                         intel_atomic_get_crtc_state(state, other_crtc);
7080                 if (IS_ERR(other_crtc_state))
7081                         return PTR_ERR(other_crtc_state);
7082
7083                 if (pipe_required_fdi_lanes(other_crtc_state) > 0) {
7084                         DRM_DEBUG_KMS("invalid shared fdi lane config on pipe %c: %i lanes\n",
7085                                       pipe_name(pipe), pipe_config->fdi_lanes);
7086                         return -EINVAL;
7087                 }
7088                 return 0;
7089         case PIPE_C:
7090                 if (pipe_config->fdi_lanes > 2) {
7091                         DRM_DEBUG_KMS("only 2 lanes on pipe %c: required %i lanes\n",
7092                                       pipe_name(pipe), pipe_config->fdi_lanes);
7093                         return -EINVAL;
7094                 }
7095
7096                 other_crtc = to_intel_crtc(intel_get_crtc_for_pipe(dev, PIPE_B));
7097                 other_crtc_state =
7098                         intel_atomic_get_crtc_state(state, other_crtc);
7099                 if (IS_ERR(other_crtc_state))
7100                         return PTR_ERR(other_crtc_state);
7101
7102                 if (pipe_required_fdi_lanes(other_crtc_state) > 2) {
7103                         DRM_DEBUG_KMS("fdi link B uses too many lanes to enable link C\n");
7104                         return -EINVAL;
7105                 }
7106                 return 0;
7107         default:
7108                 BUG();
7109         }
7110 }
7111
7112 #define RETRY 1
7113 static int ironlake_fdi_compute_config(struct intel_crtc *intel_crtc,
7114                                        struct intel_crtc_state *pipe_config)
7115 {
7116         struct drm_device *dev = intel_crtc->base.dev;
7117         const struct drm_display_mode *adjusted_mode = &pipe_config->base.adjusted_mode;
7118         int lane, link_bw, fdi_dotclock, ret;
7119         bool needs_recompute = false;
7120
7121 retry:
7122         /* FDI is a binary signal running at ~2.7GHz, encoding
7123          * each output octet as 10 bits. The actual frequency
7124          * is stored as a divider into a 100MHz clock, and the
7125          * mode pixel clock is stored in units of 1KHz.
7126          * Hence the bw of each lane in terms of the mode signal
7127          * is:
7128          */
7129         link_bw = intel_fdi_link_freq(to_i915(dev), pipe_config);
7130
7131         fdi_dotclock = adjusted_mode->crtc_clock;
7132
7133         lane = ironlake_get_lanes_required(fdi_dotclock, link_bw,
7134                                            pipe_config->pipe_bpp);
7135
7136         pipe_config->fdi_lanes = lane;
7137
7138         intel_link_compute_m_n(pipe_config->pipe_bpp, lane, fdi_dotclock,
7139                                link_bw, &pipe_config->fdi_m_n);
7140
7141         ret = ironlake_check_fdi_lanes(dev, intel_crtc->pipe, pipe_config);
7142         if (ret == -EINVAL && pipe_config->pipe_bpp > 6*3) {
7143                 pipe_config->pipe_bpp -= 2*3;
7144                 DRM_DEBUG_KMS("fdi link bw constraint, reducing pipe bpp to %i\n",
7145                               pipe_config->pipe_bpp);
7146                 needs_recompute = true;
7147                 pipe_config->bw_constrained = true;
7148
7149                 goto retry;
7150         }
7151
7152         if (needs_recompute)
7153                 return RETRY;
7154
7155         return ret;
7156 }
7157
7158 static bool pipe_config_supports_ips(struct drm_i915_private *dev_priv,
7159                                      struct intel_crtc_state *pipe_config)
7160 {
7161         if (pipe_config->pipe_bpp > 24)
7162                 return false;
7163
7164         /* HSW can handle pixel rate up to cdclk? */
7165         if (IS_HASWELL(dev_priv))
7166                 return true;
7167
7168         /*
7169          * We compare against max which means we must take
7170          * the increased cdclk requirement into account when
7171          * calculating the new cdclk.
7172          *
7173          * Should measure whether using a lower cdclk w/o IPS
7174          */
7175         return ilk_pipe_pixel_rate(pipe_config) <=
7176                 dev_priv->max_cdclk_freq * 95 / 100;
7177 }
7178
7179 static void hsw_compute_ips_config(struct intel_crtc *crtc,
7180                                    struct intel_crtc_state *pipe_config)
7181 {
7182         struct drm_device *dev = crtc->base.dev;
7183         struct drm_i915_private *dev_priv = to_i915(dev);
7184
7185         pipe_config->ips_enabled = i915.enable_ips &&
7186                 hsw_crtc_supports_ips(crtc) &&
7187                 pipe_config_supports_ips(dev_priv, pipe_config);
7188 }
7189
7190 static bool intel_crtc_supports_double_wide(const struct intel_crtc *crtc)
7191 {
7192         const struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
7193
7194         /* GDG double wide on either pipe, otherwise pipe A only */
7195         return INTEL_INFO(dev_priv)->gen < 4 &&
7196                 (crtc->pipe == PIPE_A || IS_I915G(dev_priv));
7197 }
7198
7199 static int intel_crtc_compute_config(struct intel_crtc *crtc,
7200                                      struct intel_crtc_state *pipe_config)
7201 {
7202         struct drm_device *dev = crtc->base.dev;
7203         struct drm_i915_private *dev_priv = to_i915(dev);
7204         const struct drm_display_mode *adjusted_mode = &pipe_config->base.adjusted_mode;
7205         int clock_limit = dev_priv->max_dotclk_freq;
7206
7207         if (INTEL_INFO(dev)->gen < 4) {
7208                 clock_limit = dev_priv->max_cdclk_freq * 9 / 10;
7209
7210                 /*
7211                  * Enable double wide mode when the dot clock
7212                  * is > 90% of the (display) core speed.
7213                  */
7214                 if (intel_crtc_supports_double_wide(crtc) &&
7215                     adjusted_mode->crtc_clock > clock_limit) {
7216                         clock_limit = dev_priv->max_dotclk_freq;
7217                         pipe_config->double_wide = true;
7218                 }
7219         }
7220
7221         if (adjusted_mode->crtc_clock > clock_limit) {
7222                 DRM_DEBUG_KMS("requested pixel clock (%d kHz) too high (max: %d kHz, double wide: %s)\n",
7223                               adjusted_mode->crtc_clock, clock_limit,
7224                               yesno(pipe_config->double_wide));
7225                 return -EINVAL;
7226         }
7227
7228         /*
7229          * Pipe horizontal size must be even in:
7230          * - DVO ganged mode
7231          * - LVDS dual channel mode
7232          * - Double wide pipe
7233          */
7234         if ((intel_crtc_has_type(pipe_config, INTEL_OUTPUT_LVDS) &&
7235              intel_is_dual_link_lvds(dev)) || pipe_config->double_wide)
7236                 pipe_config->pipe_src_w &= ~1;
7237
7238         /* Cantiga+ cannot handle modes with a hsync front porch of 0.
7239          * WaPruneModeWithIncorrectHsyncOffset:ctg,elk,ilk,snb,ivb,vlv,hsw.
7240          */
7241         if ((INTEL_GEN(dev_priv) > 4 || IS_G4X(dev_priv)) &&
7242                 adjusted_mode->crtc_hsync_start == adjusted_mode->crtc_hdisplay)
7243                 return -EINVAL;
7244
7245         if (HAS_IPS(dev_priv))
7246                 hsw_compute_ips_config(crtc, pipe_config);
7247
7248         if (pipe_config->has_pch_encoder)
7249                 return ironlake_fdi_compute_config(crtc, pipe_config);
7250
7251         return 0;
7252 }
7253
7254 static int skylake_get_display_clock_speed(struct drm_device *dev)
7255 {
7256         struct drm_i915_private *dev_priv = to_i915(dev);
7257         uint32_t cdctl;
7258
7259         skl_dpll0_update(dev_priv);
7260
7261         if (dev_priv->cdclk_pll.vco == 0)
7262                 return dev_priv->cdclk_pll.ref;
7263
7264         cdctl = I915_READ(CDCLK_CTL);
7265
7266         if (dev_priv->cdclk_pll.vco == 8640000) {
7267                 switch (cdctl & CDCLK_FREQ_SEL_MASK) {
7268                 case CDCLK_FREQ_450_432:
7269                         return 432000;
7270                 case CDCLK_FREQ_337_308:
7271                         return 308571;
7272                 case CDCLK_FREQ_540:
7273                         return 540000;
7274                 case CDCLK_FREQ_675_617:
7275                         return 617143;
7276                 default:
7277                         MISSING_CASE(cdctl & CDCLK_FREQ_SEL_MASK);
7278                 }
7279         } else {
7280                 switch (cdctl & CDCLK_FREQ_SEL_MASK) {
7281                 case CDCLK_FREQ_450_432:
7282                         return 450000;
7283                 case CDCLK_FREQ_337_308:
7284                         return 337500;
7285                 case CDCLK_FREQ_540:
7286                         return 540000;
7287                 case CDCLK_FREQ_675_617:
7288                         return 675000;
7289                 default:
7290                         MISSING_CASE(cdctl & CDCLK_FREQ_SEL_MASK);
7291                 }
7292         }
7293
7294         return dev_priv->cdclk_pll.ref;
7295 }
7296
7297 static void bxt_de_pll_update(struct drm_i915_private *dev_priv)
7298 {
7299         u32 val;
7300
7301         dev_priv->cdclk_pll.ref = 19200;
7302         dev_priv->cdclk_pll.vco = 0;
7303
7304         val = I915_READ(BXT_DE_PLL_ENABLE);
7305         if ((val & BXT_DE_PLL_PLL_ENABLE) == 0)
7306                 return;
7307
7308         if (WARN_ON((val & BXT_DE_PLL_LOCK) == 0))
7309                 return;
7310
7311         val = I915_READ(BXT_DE_PLL_CTL);
7312         dev_priv->cdclk_pll.vco = (val & BXT_DE_PLL_RATIO_MASK) *
7313                 dev_priv->cdclk_pll.ref;
7314 }
7315
7316 static int broxton_get_display_clock_speed(struct drm_device *dev)
7317 {
7318         struct drm_i915_private *dev_priv = to_i915(dev);
7319         u32 divider;
7320         int div, vco;
7321
7322         bxt_de_pll_update(dev_priv);
7323
7324         vco = dev_priv->cdclk_pll.vco;
7325         if (vco == 0)
7326                 return dev_priv->cdclk_pll.ref;
7327
7328         divider = I915_READ(CDCLK_CTL) & BXT_CDCLK_CD2X_DIV_SEL_MASK;
7329
7330         switch (divider) {
7331         case BXT_CDCLK_CD2X_DIV_SEL_1:
7332                 div = 2;
7333                 break;
7334         case BXT_CDCLK_CD2X_DIV_SEL_1_5:
7335                 div = 3;
7336                 break;
7337         case BXT_CDCLK_CD2X_DIV_SEL_2:
7338                 div = 4;
7339                 break;
7340         case BXT_CDCLK_CD2X_DIV_SEL_4:
7341                 div = 8;
7342                 break;
7343         default:
7344                 MISSING_CASE(divider);
7345                 return dev_priv->cdclk_pll.ref;
7346         }
7347
7348         return DIV_ROUND_CLOSEST(vco, div);
7349 }
7350
7351 static int broadwell_get_display_clock_speed(struct drm_device *dev)
7352 {
7353         struct drm_i915_private *dev_priv = to_i915(dev);
7354         uint32_t lcpll = I915_READ(LCPLL_CTL);
7355         uint32_t freq = lcpll & LCPLL_CLK_FREQ_MASK;
7356
7357         if (lcpll & LCPLL_CD_SOURCE_FCLK)
7358                 return 800000;
7359         else if (I915_READ(FUSE_STRAP) & HSW_CDCLK_LIMIT)
7360                 return 450000;
7361         else if (freq == LCPLL_CLK_FREQ_450)
7362                 return 450000;
7363         else if (freq == LCPLL_CLK_FREQ_54O_BDW)
7364                 return 540000;
7365         else if (freq == LCPLL_CLK_FREQ_337_5_BDW)
7366                 return 337500;
7367         else
7368                 return 675000;
7369 }
7370
7371 static int haswell_get_display_clock_speed(struct drm_device *dev)
7372 {
7373         struct drm_i915_private *dev_priv = to_i915(dev);
7374         uint32_t lcpll = I915_READ(LCPLL_CTL);
7375         uint32_t freq = lcpll & LCPLL_CLK_FREQ_MASK;
7376
7377         if (lcpll & LCPLL_CD_SOURCE_FCLK)
7378                 return 800000;
7379         else if (I915_READ(FUSE_STRAP) & HSW_CDCLK_LIMIT)
7380                 return 450000;
7381         else if (freq == LCPLL_CLK_FREQ_450)
7382                 return 450000;
7383         else if (IS_HSW_ULT(dev_priv))
7384                 return 337500;
7385         else
7386                 return 540000;
7387 }
7388
7389 static int valleyview_get_display_clock_speed(struct drm_device *dev)
7390 {
7391         return vlv_get_cck_clock_hpll(to_i915(dev), "cdclk",
7392                                       CCK_DISPLAY_CLOCK_CONTROL);
7393 }
7394
7395 static int ilk_get_display_clock_speed(struct drm_device *dev)
7396 {
7397         return 450000;
7398 }
7399
7400 static int i945_get_display_clock_speed(struct drm_device *dev)
7401 {
7402         return 400000;
7403 }
7404
7405 static int i915_get_display_clock_speed(struct drm_device *dev)
7406 {
7407         return 333333;
7408 }
7409
7410 static int i9xx_misc_get_display_clock_speed(struct drm_device *dev)
7411 {
7412         return 200000;
7413 }
7414
7415 static int pnv_get_display_clock_speed(struct drm_device *dev)
7416 {
7417         struct pci_dev *pdev = dev->pdev;
7418         u16 gcfgc = 0;
7419
7420         pci_read_config_word(pdev, GCFGC, &gcfgc);
7421
7422         switch (gcfgc & GC_DISPLAY_CLOCK_MASK) {
7423         case GC_DISPLAY_CLOCK_267_MHZ_PNV:
7424                 return 266667;
7425         case GC_DISPLAY_CLOCK_333_MHZ_PNV:
7426                 return 333333;
7427         case GC_DISPLAY_CLOCK_444_MHZ_PNV:
7428                 return 444444;
7429         case GC_DISPLAY_CLOCK_200_MHZ_PNV:
7430                 return 200000;
7431         default:
7432                 DRM_ERROR("Unknown pnv display core clock 0x%04x\n", gcfgc);
7433         case GC_DISPLAY_CLOCK_133_MHZ_PNV:
7434                 return 133333;
7435         case GC_DISPLAY_CLOCK_167_MHZ_PNV:
7436                 return 166667;
7437         }
7438 }
7439
7440 static int i915gm_get_display_clock_speed(struct drm_device *dev)
7441 {
7442         struct pci_dev *pdev = dev->pdev;
7443         u16 gcfgc = 0;
7444
7445         pci_read_config_word(pdev, GCFGC, &gcfgc);
7446
7447         if (gcfgc & GC_LOW_FREQUENCY_ENABLE)
7448                 return 133333;
7449         else {
7450                 switch (gcfgc & GC_DISPLAY_CLOCK_MASK) {
7451                 case GC_DISPLAY_CLOCK_333_MHZ:
7452                         return 333333;
7453                 default:
7454                 case GC_DISPLAY_CLOCK_190_200_MHZ:
7455                         return 190000;
7456                 }
7457         }
7458 }
7459
7460 static int i865_get_display_clock_speed(struct drm_device *dev)
7461 {
7462         return 266667;
7463 }
7464
7465 static int i85x_get_display_clock_speed(struct drm_device *dev)
7466 {
7467         struct pci_dev *pdev = dev->pdev;
7468         u16 hpllcc = 0;
7469
7470         /*
7471          * 852GM/852GMV only supports 133 MHz and the HPLLCC
7472          * encoding is different :(
7473          * FIXME is this the right way to detect 852GM/852GMV?
7474          */
7475         if (pdev->revision == 0x1)
7476                 return 133333;
7477
7478         pci_bus_read_config_word(pdev->bus,
7479                                  PCI_DEVFN(0, 3), HPLLCC, &hpllcc);
7480
7481         /* Assume that the hardware is in the high speed state.  This
7482          * should be the default.
7483          */
7484         switch (hpllcc & GC_CLOCK_CONTROL_MASK) {
7485         case GC_CLOCK_133_200:
7486         case GC_CLOCK_133_200_2:
7487         case GC_CLOCK_100_200:
7488                 return 200000;
7489         case GC_CLOCK_166_250:
7490                 return 250000;
7491         case GC_CLOCK_100_133:
7492                 return 133333;
7493         case GC_CLOCK_133_266:
7494         case GC_CLOCK_133_266_2:
7495         case GC_CLOCK_166_266:
7496                 return 266667;
7497         }
7498
7499         /* Shouldn't happen */
7500         return 0;
7501 }
7502
7503 static int i830_get_display_clock_speed(struct drm_device *dev)
7504 {
7505         return 133333;
7506 }
7507
7508 static unsigned int intel_hpll_vco(struct drm_device *dev)
7509 {
7510         struct drm_i915_private *dev_priv = to_i915(dev);
7511         static const unsigned int blb_vco[8] = {
7512                 [0] = 3200000,
7513                 [1] = 4000000,
7514                 [2] = 5333333,
7515                 [3] = 4800000,
7516                 [4] = 6400000,
7517         };
7518         static const unsigned int pnv_vco[8] = {
7519                 [0] = 3200000,
7520                 [1] = 4000000,
7521                 [2] = 5333333,
7522                 [3] = 4800000,
7523                 [4] = 2666667,
7524         };
7525         static const unsigned int cl_vco[8] = {
7526                 [0] = 3200000,
7527                 [1] = 4000000,
7528                 [2] = 5333333,
7529                 [3] = 6400000,
7530                 [4] = 3333333,
7531                 [5] = 3566667,
7532                 [6] = 4266667,
7533         };
7534         static const unsigned int elk_vco[8] = {
7535                 [0] = 3200000,
7536                 [1] = 4000000,
7537                 [2] = 5333333,
7538                 [3] = 4800000,
7539         };
7540         static const unsigned int ctg_vco[8] = {
7541                 [0] = 3200000,
7542                 [1] = 4000000,
7543                 [2] = 5333333,
7544                 [3] = 6400000,
7545                 [4] = 2666667,
7546                 [5] = 4266667,
7547         };
7548         const unsigned int *vco_table;
7549         unsigned int vco;
7550         uint8_t tmp = 0;
7551
7552         /* FIXME other chipsets? */
7553         if (IS_GM45(dev_priv))
7554                 vco_table = ctg_vco;
7555         else if (IS_G4X(dev_priv))
7556                 vco_table = elk_vco;
7557         else if (IS_CRESTLINE(dev))
7558                 vco_table = cl_vco;
7559         else if (IS_PINEVIEW(dev))
7560                 vco_table = pnv_vco;
7561         else if (IS_G33(dev))
7562                 vco_table = blb_vco;
7563         else
7564                 return 0;
7565
7566         tmp = I915_READ(IS_MOBILE(dev) ? HPLLVCO_MOBILE : HPLLVCO);
7567
7568         vco = vco_table[tmp & 0x7];
7569         if (vco == 0)
7570                 DRM_ERROR("Bad HPLL VCO (HPLLVCO=0x%02x)\n", tmp);
7571         else
7572                 DRM_DEBUG_KMS("HPLL VCO %u kHz\n", vco);
7573
7574         return vco;
7575 }
7576
7577 static int gm45_get_display_clock_speed(struct drm_device *dev)
7578 {
7579         struct pci_dev *pdev = dev->pdev;
7580         unsigned int cdclk_sel, vco = intel_hpll_vco(dev);
7581         uint16_t tmp = 0;
7582
7583         pci_read_config_word(pdev, GCFGC, &tmp);
7584
7585         cdclk_sel = (tmp >> 12) & 0x1;
7586
7587         switch (vco) {
7588         case 2666667:
7589         case 4000000:
7590         case 5333333:
7591                 return cdclk_sel ? 333333 : 222222;
7592         case 3200000:
7593                 return cdclk_sel ? 320000 : 228571;
7594         default:
7595                 DRM_ERROR("Unable to determine CDCLK. HPLL VCO=%u, CFGC=0x%04x\n", vco, tmp);
7596                 return 222222;
7597         }
7598 }
7599
7600 static int i965gm_get_display_clock_speed(struct drm_device *dev)
7601 {
7602         struct pci_dev *pdev = dev->pdev;
7603         static const uint8_t div_3200[] = { 16, 10,  8 };
7604         static const uint8_t div_4000[] = { 20, 12, 10 };
7605         static const uint8_t div_5333[] = { 24, 16, 14 };
7606         const uint8_t *div_table;
7607         unsigned int cdclk_sel, vco = intel_hpll_vco(dev);
7608         uint16_t tmp = 0;
7609
7610         pci_read_config_word(pdev, GCFGC, &tmp);
7611
7612         cdclk_sel = ((tmp >> 8) & 0x1f) - 1;
7613
7614         if (cdclk_sel >= ARRAY_SIZE(div_3200))
7615                 goto fail;
7616
7617         switch (vco) {
7618         case 3200000:
7619                 div_table = div_3200;
7620                 break;
7621         case 4000000:
7622                 div_table = div_4000;
7623                 break;
7624         case 5333333:
7625                 div_table = div_5333;
7626                 break;
7627         default:
7628                 goto fail;
7629         }
7630
7631         return DIV_ROUND_CLOSEST(vco, div_table[cdclk_sel]);
7632
7633 fail:
7634         DRM_ERROR("Unable to determine CDCLK. HPLL VCO=%u kHz, CFGC=0x%04x\n", vco, tmp);
7635         return 200000;
7636 }
7637
7638 static int g33_get_display_clock_speed(struct drm_device *dev)
7639 {
7640         struct pci_dev *pdev = dev->pdev;
7641         static const uint8_t div_3200[] = { 12, 10,  8,  7, 5, 16 };
7642         static const uint8_t div_4000[] = { 14, 12, 10,  8, 6, 20 };
7643         static const uint8_t div_4800[] = { 20, 14, 12, 10, 8, 24 };
7644         static const uint8_t div_5333[] = { 20, 16, 12, 12, 8, 28 };
7645         const uint8_t *div_table;
7646         unsigned int cdclk_sel, vco = intel_hpll_vco(dev);
7647         uint16_t tmp = 0;
7648
7649         pci_read_config_word(pdev, GCFGC, &tmp);
7650
7651         cdclk_sel = (tmp >> 4) & 0x7;
7652
7653         if (cdclk_sel >= ARRAY_SIZE(div_3200))
7654                 goto fail;
7655
7656         switch (vco) {
7657         case 3200000:
7658                 div_table = div_3200;
7659                 break;
7660         case 4000000:
7661                 div_table = div_4000;
7662                 break;
7663         case 4800000:
7664                 div_table = div_4800;
7665                 break;
7666         case 5333333:
7667                 div_table = div_5333;
7668                 break;
7669         default:
7670                 goto fail;
7671         }
7672
7673         return DIV_ROUND_CLOSEST(vco, div_table[cdclk_sel]);
7674
7675 fail:
7676         DRM_ERROR("Unable to determine CDCLK. HPLL VCO=%u kHz, CFGC=0x%08x\n", vco, tmp);
7677         return 190476;
7678 }
7679
7680 static void
7681 intel_reduce_m_n_ratio(uint32_t *num, uint32_t *den)
7682 {
7683         while (*num > DATA_LINK_M_N_MASK ||
7684                *den > DATA_LINK_M_N_MASK) {
7685                 *num >>= 1;
7686                 *den >>= 1;
7687         }
7688 }
7689
7690 static void compute_m_n(unsigned int m, unsigned int n,
7691                         uint32_t *ret_m, uint32_t *ret_n)
7692 {
7693         *ret_n = min_t(unsigned int, roundup_pow_of_two(n), DATA_LINK_N_MAX);
7694         *ret_m = div_u64((uint64_t) m * *ret_n, n);
7695         intel_reduce_m_n_ratio(ret_m, ret_n);
7696 }
7697
7698 void
7699 intel_link_compute_m_n(int bits_per_pixel, int nlanes,
7700                        int pixel_clock, int link_clock,
7701                        struct intel_link_m_n *m_n)
7702 {
7703         m_n->tu = 64;
7704
7705         compute_m_n(bits_per_pixel * pixel_clock,
7706                     link_clock * nlanes * 8,
7707                     &m_n->gmch_m, &m_n->gmch_n);
7708
7709         compute_m_n(pixel_clock, link_clock,
7710                     &m_n->link_m, &m_n->link_n);
7711 }
7712
7713 static inline bool intel_panel_use_ssc(struct drm_i915_private *dev_priv)
7714 {
7715         if (i915.panel_use_ssc >= 0)
7716                 return i915.panel_use_ssc != 0;
7717         return dev_priv->vbt.lvds_use_ssc
7718                 && !(dev_priv->quirks & QUIRK_LVDS_SSC_DISABLE);
7719 }
7720
7721 static uint32_t pnv_dpll_compute_fp(struct dpll *dpll)
7722 {
7723         return (1 << dpll->n) << 16 | dpll->m2;
7724 }
7725
7726 static uint32_t i9xx_dpll_compute_fp(struct dpll *dpll)
7727 {
7728         return dpll->n << 16 | dpll->m1 << 8 | dpll->m2;
7729 }
7730
7731 static void i9xx_update_pll_dividers(struct intel_crtc *crtc,
7732                                      struct intel_crtc_state *crtc_state,
7733                                      struct dpll *reduced_clock)
7734 {
7735         struct drm_device *dev = crtc->base.dev;
7736         u32 fp, fp2 = 0;
7737
7738         if (IS_PINEVIEW(dev)) {
7739                 fp = pnv_dpll_compute_fp(&crtc_state->dpll);
7740                 if (reduced_clock)
7741                         fp2 = pnv_dpll_compute_fp(reduced_clock);
7742         } else {
7743                 fp = i9xx_dpll_compute_fp(&crtc_state->dpll);
7744                 if (reduced_clock)
7745                         fp2 = i9xx_dpll_compute_fp(reduced_clock);
7746         }
7747
7748         crtc_state->dpll_hw_state.fp0 = fp;
7749
7750         crtc->lowfreq_avail = false;
7751         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS) &&
7752             reduced_clock) {
7753                 crtc_state->dpll_hw_state.fp1 = fp2;
7754                 crtc->lowfreq_avail = true;
7755         } else {
7756                 crtc_state->dpll_hw_state.fp1 = fp;
7757         }
7758 }
7759
7760 static void vlv_pllb_recal_opamp(struct drm_i915_private *dev_priv, enum pipe
7761                 pipe)
7762 {
7763         u32 reg_val;
7764
7765         /*
7766          * PLLB opamp always calibrates to max value of 0x3f, force enable it
7767          * and set it to a reasonable value instead.
7768          */
7769         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW9(1));
7770         reg_val &= 0xffffff00;
7771         reg_val |= 0x00000030;
7772         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW9(1), reg_val);
7773
7774         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_REF_DW13);
7775         reg_val &= 0x8cffffff;
7776         reg_val = 0x8c000000;
7777         vlv_dpio_write(dev_priv, pipe, VLV_REF_DW13, reg_val);
7778
7779         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW9(1));
7780         reg_val &= 0xffffff00;
7781         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW9(1), reg_val);
7782
7783         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_REF_DW13);
7784         reg_val &= 0x00ffffff;
7785         reg_val |= 0xb0000000;
7786         vlv_dpio_write(dev_priv, pipe, VLV_REF_DW13, reg_val);
7787 }
7788
7789 static void intel_pch_transcoder_set_m_n(struct intel_crtc *crtc,
7790                                          struct intel_link_m_n *m_n)
7791 {
7792         struct drm_device *dev = crtc->base.dev;
7793         struct drm_i915_private *dev_priv = to_i915(dev);
7794         int pipe = crtc->pipe;
7795
7796         I915_WRITE(PCH_TRANS_DATA_M1(pipe), TU_SIZE(m_n->tu) | m_n->gmch_m);
7797         I915_WRITE(PCH_TRANS_DATA_N1(pipe), m_n->gmch_n);
7798         I915_WRITE(PCH_TRANS_LINK_M1(pipe), m_n->link_m);
7799         I915_WRITE(PCH_TRANS_LINK_N1(pipe), m_n->link_n);
7800 }
7801
7802 static void intel_cpu_transcoder_set_m_n(struct intel_crtc *crtc,
7803                                          struct intel_link_m_n *m_n,
7804                                          struct intel_link_m_n *m2_n2)
7805 {
7806         struct drm_device *dev = crtc->base.dev;
7807         struct drm_i915_private *dev_priv = to_i915(dev);
7808         int pipe = crtc->pipe;
7809         enum transcoder transcoder = crtc->config->cpu_transcoder;
7810
7811         if (INTEL_INFO(dev)->gen >= 5) {
7812                 I915_WRITE(PIPE_DATA_M1(transcoder), TU_SIZE(m_n->tu) | m_n->gmch_m);
7813                 I915_WRITE(PIPE_DATA_N1(transcoder), m_n->gmch_n);
7814                 I915_WRITE(PIPE_LINK_M1(transcoder), m_n->link_m);
7815                 I915_WRITE(PIPE_LINK_N1(transcoder), m_n->link_n);
7816                 /* M2_N2 registers to be set only for gen < 8 (M2_N2 available
7817                  * for gen < 8) and if DRRS is supported (to make sure the
7818                  * registers are not unnecessarily accessed).
7819                  */
7820                 if (m2_n2 && (IS_CHERRYVIEW(dev_priv) ||
7821                     INTEL_GEN(dev_priv) < 8) && crtc->config->has_drrs) {
7822                         I915_WRITE(PIPE_DATA_M2(transcoder),
7823                                         TU_SIZE(m2_n2->tu) | m2_n2->gmch_m);
7824                         I915_WRITE(PIPE_DATA_N2(transcoder), m2_n2->gmch_n);
7825                         I915_WRITE(PIPE_LINK_M2(transcoder), m2_n2->link_m);
7826                         I915_WRITE(PIPE_LINK_N2(transcoder), m2_n2->link_n);
7827                 }
7828         } else {
7829                 I915_WRITE(PIPE_DATA_M_G4X(pipe), TU_SIZE(m_n->tu) | m_n->gmch_m);
7830                 I915_WRITE(PIPE_DATA_N_G4X(pipe), m_n->gmch_n);
7831                 I915_WRITE(PIPE_LINK_M_G4X(pipe), m_n->link_m);
7832                 I915_WRITE(PIPE_LINK_N_G4X(pipe), m_n->link_n);
7833         }
7834 }
7835
7836 void intel_dp_set_m_n(struct intel_crtc *crtc, enum link_m_n_set m_n)
7837 {
7838         struct intel_link_m_n *dp_m_n, *dp_m2_n2 = NULL;
7839
7840         if (m_n == M1_N1) {
7841                 dp_m_n = &crtc->config->dp_m_n;
7842                 dp_m2_n2 = &crtc->config->dp_m2_n2;
7843         } else if (m_n == M2_N2) {
7844
7845                 /*
7846                  * M2_N2 registers are not supported. Hence m2_n2 divider value
7847                  * needs to be programmed into M1_N1.
7848                  */
7849                 dp_m_n = &crtc->config->dp_m2_n2;
7850         } else {
7851                 DRM_ERROR("Unsupported divider value\n");
7852                 return;
7853         }
7854
7855         if (crtc->config->has_pch_encoder)
7856                 intel_pch_transcoder_set_m_n(crtc, &crtc->config->dp_m_n);
7857         else
7858                 intel_cpu_transcoder_set_m_n(crtc, dp_m_n, dp_m2_n2);
7859 }
7860
7861 static void vlv_compute_dpll(struct intel_crtc *crtc,
7862                              struct intel_crtc_state *pipe_config)
7863 {
7864         pipe_config->dpll_hw_state.dpll = DPLL_INTEGRATED_REF_CLK_VLV |
7865                 DPLL_REF_CLK_ENABLE_VLV | DPLL_VGA_MODE_DIS;
7866         if (crtc->pipe != PIPE_A)
7867                 pipe_config->dpll_hw_state.dpll |= DPLL_INTEGRATED_CRI_CLK_VLV;
7868
7869         /* DPLL not used with DSI, but still need the rest set up */
7870         if (!intel_crtc_has_type(pipe_config, INTEL_OUTPUT_DSI))
7871                 pipe_config->dpll_hw_state.dpll |= DPLL_VCO_ENABLE |
7872                         DPLL_EXT_BUFFER_ENABLE_VLV;
7873
7874         pipe_config->dpll_hw_state.dpll_md =
7875                 (pipe_config->pixel_multiplier - 1) << DPLL_MD_UDI_MULTIPLIER_SHIFT;
7876 }
7877
7878 static void chv_compute_dpll(struct intel_crtc *crtc,
7879                              struct intel_crtc_state *pipe_config)
7880 {
7881         pipe_config->dpll_hw_state.dpll = DPLL_SSC_REF_CLK_CHV |
7882                 DPLL_REF_CLK_ENABLE_VLV | DPLL_VGA_MODE_DIS;
7883         if (crtc->pipe != PIPE_A)
7884                 pipe_config->dpll_hw_state.dpll |= DPLL_INTEGRATED_CRI_CLK_VLV;
7885
7886         /* DPLL not used with DSI, but still need the rest set up */
7887         if (!intel_crtc_has_type(pipe_config, INTEL_OUTPUT_DSI))
7888                 pipe_config->dpll_hw_state.dpll |= DPLL_VCO_ENABLE;
7889
7890         pipe_config->dpll_hw_state.dpll_md =
7891                 (pipe_config->pixel_multiplier - 1) << DPLL_MD_UDI_MULTIPLIER_SHIFT;
7892 }
7893
7894 static void vlv_prepare_pll(struct intel_crtc *crtc,
7895                             const struct intel_crtc_state *pipe_config)
7896 {
7897         struct drm_device *dev = crtc->base.dev;
7898         struct drm_i915_private *dev_priv = to_i915(dev);
7899         enum pipe pipe = crtc->pipe;
7900         u32 mdiv;
7901         u32 bestn, bestm1, bestm2, bestp1, bestp2;
7902         u32 coreclk, reg_val;
7903
7904         /* Enable Refclk */
7905         I915_WRITE(DPLL(pipe),
7906                    pipe_config->dpll_hw_state.dpll &
7907                    ~(DPLL_VCO_ENABLE | DPLL_EXT_BUFFER_ENABLE_VLV));
7908
7909         /* No need to actually set up the DPLL with DSI */
7910         if ((pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE) == 0)
7911                 return;
7912
7913         mutex_lock(&dev_priv->sb_lock);
7914
7915         bestn = pipe_config->dpll.n;
7916         bestm1 = pipe_config->dpll.m1;
7917         bestm2 = pipe_config->dpll.m2;
7918         bestp1 = pipe_config->dpll.p1;
7919         bestp2 = pipe_config->dpll.p2;
7920
7921         /* See eDP HDMI DPIO driver vbios notes doc */
7922
7923         /* PLL B needs special handling */
7924         if (pipe == PIPE_B)
7925                 vlv_pllb_recal_opamp(dev_priv, pipe);
7926
7927         /* Set up Tx target for periodic Rcomp update */
7928         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW9_BCAST, 0x0100000f);
7929
7930         /* Disable target IRef on PLL */
7931         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW8(pipe));
7932         reg_val &= 0x00ffffff;
7933         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW8(pipe), reg_val);
7934
7935         /* Disable fast lock */
7936         vlv_dpio_write(dev_priv, pipe, VLV_CMN_DW0, 0x610);
7937
7938         /* Set idtafcrecal before PLL is enabled */
7939         mdiv = ((bestm1 << DPIO_M1DIV_SHIFT) | (bestm2 & DPIO_M2DIV_MASK));
7940         mdiv |= ((bestp1 << DPIO_P1_SHIFT) | (bestp2 << DPIO_P2_SHIFT));
7941         mdiv |= ((bestn << DPIO_N_SHIFT));
7942         mdiv |= (1 << DPIO_K_SHIFT);
7943
7944         /*
7945          * Post divider depends on pixel clock rate, DAC vs digital (and LVDS,
7946          * but we don't support that).
7947          * Note: don't use the DAC post divider as it seems unstable.
7948          */
7949         mdiv |= (DPIO_POST_DIV_HDMIDP << DPIO_POST_DIV_SHIFT);
7950         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW3(pipe), mdiv);
7951
7952         mdiv |= DPIO_ENABLE_CALIBRATION;
7953         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW3(pipe), mdiv);
7954
7955         /* Set HBR and RBR LPF coefficients */
7956         if (pipe_config->port_clock == 162000 ||
7957             intel_crtc_has_type(crtc->config, INTEL_OUTPUT_ANALOG) ||
7958             intel_crtc_has_type(crtc->config, INTEL_OUTPUT_HDMI))
7959                 vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW10(pipe),
7960                                  0x009f0003);
7961         else
7962                 vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW10(pipe),
7963                                  0x00d0000f);
7964
7965         if (intel_crtc_has_dp_encoder(pipe_config)) {
7966                 /* Use SSC source */
7967                 if (pipe == PIPE_A)
7968                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
7969                                          0x0df40000);
7970                 else
7971                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
7972                                          0x0df70000);
7973         } else { /* HDMI or VGA */
7974                 /* Use bend source */
7975                 if (pipe == PIPE_A)
7976                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
7977                                          0x0df70000);
7978                 else
7979                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
7980                                          0x0df40000);
7981         }
7982
7983         coreclk = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW7(pipe));
7984         coreclk = (coreclk & 0x0000ff00) | 0x01c00000;
7985         if (intel_crtc_has_dp_encoder(crtc->config))
7986                 coreclk |= 0x01000000;
7987         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW7(pipe), coreclk);
7988
7989         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW11(pipe), 0x87871000);
7990         mutex_unlock(&dev_priv->sb_lock);
7991 }
7992
7993 static void chv_prepare_pll(struct intel_crtc *crtc,
7994                             const struct intel_crtc_state *pipe_config)
7995 {
7996         struct drm_device *dev = crtc->base.dev;
7997         struct drm_i915_private *dev_priv = to_i915(dev);
7998         enum pipe pipe = crtc->pipe;
7999         enum dpio_channel port = vlv_pipe_to_channel(pipe);
8000         u32 loopfilter, tribuf_calcntr;
8001         u32 bestn, bestm1, bestm2, bestp1, bestp2, bestm2_frac;
8002         u32 dpio_val;
8003         int vco;
8004
8005         /* Enable Refclk and SSC */
8006         I915_WRITE(DPLL(pipe),
8007                    pipe_config->dpll_hw_state.dpll & ~DPLL_VCO_ENABLE);
8008
8009         /* No need to actually set up the DPLL with DSI */
8010         if ((pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE) == 0)
8011                 return;
8012
8013         bestn = pipe_config->dpll.n;
8014         bestm2_frac = pipe_config->dpll.m2 & 0x3fffff;
8015         bestm1 = pipe_config->dpll.m1;
8016         bestm2 = pipe_config->dpll.m2 >> 22;
8017         bestp1 = pipe_config->dpll.p1;
8018         bestp2 = pipe_config->dpll.p2;
8019         vco = pipe_config->dpll.vco;
8020         dpio_val = 0;
8021         loopfilter = 0;
8022
8023         mutex_lock(&dev_priv->sb_lock);
8024
8025         /* p1 and p2 divider */
8026         vlv_dpio_write(dev_priv, pipe, CHV_CMN_DW13(port),
8027                         5 << DPIO_CHV_S1_DIV_SHIFT |
8028                         bestp1 << DPIO_CHV_P1_DIV_SHIFT |
8029                         bestp2 << DPIO_CHV_P2_DIV_SHIFT |
8030                         1 << DPIO_CHV_K_DIV_SHIFT);
8031
8032         /* Feedback post-divider - m2 */
8033         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW0(port), bestm2);
8034
8035         /* Feedback refclk divider - n and m1 */
8036         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW1(port),
8037                         DPIO_CHV_M1_DIV_BY_2 |
8038                         1 << DPIO_CHV_N_DIV_SHIFT);
8039
8040         /* M2 fraction division */
8041         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW2(port), bestm2_frac);
8042
8043         /* M2 fraction division enable */
8044         dpio_val = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW3(port));
8045         dpio_val &= ~(DPIO_CHV_FEEDFWD_GAIN_MASK | DPIO_CHV_FRAC_DIV_EN);
8046         dpio_val |= (2 << DPIO_CHV_FEEDFWD_GAIN_SHIFT);
8047         if (bestm2_frac)
8048                 dpio_val |= DPIO_CHV_FRAC_DIV_EN;
8049         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW3(port), dpio_val);
8050
8051         /* Program digital lock detect threshold */
8052         dpio_val = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW9(port));
8053         dpio_val &= ~(DPIO_CHV_INT_LOCK_THRESHOLD_MASK |
8054                                         DPIO_CHV_INT_LOCK_THRESHOLD_SEL_COARSE);
8055         dpio_val |= (0x5 << DPIO_CHV_INT_LOCK_THRESHOLD_SHIFT);
8056         if (!bestm2_frac)
8057                 dpio_val |= DPIO_CHV_INT_LOCK_THRESHOLD_SEL_COARSE;
8058         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW9(port), dpio_val);
8059
8060         /* Loop filter */
8061         if (vco == 5400000) {
8062                 loopfilter |= (0x3 << DPIO_CHV_PROP_COEFF_SHIFT);
8063                 loopfilter |= (0x8 << DPIO_CHV_INT_COEFF_SHIFT);
8064                 loopfilter |= (0x1 << DPIO_CHV_GAIN_CTRL_SHIFT);
8065                 tribuf_calcntr = 0x9;
8066         } else if (vco <= 6200000) {
8067                 loopfilter |= (0x5 << DPIO_CHV_PROP_COEFF_SHIFT);
8068                 loopfilter |= (0xB << DPIO_CHV_INT_COEFF_SHIFT);
8069                 loopfilter |= (0x3 << DPIO_CHV_GAIN_CTRL_SHIFT);
8070                 tribuf_calcntr = 0x9;
8071         } else if (vco <= 6480000) {
8072                 loopfilter |= (0x4 << DPIO_CHV_PROP_COEFF_SHIFT);
8073                 loopfilter |= (0x9 << DPIO_CHV_INT_COEFF_SHIFT);
8074                 loopfilter |= (0x3 << DPIO_CHV_GAIN_CTRL_SHIFT);
8075                 tribuf_calcntr = 0x8;
8076         } else {
8077                 /* Not supported. Apply the same limits as in the max case */
8078                 loopfilter |= (0x4 << DPIO_CHV_PROP_COEFF_SHIFT);
8079                 loopfilter |= (0x9 << DPIO_CHV_INT_COEFF_SHIFT);
8080                 loopfilter |= (0x3 << DPIO_CHV_GAIN_CTRL_SHIFT);
8081                 tribuf_calcntr = 0;
8082         }
8083         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW6(port), loopfilter);
8084
8085         dpio_val = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW8(port));
8086         dpio_val &= ~DPIO_CHV_TDC_TARGET_CNT_MASK;
8087         dpio_val |= (tribuf_calcntr << DPIO_CHV_TDC_TARGET_CNT_SHIFT);
8088         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW8(port), dpio_val);
8089
8090         /* AFC Recal */
8091         vlv_dpio_write(dev_priv, pipe, CHV_CMN_DW14(port),
8092                         vlv_dpio_read(dev_priv, pipe, CHV_CMN_DW14(port)) |
8093                         DPIO_AFC_RECAL);
8094
8095         mutex_unlock(&dev_priv->sb_lock);
8096 }
8097
8098 /**
8099  * vlv_force_pll_on - forcibly enable just the PLL
8100  * @dev_priv: i915 private structure
8101  * @pipe: pipe PLL to enable
8102  * @dpll: PLL configuration
8103  *
8104  * Enable the PLL for @pipe using the supplied @dpll config. To be used
8105  * in cases where we need the PLL enabled even when @pipe is not going to
8106  * be enabled.
8107  */
8108 int vlv_force_pll_on(struct drm_device *dev, enum pipe pipe,
8109                      const struct dpll *dpll)
8110 {
8111         struct intel_crtc *crtc =
8112                 to_intel_crtc(intel_get_crtc_for_pipe(dev, pipe));
8113         struct intel_crtc_state *pipe_config;
8114
8115         pipe_config = kzalloc(sizeof(*pipe_config), GFP_KERNEL);
8116         if (!pipe_config)
8117                 return -ENOMEM;
8118
8119         pipe_config->base.crtc = &crtc->base;
8120         pipe_config->pixel_multiplier = 1;
8121         pipe_config->dpll = *dpll;
8122
8123         if (IS_CHERRYVIEW(to_i915(dev))) {
8124                 chv_compute_dpll(crtc, pipe_config);
8125                 chv_prepare_pll(crtc, pipe_config);
8126                 chv_enable_pll(crtc, pipe_config);
8127         } else {
8128                 vlv_compute_dpll(crtc, pipe_config);
8129                 vlv_prepare_pll(crtc, pipe_config);
8130                 vlv_enable_pll(crtc, pipe_config);
8131         }
8132
8133         kfree(pipe_config);
8134
8135         return 0;
8136 }
8137
8138 /**
8139  * vlv_force_pll_off - forcibly disable just the PLL
8140  * @dev_priv: i915 private structure
8141  * @pipe: pipe PLL to disable
8142  *
8143  * Disable the PLL for @pipe. To be used in cases where we need
8144  * the PLL enabled even when @pipe is not going to be enabled.
8145  */
8146 void vlv_force_pll_off(struct drm_device *dev, enum pipe pipe)
8147 {
8148         if (IS_CHERRYVIEW(to_i915(dev)))
8149                 chv_disable_pll(to_i915(dev), pipe);
8150         else
8151                 vlv_disable_pll(to_i915(dev), pipe);
8152 }
8153
8154 static void i9xx_compute_dpll(struct intel_crtc *crtc,
8155                               struct intel_crtc_state *crtc_state,
8156                               struct dpll *reduced_clock)
8157 {
8158         struct drm_device *dev = crtc->base.dev;
8159         struct drm_i915_private *dev_priv = to_i915(dev);
8160         u32 dpll;
8161         struct dpll *clock = &crtc_state->dpll;
8162
8163         i9xx_update_pll_dividers(crtc, crtc_state, reduced_clock);
8164
8165         dpll = DPLL_VGA_MODE_DIS;
8166
8167         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS))
8168                 dpll |= DPLLB_MODE_LVDS;
8169         else
8170                 dpll |= DPLLB_MODE_DAC_SERIAL;
8171
8172         if (IS_I945G(dev_priv) || IS_I945GM(dev_priv) || IS_G33(dev_priv)) {
8173                 dpll |= (crtc_state->pixel_multiplier - 1)
8174                         << SDVO_MULTIPLIER_SHIFT_HIRES;
8175         }
8176
8177         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_SDVO) ||
8178             intel_crtc_has_type(crtc_state, INTEL_OUTPUT_HDMI))
8179                 dpll |= DPLL_SDVO_HIGH_SPEED;
8180
8181         if (intel_crtc_has_dp_encoder(crtc_state))
8182                 dpll |= DPLL_SDVO_HIGH_SPEED;
8183
8184         /* compute bitmask from p1 value */
8185         if (IS_PINEVIEW(dev))
8186                 dpll |= (1 << (clock->p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT_PINEVIEW;
8187         else {
8188                 dpll |= (1 << (clock->p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT;
8189                 if (IS_G4X(dev_priv) && reduced_clock)
8190                         dpll |= (1 << (reduced_clock->p1 - 1)) << DPLL_FPA1_P1_POST_DIV_SHIFT;
8191         }
8192         switch (clock->p2) {
8193         case 5:
8194                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_5;
8195                 break;
8196         case 7:
8197                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_7;
8198                 break;
8199         case 10:
8200                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_10;
8201                 break;
8202         case 14:
8203                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_14;
8204                 break;
8205         }
8206         if (INTEL_INFO(dev)->gen >= 4)
8207                 dpll |= (6 << PLL_LOAD_PULSE_PHASE_SHIFT);
8208
8209         if (crtc_state->sdvo_tv_clock)
8210                 dpll |= PLL_REF_INPUT_TVCLKINBC;
8211         else if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS) &&
8212                  intel_panel_use_ssc(dev_priv))
8213                 dpll |= PLLB_REF_INPUT_SPREADSPECTRUMIN;
8214         else
8215                 dpll |= PLL_REF_INPUT_DREFCLK;
8216
8217         dpll |= DPLL_VCO_ENABLE;
8218         crtc_state->dpll_hw_state.dpll = dpll;
8219
8220         if (INTEL_INFO(dev)->gen >= 4) {
8221                 u32 dpll_md = (crtc_state->pixel_multiplier - 1)
8222                         << DPLL_MD_UDI_MULTIPLIER_SHIFT;
8223                 crtc_state->dpll_hw_state.dpll_md = dpll_md;
8224         }
8225 }
8226
8227 static void i8xx_compute_dpll(struct intel_crtc *crtc,
8228                               struct intel_crtc_state *crtc_state,
8229                               struct dpll *reduced_clock)
8230 {
8231         struct drm_device *dev = crtc->base.dev;
8232         struct drm_i915_private *dev_priv = to_i915(dev);
8233         u32 dpll;
8234         struct dpll *clock = &crtc_state->dpll;
8235
8236         i9xx_update_pll_dividers(crtc, crtc_state, reduced_clock);
8237
8238         dpll = DPLL_VGA_MODE_DIS;
8239
8240         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
8241                 dpll |= (1 << (clock->p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT;
8242         } else {
8243                 if (clock->p1 == 2)
8244                         dpll |= PLL_P1_DIVIDE_BY_TWO;
8245                 else
8246                         dpll |= (clock->p1 - 2) << DPLL_FPA01_P1_POST_DIV_SHIFT;
8247                 if (clock->p2 == 4)
8248                         dpll |= PLL_P2_DIVIDE_BY_4;
8249         }
8250
8251         if (!IS_I830(dev_priv) &&
8252             intel_crtc_has_type(crtc_state, INTEL_OUTPUT_DVO))
8253                 dpll |= DPLL_DVO_2X_MODE;
8254
8255         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS) &&
8256             intel_panel_use_ssc(dev_priv))
8257                 dpll |= PLLB_REF_INPUT_SPREADSPECTRUMIN;
8258         else
8259                 dpll |= PLL_REF_INPUT_DREFCLK;
8260
8261         dpll |= DPLL_VCO_ENABLE;
8262         crtc_state->dpll_hw_state.dpll = dpll;
8263 }
8264
8265 static void intel_set_pipe_timings(struct intel_crtc *intel_crtc)
8266 {
8267         struct drm_device *dev = intel_crtc->base.dev;
8268         struct drm_i915_private *dev_priv = to_i915(dev);
8269         enum pipe pipe = intel_crtc->pipe;
8270         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
8271         const struct drm_display_mode *adjusted_mode = &intel_crtc->config->base.adjusted_mode;
8272         uint32_t crtc_vtotal, crtc_vblank_end;
8273         int vsyncshift = 0;
8274
8275         /* We need to be careful not to changed the adjusted mode, for otherwise
8276          * the hw state checker will get angry at the mismatch. */
8277         crtc_vtotal = adjusted_mode->crtc_vtotal;
8278         crtc_vblank_end = adjusted_mode->crtc_vblank_end;
8279
8280         if (adjusted_mode->flags & DRM_MODE_FLAG_INTERLACE) {
8281                 /* the chip adds 2 halflines automatically */
8282                 crtc_vtotal -= 1;
8283                 crtc_vblank_end -= 1;
8284
8285                 if (intel_crtc_has_type(intel_crtc->config, INTEL_OUTPUT_SDVO))
8286                         vsyncshift = (adjusted_mode->crtc_htotal - 1) / 2;
8287                 else
8288                         vsyncshift = adjusted_mode->crtc_hsync_start -
8289                                 adjusted_mode->crtc_htotal / 2;
8290                 if (vsyncshift < 0)
8291                         vsyncshift += adjusted_mode->crtc_htotal;
8292         }
8293
8294         if (INTEL_INFO(dev)->gen > 3)
8295                 I915_WRITE(VSYNCSHIFT(cpu_transcoder), vsyncshift);
8296
8297         I915_WRITE(HTOTAL(cpu_transcoder),
8298                    (adjusted_mode->crtc_hdisplay - 1) |
8299                    ((adjusted_mode->crtc_htotal - 1) << 16));
8300         I915_WRITE(HBLANK(cpu_transcoder),
8301                    (adjusted_mode->crtc_hblank_start - 1) |
8302                    ((adjusted_mode->crtc_hblank_end - 1) << 16));
8303         I915_WRITE(HSYNC(cpu_transcoder),
8304                    (adjusted_mode->crtc_hsync_start - 1) |
8305                    ((adjusted_mode->crtc_hsync_end - 1) << 16));
8306
8307         I915_WRITE(VTOTAL(cpu_transcoder),
8308                    (adjusted_mode->crtc_vdisplay - 1) |
8309                    ((crtc_vtotal - 1) << 16));
8310         I915_WRITE(VBLANK(cpu_transcoder),
8311                    (adjusted_mode->crtc_vblank_start - 1) |
8312                    ((crtc_vblank_end - 1) << 16));
8313         I915_WRITE(VSYNC(cpu_transcoder),
8314                    (adjusted_mode->crtc_vsync_start - 1) |
8315                    ((adjusted_mode->crtc_vsync_end - 1) << 16));
8316
8317         /* Workaround: when the EDP input selection is B, the VTOTAL_B must be
8318          * programmed with the VTOTAL_EDP value. Same for VTOTAL_C. This is
8319          * documented on the DDI_FUNC_CTL register description, EDP Input Select
8320          * bits. */
8321         if (IS_HASWELL(dev_priv) && cpu_transcoder == TRANSCODER_EDP &&
8322             (pipe == PIPE_B || pipe == PIPE_C))
8323                 I915_WRITE(VTOTAL(pipe), I915_READ(VTOTAL(cpu_transcoder)));
8324
8325 }
8326
8327 static void intel_set_pipe_src_size(struct intel_crtc *intel_crtc)
8328 {
8329         struct drm_device *dev = intel_crtc->base.dev;
8330         struct drm_i915_private *dev_priv = to_i915(dev);
8331         enum pipe pipe = intel_crtc->pipe;
8332
8333         /* pipesrc controls the size that is scaled from, which should
8334          * always be the user's requested size.
8335          */
8336         I915_WRITE(PIPESRC(pipe),
8337                    ((intel_crtc->config->pipe_src_w - 1) << 16) |
8338                    (intel_crtc->config->pipe_src_h - 1));
8339 }
8340
8341 static void intel_get_pipe_timings(struct intel_crtc *crtc,
8342                                    struct intel_crtc_state *pipe_config)
8343 {
8344         struct drm_device *dev = crtc->base.dev;
8345         struct drm_i915_private *dev_priv = to_i915(dev);
8346         enum transcoder cpu_transcoder = pipe_config->cpu_transcoder;
8347         uint32_t tmp;
8348
8349         tmp = I915_READ(HTOTAL(cpu_transcoder));
8350         pipe_config->base.adjusted_mode.crtc_hdisplay = (tmp & 0xffff) + 1;
8351         pipe_config->base.adjusted_mode.crtc_htotal = ((tmp >> 16) & 0xffff) + 1;
8352         tmp = I915_READ(HBLANK(cpu_transcoder));
8353         pipe_config->base.adjusted_mode.crtc_hblank_start = (tmp & 0xffff) + 1;
8354         pipe_config->base.adjusted_mode.crtc_hblank_end = ((tmp >> 16) & 0xffff) + 1;
8355         tmp = I915_READ(HSYNC(cpu_transcoder));
8356         pipe_config->base.adjusted_mode.crtc_hsync_start = (tmp & 0xffff) + 1;
8357         pipe_config->base.adjusted_mode.crtc_hsync_end = ((tmp >> 16) & 0xffff) + 1;
8358
8359         tmp = I915_READ(VTOTAL(cpu_transcoder));
8360         pipe_config->base.adjusted_mode.crtc_vdisplay = (tmp & 0xffff) + 1;
8361         pipe_config->base.adjusted_mode.crtc_vtotal = ((tmp >> 16) & 0xffff) + 1;
8362         tmp = I915_READ(VBLANK(cpu_transcoder));
8363         pipe_config->base.adjusted_mode.crtc_vblank_start = (tmp & 0xffff) + 1;
8364         pipe_config->base.adjusted_mode.crtc_vblank_end = ((tmp >> 16) & 0xffff) + 1;
8365         tmp = I915_READ(VSYNC(cpu_transcoder));
8366         pipe_config->base.adjusted_mode.crtc_vsync_start = (tmp & 0xffff) + 1;
8367         pipe_config->base.adjusted_mode.crtc_vsync_end = ((tmp >> 16) & 0xffff) + 1;
8368
8369         if (I915_READ(PIPECONF(cpu_transcoder)) & PIPECONF_INTERLACE_MASK) {
8370                 pipe_config->base.adjusted_mode.flags |= DRM_MODE_FLAG_INTERLACE;
8371                 pipe_config->base.adjusted_mode.crtc_vtotal += 1;
8372                 pipe_config->base.adjusted_mode.crtc_vblank_end += 1;
8373         }
8374 }
8375
8376 static void intel_get_pipe_src_size(struct intel_crtc *crtc,
8377                                     struct intel_crtc_state *pipe_config)
8378 {
8379         struct drm_device *dev = crtc->base.dev;
8380         struct drm_i915_private *dev_priv = to_i915(dev);
8381         u32 tmp;
8382
8383         tmp = I915_READ(PIPESRC(crtc->pipe));
8384         pipe_config->pipe_src_h = (tmp & 0xffff) + 1;
8385         pipe_config->pipe_src_w = ((tmp >> 16) & 0xffff) + 1;
8386
8387         pipe_config->base.mode.vdisplay = pipe_config->pipe_src_h;
8388         pipe_config->base.mode.hdisplay = pipe_config->pipe_src_w;
8389 }
8390
8391 void intel_mode_from_pipe_config(struct drm_display_mode *mode,
8392                                  struct intel_crtc_state *pipe_config)
8393 {
8394         mode->hdisplay = pipe_config->base.adjusted_mode.crtc_hdisplay;
8395         mode->htotal = pipe_config->base.adjusted_mode.crtc_htotal;
8396         mode->hsync_start = pipe_config->base.adjusted_mode.crtc_hsync_start;
8397         mode->hsync_end = pipe_config->base.adjusted_mode.crtc_hsync_end;
8398
8399         mode->vdisplay = pipe_config->base.adjusted_mode.crtc_vdisplay;
8400         mode->vtotal = pipe_config->base.adjusted_mode.crtc_vtotal;
8401         mode->vsync_start = pipe_config->base.adjusted_mode.crtc_vsync_start;
8402         mode->vsync_end = pipe_config->base.adjusted_mode.crtc_vsync_end;
8403
8404         mode->flags = pipe_config->base.adjusted_mode.flags;
8405         mode->type = DRM_MODE_TYPE_DRIVER;
8406
8407         mode->clock = pipe_config->base.adjusted_mode.crtc_clock;
8408         mode->flags |= pipe_config->base.adjusted_mode.flags;
8409
8410         mode->hsync = drm_mode_hsync(mode);
8411         mode->vrefresh = drm_mode_vrefresh(mode);
8412         drm_mode_set_name(mode);
8413 }
8414
8415 static void i9xx_set_pipeconf(struct intel_crtc *intel_crtc)
8416 {
8417         struct drm_device *dev = intel_crtc->base.dev;
8418         struct drm_i915_private *dev_priv = to_i915(dev);
8419         uint32_t pipeconf;
8420
8421         pipeconf = 0;
8422
8423         if ((intel_crtc->pipe == PIPE_A && dev_priv->quirks & QUIRK_PIPEA_FORCE) ||
8424             (intel_crtc->pipe == PIPE_B && dev_priv->quirks & QUIRK_PIPEB_FORCE))
8425                 pipeconf |= I915_READ(PIPECONF(intel_crtc->pipe)) & PIPECONF_ENABLE;
8426
8427         if (intel_crtc->config->double_wide)
8428                 pipeconf |= PIPECONF_DOUBLE_WIDE;
8429
8430         /* only g4x and later have fancy bpc/dither controls */
8431         if (IS_G4X(dev_priv) || IS_VALLEYVIEW(dev_priv) ||
8432             IS_CHERRYVIEW(dev_priv)) {
8433                 /* Bspec claims that we can't use dithering for 30bpp pipes. */
8434                 if (intel_crtc->config->dither && intel_crtc->config->pipe_bpp != 30)
8435                         pipeconf |= PIPECONF_DITHER_EN |
8436                                     PIPECONF_DITHER_TYPE_SP;
8437
8438                 switch (intel_crtc->config->pipe_bpp) {
8439                 case 18:
8440                         pipeconf |= PIPECONF_6BPC;
8441                         break;
8442                 case 24:
8443                         pipeconf |= PIPECONF_8BPC;
8444                         break;
8445                 case 30:
8446                         pipeconf |= PIPECONF_10BPC;
8447                         break;
8448                 default:
8449                         /* Case prevented by intel_choose_pipe_bpp_dither. */
8450                         BUG();
8451                 }
8452         }
8453
8454         if (HAS_PIPE_CXSR(dev)) {
8455                 if (intel_crtc->lowfreq_avail) {
8456                         DRM_DEBUG_KMS("enabling CxSR downclocking\n");
8457                         pipeconf |= PIPECONF_CXSR_DOWNCLOCK;
8458                 } else {
8459                         DRM_DEBUG_KMS("disabling CxSR downclocking\n");
8460                 }
8461         }
8462
8463         if (intel_crtc->config->base.adjusted_mode.flags & DRM_MODE_FLAG_INTERLACE) {
8464                 if (INTEL_INFO(dev)->gen < 4 ||
8465                     intel_crtc_has_type(intel_crtc->config, INTEL_OUTPUT_SDVO))
8466                         pipeconf |= PIPECONF_INTERLACE_W_FIELD_INDICATION;
8467                 else
8468                         pipeconf |= PIPECONF_INTERLACE_W_SYNC_SHIFT;
8469         } else
8470                 pipeconf |= PIPECONF_PROGRESSIVE;
8471
8472         if ((IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv)) &&
8473              intel_crtc->config->limited_color_range)
8474                 pipeconf |= PIPECONF_COLOR_RANGE_SELECT;
8475
8476         I915_WRITE(PIPECONF(intel_crtc->pipe), pipeconf);
8477         POSTING_READ(PIPECONF(intel_crtc->pipe));
8478 }
8479
8480 static int i8xx_crtc_compute_clock(struct intel_crtc *crtc,
8481                                    struct intel_crtc_state *crtc_state)
8482 {
8483         struct drm_device *dev = crtc->base.dev;
8484         struct drm_i915_private *dev_priv = to_i915(dev);
8485         const struct intel_limit *limit;
8486         int refclk = 48000;
8487
8488         memset(&crtc_state->dpll_hw_state, 0,
8489                sizeof(crtc_state->dpll_hw_state));
8490
8491         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
8492                 if (intel_panel_use_ssc(dev_priv)) {
8493                         refclk = dev_priv->vbt.lvds_ssc_freq;
8494                         DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n", refclk);
8495                 }
8496
8497                 limit = &intel_limits_i8xx_lvds;
8498         } else if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_DVO)) {
8499                 limit = &intel_limits_i8xx_dvo;
8500         } else {
8501                 limit = &intel_limits_i8xx_dac;
8502         }
8503
8504         if (!crtc_state->clock_set &&
8505             !i9xx_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
8506                                  refclk, NULL, &crtc_state->dpll)) {
8507                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
8508                 return -EINVAL;
8509         }
8510
8511         i8xx_compute_dpll(crtc, crtc_state, NULL);
8512
8513         return 0;
8514 }
8515
8516 static int g4x_crtc_compute_clock(struct intel_crtc *crtc,
8517                                   struct intel_crtc_state *crtc_state)
8518 {
8519         struct drm_device *dev = crtc->base.dev;
8520         struct drm_i915_private *dev_priv = to_i915(dev);
8521         const struct intel_limit *limit;
8522         int refclk = 96000;
8523
8524         memset(&crtc_state->dpll_hw_state, 0,
8525                sizeof(crtc_state->dpll_hw_state));
8526
8527         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
8528                 if (intel_panel_use_ssc(dev_priv)) {
8529                         refclk = dev_priv->vbt.lvds_ssc_freq;
8530                         DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n", refclk);
8531                 }
8532
8533                 if (intel_is_dual_link_lvds(dev))
8534                         limit = &intel_limits_g4x_dual_channel_lvds;
8535                 else
8536                         limit = &intel_limits_g4x_single_channel_lvds;
8537         } else if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_HDMI) ||
8538                    intel_crtc_has_type(crtc_state, INTEL_OUTPUT_ANALOG)) {
8539                 limit = &intel_limits_g4x_hdmi;
8540         } else if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_SDVO)) {
8541                 limit = &intel_limits_g4x_sdvo;
8542         } else {
8543                 /* The option is for other outputs */
8544                 limit = &intel_limits_i9xx_sdvo;
8545         }
8546
8547         if (!crtc_state->clock_set &&
8548             !g4x_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
8549                                 refclk, NULL, &crtc_state->dpll)) {
8550                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
8551                 return -EINVAL;
8552         }
8553
8554         i9xx_compute_dpll(crtc, crtc_state, NULL);
8555
8556         return 0;
8557 }
8558
8559 static int pnv_crtc_compute_clock(struct intel_crtc *crtc,
8560                                   struct intel_crtc_state *crtc_state)
8561 {
8562         struct drm_device *dev = crtc->base.dev;
8563         struct drm_i915_private *dev_priv = to_i915(dev);
8564         const struct intel_limit *limit;
8565         int refclk = 96000;
8566
8567         memset(&crtc_state->dpll_hw_state, 0,
8568                sizeof(crtc_state->dpll_hw_state));
8569
8570         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
8571                 if (intel_panel_use_ssc(dev_priv)) {
8572                         refclk = dev_priv->vbt.lvds_ssc_freq;
8573                         DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n", refclk);
8574                 }
8575
8576                 limit = &intel_limits_pineview_lvds;
8577         } else {
8578                 limit = &intel_limits_pineview_sdvo;
8579         }
8580
8581         if (!crtc_state->clock_set &&
8582             !pnv_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
8583                                 refclk, NULL, &crtc_state->dpll)) {
8584                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
8585                 return -EINVAL;
8586         }
8587
8588         i9xx_compute_dpll(crtc, crtc_state, NULL);
8589
8590         return 0;
8591 }
8592
8593 static int i9xx_crtc_compute_clock(struct intel_crtc *crtc,
8594                                    struct intel_crtc_state *crtc_state)
8595 {
8596         struct drm_device *dev = crtc->base.dev;
8597         struct drm_i915_private *dev_priv = to_i915(dev);
8598         const struct intel_limit *limit;
8599         int refclk = 96000;
8600
8601         memset(&crtc_state->dpll_hw_state, 0,
8602                sizeof(crtc_state->dpll_hw_state));
8603
8604         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
8605                 if (intel_panel_use_ssc(dev_priv)) {
8606                         refclk = dev_priv->vbt.lvds_ssc_freq;
8607                         DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n", refclk);
8608                 }
8609
8610                 limit = &intel_limits_i9xx_lvds;
8611         } else {
8612                 limit = &intel_limits_i9xx_sdvo;
8613         }
8614
8615         if (!crtc_state->clock_set &&
8616             !i9xx_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
8617                                  refclk, NULL, &crtc_state->dpll)) {
8618                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
8619                 return -EINVAL;
8620         }
8621
8622         i9xx_compute_dpll(crtc, crtc_state, NULL);
8623
8624         return 0;
8625 }
8626
8627 static int chv_crtc_compute_clock(struct intel_crtc *crtc,
8628                                   struct intel_crtc_state *crtc_state)
8629 {
8630         int refclk = 100000;
8631         const struct intel_limit *limit = &intel_limits_chv;
8632
8633         memset(&crtc_state->dpll_hw_state, 0,
8634                sizeof(crtc_state->dpll_hw_state));
8635
8636         if (!crtc_state->clock_set &&
8637             !chv_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
8638                                 refclk, NULL, &crtc_state->dpll)) {
8639                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
8640                 return -EINVAL;
8641         }
8642
8643         chv_compute_dpll(crtc, crtc_state);
8644
8645         return 0;
8646 }
8647
8648 static int vlv_crtc_compute_clock(struct intel_crtc *crtc,
8649                                   struct intel_crtc_state *crtc_state)
8650 {
8651         int refclk = 100000;
8652         const struct intel_limit *limit = &intel_limits_vlv;
8653
8654         memset(&crtc_state->dpll_hw_state, 0,
8655                sizeof(crtc_state->dpll_hw_state));
8656
8657         if (!crtc_state->clock_set &&
8658             !vlv_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
8659                                 refclk, NULL, &crtc_state->dpll)) {
8660                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
8661                 return -EINVAL;
8662         }
8663
8664         vlv_compute_dpll(crtc, crtc_state);
8665
8666         return 0;
8667 }
8668
8669 static void i9xx_get_pfit_config(struct intel_crtc *crtc,
8670                                  struct intel_crtc_state *pipe_config)
8671 {
8672         struct drm_device *dev = crtc->base.dev;
8673         struct drm_i915_private *dev_priv = to_i915(dev);
8674         uint32_t tmp;
8675
8676         if (INTEL_GEN(dev_priv) <= 3 &&
8677             (IS_I830(dev_priv) || !IS_MOBILE(dev_priv)))
8678                 return;
8679
8680         tmp = I915_READ(PFIT_CONTROL);
8681         if (!(tmp & PFIT_ENABLE))
8682                 return;
8683
8684         /* Check whether the pfit is attached to our pipe. */
8685         if (INTEL_INFO(dev)->gen < 4) {
8686                 if (crtc->pipe != PIPE_B)
8687                         return;
8688         } else {
8689                 if ((tmp & PFIT_PIPE_MASK) != (crtc->pipe << PFIT_PIPE_SHIFT))
8690                         return;
8691         }
8692
8693         pipe_config->gmch_pfit.control = tmp;
8694         pipe_config->gmch_pfit.pgm_ratios = I915_READ(PFIT_PGM_RATIOS);
8695 }
8696
8697 static void vlv_crtc_clock_get(struct intel_crtc *crtc,
8698                                struct intel_crtc_state *pipe_config)
8699 {
8700         struct drm_device *dev = crtc->base.dev;
8701         struct drm_i915_private *dev_priv = to_i915(dev);
8702         int pipe = pipe_config->cpu_transcoder;
8703         struct dpll clock;
8704         u32 mdiv;
8705         int refclk = 100000;
8706
8707         /* In case of DSI, DPLL will not be used */
8708         if ((pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE) == 0)
8709                 return;
8710
8711         mutex_lock(&dev_priv->sb_lock);
8712         mdiv = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW3(pipe));
8713         mutex_unlock(&dev_priv->sb_lock);
8714
8715         clock.m1 = (mdiv >> DPIO_M1DIV_SHIFT) & 7;
8716         clock.m2 = mdiv & DPIO_M2DIV_MASK;
8717         clock.n = (mdiv >> DPIO_N_SHIFT) & 0xf;
8718         clock.p1 = (mdiv >> DPIO_P1_SHIFT) & 7;
8719         clock.p2 = (mdiv >> DPIO_P2_SHIFT) & 0x1f;
8720
8721         pipe_config->port_clock = vlv_calc_dpll_params(refclk, &clock);
8722 }
8723
8724 static void
8725 i9xx_get_initial_plane_config(struct intel_crtc *crtc,
8726                               struct intel_initial_plane_config *plane_config)
8727 {
8728         struct drm_device *dev = crtc->base.dev;
8729         struct drm_i915_private *dev_priv = to_i915(dev);
8730         u32 val, base, offset;
8731         int pipe = crtc->pipe, plane = crtc->plane;
8732         int fourcc, pixel_format;
8733         unsigned int aligned_height;
8734         struct drm_framebuffer *fb;
8735         struct intel_framebuffer *intel_fb;
8736
8737         val = I915_READ(DSPCNTR(plane));
8738         if (!(val & DISPLAY_PLANE_ENABLE))
8739                 return;
8740
8741         intel_fb = kzalloc(sizeof(*intel_fb), GFP_KERNEL);
8742         if (!intel_fb) {
8743                 DRM_DEBUG_KMS("failed to alloc fb\n");
8744                 return;
8745         }
8746
8747         fb = &intel_fb->base;
8748
8749         if (INTEL_INFO(dev)->gen >= 4) {
8750                 if (val & DISPPLANE_TILED) {
8751                         plane_config->tiling = I915_TILING_X;
8752                         fb->modifier[0] = I915_FORMAT_MOD_X_TILED;
8753                 }
8754         }
8755
8756         pixel_format = val & DISPPLANE_PIXFORMAT_MASK;
8757         fourcc = i9xx_format_to_fourcc(pixel_format);
8758         fb->pixel_format = fourcc;
8759         fb->bits_per_pixel = drm_format_plane_cpp(fourcc, 0) * 8;
8760
8761         if (INTEL_INFO(dev)->gen >= 4) {
8762                 if (plane_config->tiling)
8763                         offset = I915_READ(DSPTILEOFF(plane));
8764                 else
8765                         offset = I915_READ(DSPLINOFF(plane));
8766                 base = I915_READ(DSPSURF(plane)) & 0xfffff000;
8767         } else {
8768                 base = I915_READ(DSPADDR(plane));
8769         }
8770         plane_config->base = base;
8771
8772         val = I915_READ(PIPESRC(pipe));
8773         fb->width = ((val >> 16) & 0xfff) + 1;
8774         fb->height = ((val >> 0) & 0xfff) + 1;
8775
8776         val = I915_READ(DSPSTRIDE(pipe));
8777         fb->pitches[0] = val & 0xffffffc0;
8778
8779         aligned_height = intel_fb_align_height(dev, fb->height,
8780                                                fb->pixel_format,
8781                                                fb->modifier[0]);
8782
8783         plane_config->size = fb->pitches[0] * aligned_height;
8784
8785         DRM_DEBUG_KMS("pipe/plane %c/%d with fb: size=%dx%d@%d, offset=%x, pitch %d, size 0x%x\n",
8786                       pipe_name(pipe), plane, fb->width, fb->height,
8787                       fb->bits_per_pixel, base, fb->pitches[0],
8788                       plane_config->size);
8789
8790         plane_config->fb = intel_fb;
8791 }
8792
8793 static void chv_crtc_clock_get(struct intel_crtc *crtc,
8794                                struct intel_crtc_state *pipe_config)
8795 {
8796         struct drm_device *dev = crtc->base.dev;
8797         struct drm_i915_private *dev_priv = to_i915(dev);
8798         int pipe = pipe_config->cpu_transcoder;
8799         enum dpio_channel port = vlv_pipe_to_channel(pipe);
8800         struct dpll clock;
8801         u32 cmn_dw13, pll_dw0, pll_dw1, pll_dw2, pll_dw3;
8802         int refclk = 100000;
8803
8804         /* In case of DSI, DPLL will not be used */
8805         if ((pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE) == 0)
8806                 return;
8807
8808         mutex_lock(&dev_priv->sb_lock);
8809         cmn_dw13 = vlv_dpio_read(dev_priv, pipe, CHV_CMN_DW13(port));
8810         pll_dw0 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW0(port));
8811         pll_dw1 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW1(port));
8812         pll_dw2 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW2(port));
8813         pll_dw3 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW3(port));
8814         mutex_unlock(&dev_priv->sb_lock);
8815
8816         clock.m1 = (pll_dw1 & 0x7) == DPIO_CHV_M1_DIV_BY_2 ? 2 : 0;
8817         clock.m2 = (pll_dw0 & 0xff) << 22;
8818         if (pll_dw3 & DPIO_CHV_FRAC_DIV_EN)
8819                 clock.m2 |= pll_dw2 & 0x3fffff;
8820         clock.n = (pll_dw1 >> DPIO_CHV_N_DIV_SHIFT) & 0xf;
8821         clock.p1 = (cmn_dw13 >> DPIO_CHV_P1_DIV_SHIFT) & 0x7;
8822         clock.p2 = (cmn_dw13 >> DPIO_CHV_P2_DIV_SHIFT) & 0x1f;
8823
8824         pipe_config->port_clock = chv_calc_dpll_params(refclk, &clock);
8825 }
8826
8827 static bool i9xx_get_pipe_config(struct intel_crtc *crtc,
8828                                  struct intel_crtc_state *pipe_config)
8829 {
8830         struct drm_device *dev = crtc->base.dev;
8831         struct drm_i915_private *dev_priv = to_i915(dev);
8832         enum intel_display_power_domain power_domain;
8833         uint32_t tmp;
8834         bool ret;
8835
8836         power_domain = POWER_DOMAIN_PIPE(crtc->pipe);
8837         if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
8838                 return false;
8839
8840         pipe_config->cpu_transcoder = (enum transcoder) crtc->pipe;
8841         pipe_config->shared_dpll = NULL;
8842
8843         ret = false;
8844
8845         tmp = I915_READ(PIPECONF(crtc->pipe));
8846         if (!(tmp & PIPECONF_ENABLE))
8847                 goto out;
8848
8849         if (IS_G4X(dev_priv) || IS_VALLEYVIEW(dev_priv) ||
8850             IS_CHERRYVIEW(dev_priv)) {
8851                 switch (tmp & PIPECONF_BPC_MASK) {
8852                 case PIPECONF_6BPC:
8853                         pipe_config->pipe_bpp = 18;
8854                         break;
8855                 case PIPECONF_8BPC:
8856                         pipe_config->pipe_bpp = 24;
8857                         break;
8858                 case PIPECONF_10BPC:
8859                         pipe_config->pipe_bpp = 30;
8860                         break;
8861                 default:
8862                         break;
8863                 }
8864         }
8865
8866         if ((IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv)) &&
8867             (tmp & PIPECONF_COLOR_RANGE_SELECT))
8868                 pipe_config->limited_color_range = true;
8869
8870         if (INTEL_INFO(dev)->gen < 4)
8871                 pipe_config->double_wide = tmp & PIPECONF_DOUBLE_WIDE;
8872
8873         intel_get_pipe_timings(crtc, pipe_config);
8874         intel_get_pipe_src_size(crtc, pipe_config);
8875
8876         i9xx_get_pfit_config(crtc, pipe_config);
8877
8878         if (INTEL_INFO(dev)->gen >= 4) {
8879                 /* No way to read it out on pipes B and C */
8880                 if (IS_CHERRYVIEW(dev_priv) && crtc->pipe != PIPE_A)
8881                         tmp = dev_priv->chv_dpll_md[crtc->pipe];
8882                 else
8883                         tmp = I915_READ(DPLL_MD(crtc->pipe));
8884                 pipe_config->pixel_multiplier =
8885                         ((tmp & DPLL_MD_UDI_MULTIPLIER_MASK)
8886                          >> DPLL_MD_UDI_MULTIPLIER_SHIFT) + 1;
8887                 pipe_config->dpll_hw_state.dpll_md = tmp;
8888         } else if (IS_I945G(dev_priv) || IS_I945GM(dev_priv) ||
8889                    IS_G33(dev_priv)) {
8890                 tmp = I915_READ(DPLL(crtc->pipe));
8891                 pipe_config->pixel_multiplier =
8892                         ((tmp & SDVO_MULTIPLIER_MASK)
8893                          >> SDVO_MULTIPLIER_SHIFT_HIRES) + 1;
8894         } else {
8895                 /* Note that on i915G/GM the pixel multiplier is in the sdvo
8896                  * port and will be fixed up in the encoder->get_config
8897                  * function. */
8898                 pipe_config->pixel_multiplier = 1;
8899         }
8900         pipe_config->dpll_hw_state.dpll = I915_READ(DPLL(crtc->pipe));
8901         if (!IS_VALLEYVIEW(dev_priv) && !IS_CHERRYVIEW(dev_priv)) {
8902                 /*
8903                  * DPLL_DVO_2X_MODE must be enabled for both DPLLs
8904                  * on 830. Filter it out here so that we don't
8905                  * report errors due to that.
8906                  */
8907                 if (IS_I830(dev_priv))
8908                         pipe_config->dpll_hw_state.dpll &= ~DPLL_DVO_2X_MODE;
8909
8910                 pipe_config->dpll_hw_state.fp0 = I915_READ(FP0(crtc->pipe));
8911                 pipe_config->dpll_hw_state.fp1 = I915_READ(FP1(crtc->pipe));
8912         } else {
8913                 /* Mask out read-only status bits. */
8914                 pipe_config->dpll_hw_state.dpll &= ~(DPLL_LOCK_VLV |
8915                                                      DPLL_PORTC_READY_MASK |
8916                                                      DPLL_PORTB_READY_MASK);
8917         }
8918
8919         if (IS_CHERRYVIEW(dev_priv))
8920                 chv_crtc_clock_get(crtc, pipe_config);
8921         else if (IS_VALLEYVIEW(dev_priv))
8922                 vlv_crtc_clock_get(crtc, pipe_config);
8923         else
8924                 i9xx_crtc_clock_get(crtc, pipe_config);
8925
8926         /*
8927          * Normally the dotclock is filled in by the encoder .get_config()
8928          * but in case the pipe is enabled w/o any ports we need a sane
8929          * default.
8930          */
8931         pipe_config->base.adjusted_mode.crtc_clock =
8932                 pipe_config->port_clock / pipe_config->pixel_multiplier;
8933
8934         ret = true;
8935
8936 out:
8937         intel_display_power_put(dev_priv, power_domain);
8938
8939         return ret;
8940 }
8941
8942 static void ironlake_init_pch_refclk(struct drm_device *dev)
8943 {
8944         struct drm_i915_private *dev_priv = to_i915(dev);
8945         struct intel_encoder *encoder;
8946         int i;
8947         u32 val, final;
8948         bool has_lvds = false;
8949         bool has_cpu_edp = false;
8950         bool has_panel = false;
8951         bool has_ck505 = false;
8952         bool can_ssc = false;
8953         bool using_ssc_source = false;
8954
8955         /* We need to take the global config into account */
8956         for_each_intel_encoder(dev, encoder) {
8957                 switch (encoder->type) {
8958                 case INTEL_OUTPUT_LVDS:
8959                         has_panel = true;
8960                         has_lvds = true;
8961                         break;
8962                 case INTEL_OUTPUT_EDP:
8963                         has_panel = true;
8964                         if (enc_to_dig_port(&encoder->base)->port == PORT_A)
8965                                 has_cpu_edp = true;
8966                         break;
8967                 default:
8968                         break;
8969                 }
8970         }
8971
8972         if (HAS_PCH_IBX(dev_priv)) {
8973                 has_ck505 = dev_priv->vbt.display_clock_mode;
8974                 can_ssc = has_ck505;
8975         } else {
8976                 has_ck505 = false;
8977                 can_ssc = true;
8978         }
8979
8980         /* Check if any DPLLs are using the SSC source */
8981         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
8982                 u32 temp = I915_READ(PCH_DPLL(i));
8983
8984                 if (!(temp & DPLL_VCO_ENABLE))
8985                         continue;
8986
8987                 if ((temp & PLL_REF_INPUT_MASK) ==
8988                     PLLB_REF_INPUT_SPREADSPECTRUMIN) {
8989                         using_ssc_source = true;
8990                         break;
8991                 }
8992         }
8993
8994         DRM_DEBUG_KMS("has_panel %d has_lvds %d has_ck505 %d using_ssc_source %d\n",
8995                       has_panel, has_lvds, has_ck505, using_ssc_source);
8996
8997         /* Ironlake: try to setup display ref clock before DPLL
8998          * enabling. This is only under driver's control after
8999          * PCH B stepping, previous chipset stepping should be
9000          * ignoring this setting.
9001          */
9002         val = I915_READ(PCH_DREF_CONTROL);
9003
9004         /* As we must carefully and slowly disable/enable each source in turn,
9005          * compute the final state we want first and check if we need to
9006          * make any changes at all.
9007          */
9008         final = val;
9009         final &= ~DREF_NONSPREAD_SOURCE_MASK;
9010         if (has_ck505)
9011                 final |= DREF_NONSPREAD_CK505_ENABLE;
9012         else
9013                 final |= DREF_NONSPREAD_SOURCE_ENABLE;
9014
9015         final &= ~DREF_SSC_SOURCE_MASK;
9016         final &= ~DREF_CPU_SOURCE_OUTPUT_MASK;
9017         final &= ~DREF_SSC1_ENABLE;
9018
9019         if (has_panel) {
9020                 final |= DREF_SSC_SOURCE_ENABLE;
9021
9022                 if (intel_panel_use_ssc(dev_priv) && can_ssc)
9023                         final |= DREF_SSC1_ENABLE;
9024
9025                 if (has_cpu_edp) {
9026                         if (intel_panel_use_ssc(dev_priv) && can_ssc)
9027                                 final |= DREF_CPU_SOURCE_OUTPUT_DOWNSPREAD;
9028                         else
9029                                 final |= DREF_CPU_SOURCE_OUTPUT_NONSPREAD;
9030                 } else
9031                         final |= DREF_CPU_SOURCE_OUTPUT_DISABLE;
9032         } else if (using_ssc_source) {
9033                 final |= DREF_SSC_SOURCE_ENABLE;
9034                 final |= DREF_SSC1_ENABLE;
9035         }
9036
9037         if (final == val)
9038                 return;
9039
9040         /* Always enable nonspread source */
9041         val &= ~DREF_NONSPREAD_SOURCE_MASK;
9042
9043         if (has_ck505)
9044                 val |= DREF_NONSPREAD_CK505_ENABLE;
9045         else
9046                 val |= DREF_NONSPREAD_SOURCE_ENABLE;
9047
9048         if (has_panel) {
9049                 val &= ~DREF_SSC_SOURCE_MASK;
9050                 val |= DREF_SSC_SOURCE_ENABLE;
9051
9052                 /* SSC must be turned on before enabling the CPU output  */
9053                 if (intel_panel_use_ssc(dev_priv) && can_ssc) {
9054                         DRM_DEBUG_KMS("Using SSC on panel\n");
9055                         val |= DREF_SSC1_ENABLE;
9056                 } else
9057                         val &= ~DREF_SSC1_ENABLE;
9058
9059                 /* Get SSC going before enabling the outputs */
9060                 I915_WRITE(PCH_DREF_CONTROL, val);
9061                 POSTING_READ(PCH_DREF_CONTROL);
9062                 udelay(200);
9063
9064                 val &= ~DREF_CPU_SOURCE_OUTPUT_MASK;
9065
9066                 /* Enable CPU source on CPU attached eDP */
9067                 if (has_cpu_edp) {
9068                         if (intel_panel_use_ssc(dev_priv) && can_ssc) {
9069                                 DRM_DEBUG_KMS("Using SSC on eDP\n");
9070                                 val |= DREF_CPU_SOURCE_OUTPUT_DOWNSPREAD;
9071                         } else
9072                                 val |= DREF_CPU_SOURCE_OUTPUT_NONSPREAD;
9073                 } else
9074                         val |= DREF_CPU_SOURCE_OUTPUT_DISABLE;
9075
9076                 I915_WRITE(PCH_DREF_CONTROL, val);
9077                 POSTING_READ(PCH_DREF_CONTROL);
9078                 udelay(200);
9079         } else {
9080                 DRM_DEBUG_KMS("Disabling CPU source output\n");
9081
9082                 val &= ~DREF_CPU_SOURCE_OUTPUT_MASK;
9083
9084                 /* Turn off CPU output */
9085                 val |= DREF_CPU_SOURCE_OUTPUT_DISABLE;
9086
9087                 I915_WRITE(PCH_DREF_CONTROL, val);
9088                 POSTING_READ(PCH_DREF_CONTROL);
9089                 udelay(200);
9090
9091                 if (!using_ssc_source) {
9092                         DRM_DEBUG_KMS("Disabling SSC source\n");
9093
9094                         /* Turn off the SSC source */
9095                         val &= ~DREF_SSC_SOURCE_MASK;
9096                         val |= DREF_SSC_SOURCE_DISABLE;
9097
9098                         /* Turn off SSC1 */
9099                         val &= ~DREF_SSC1_ENABLE;
9100
9101                         I915_WRITE(PCH_DREF_CONTROL, val);
9102                         POSTING_READ(PCH_DREF_CONTROL);
9103                         udelay(200);
9104                 }
9105         }
9106
9107         BUG_ON(val != final);
9108 }
9109
9110 static void lpt_reset_fdi_mphy(struct drm_i915_private *dev_priv)
9111 {
9112         uint32_t tmp;
9113
9114         tmp = I915_READ(SOUTH_CHICKEN2);
9115         tmp |= FDI_MPHY_IOSFSB_RESET_CTL;
9116         I915_WRITE(SOUTH_CHICKEN2, tmp);
9117
9118         if (wait_for_us(I915_READ(SOUTH_CHICKEN2) &
9119                         FDI_MPHY_IOSFSB_RESET_STATUS, 100))
9120                 DRM_ERROR("FDI mPHY reset assert timeout\n");
9121
9122         tmp = I915_READ(SOUTH_CHICKEN2);
9123         tmp &= ~FDI_MPHY_IOSFSB_RESET_CTL;
9124         I915_WRITE(SOUTH_CHICKEN2, tmp);
9125
9126         if (wait_for_us((I915_READ(SOUTH_CHICKEN2) &
9127                          FDI_MPHY_IOSFSB_RESET_STATUS) == 0, 100))
9128                 DRM_ERROR("FDI mPHY reset de-assert timeout\n");
9129 }
9130
9131 /* WaMPhyProgramming:hsw */
9132 static void lpt_program_fdi_mphy(struct drm_i915_private *dev_priv)
9133 {
9134         uint32_t tmp;
9135
9136         tmp = intel_sbi_read(dev_priv, 0x8008, SBI_MPHY);
9137         tmp &= ~(0xFF << 24);
9138         tmp |= (0x12 << 24);
9139         intel_sbi_write(dev_priv, 0x8008, tmp, SBI_MPHY);
9140
9141         tmp = intel_sbi_read(dev_priv, 0x2008, SBI_MPHY);
9142         tmp |= (1 << 11);
9143         intel_sbi_write(dev_priv, 0x2008, tmp, SBI_MPHY);
9144
9145         tmp = intel_sbi_read(dev_priv, 0x2108, SBI_MPHY);
9146         tmp |= (1 << 11);
9147         intel_sbi_write(dev_priv, 0x2108, tmp, SBI_MPHY);
9148
9149         tmp = intel_sbi_read(dev_priv, 0x206C, SBI_MPHY);
9150         tmp |= (1 << 24) | (1 << 21) | (1 << 18);
9151         intel_sbi_write(dev_priv, 0x206C, tmp, SBI_MPHY);
9152
9153         tmp = intel_sbi_read(dev_priv, 0x216C, SBI_MPHY);
9154         tmp |= (1 << 24) | (1 << 21) | (1 << 18);
9155         intel_sbi_write(dev_priv, 0x216C, tmp, SBI_MPHY);
9156
9157         tmp = intel_sbi_read(dev_priv, 0x2080, SBI_MPHY);
9158         tmp &= ~(7 << 13);
9159         tmp |= (5 << 13);
9160         intel_sbi_write(dev_priv, 0x2080, tmp, SBI_MPHY);
9161
9162         tmp = intel_sbi_read(dev_priv, 0x2180, SBI_MPHY);
9163         tmp &= ~(7 << 13);
9164         tmp |= (5 << 13);
9165         intel_sbi_write(dev_priv, 0x2180, tmp, SBI_MPHY);
9166
9167         tmp = intel_sbi_read(dev_priv, 0x208C, SBI_MPHY);
9168         tmp &= ~0xFF;
9169         tmp |= 0x1C;
9170         intel_sbi_write(dev_priv, 0x208C, tmp, SBI_MPHY);
9171
9172         tmp = intel_sbi_read(dev_priv, 0x218C, SBI_MPHY);
9173         tmp &= ~0xFF;
9174         tmp |= 0x1C;
9175         intel_sbi_write(dev_priv, 0x218C, tmp, SBI_MPHY);
9176
9177         tmp = intel_sbi_read(dev_priv, 0x2098, SBI_MPHY);
9178         tmp &= ~(0xFF << 16);
9179         tmp |= (0x1C << 16);
9180         intel_sbi_write(dev_priv, 0x2098, tmp, SBI_MPHY);
9181
9182         tmp = intel_sbi_read(dev_priv, 0x2198, SBI_MPHY);
9183         tmp &= ~(0xFF << 16);
9184         tmp |= (0x1C << 16);
9185         intel_sbi_write(dev_priv, 0x2198, tmp, SBI_MPHY);
9186
9187         tmp = intel_sbi_read(dev_priv, 0x20C4, SBI_MPHY);
9188         tmp |= (1 << 27);
9189         intel_sbi_write(dev_priv, 0x20C4, tmp, SBI_MPHY);
9190
9191         tmp = intel_sbi_read(dev_priv, 0x21C4, SBI_MPHY);
9192         tmp |= (1 << 27);
9193         intel_sbi_write(dev_priv, 0x21C4, tmp, SBI_MPHY);
9194
9195         tmp = intel_sbi_read(dev_priv, 0x20EC, SBI_MPHY);
9196         tmp &= ~(0xF << 28);
9197         tmp |= (4 << 28);
9198         intel_sbi_write(dev_priv, 0x20EC, tmp, SBI_MPHY);
9199
9200         tmp = intel_sbi_read(dev_priv, 0x21EC, SBI_MPHY);
9201         tmp &= ~(0xF << 28);
9202         tmp |= (4 << 28);
9203         intel_sbi_write(dev_priv, 0x21EC, tmp, SBI_MPHY);
9204 }
9205
9206 /* Implements 3 different sequences from BSpec chapter "Display iCLK
9207  * Programming" based on the parameters passed:
9208  * - Sequence to enable CLKOUT_DP
9209  * - Sequence to enable CLKOUT_DP without spread
9210  * - Sequence to enable CLKOUT_DP for FDI usage and configure PCH FDI I/O
9211  */
9212 static void lpt_enable_clkout_dp(struct drm_device *dev, bool with_spread,
9213                                  bool with_fdi)
9214 {
9215         struct drm_i915_private *dev_priv = to_i915(dev);
9216         uint32_t reg, tmp;
9217
9218         if (WARN(with_fdi && !with_spread, "FDI requires downspread\n"))
9219                 with_spread = true;
9220         if (WARN(HAS_PCH_LPT_LP(dev_priv) &&
9221             with_fdi, "LP PCH doesn't have FDI\n"))
9222                 with_fdi = false;
9223
9224         mutex_lock(&dev_priv->sb_lock);
9225
9226         tmp = intel_sbi_read(dev_priv, SBI_SSCCTL, SBI_ICLK);
9227         tmp &= ~SBI_SSCCTL_DISABLE;
9228         tmp |= SBI_SSCCTL_PATHALT;
9229         intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
9230
9231         udelay(24);
9232
9233         if (with_spread) {
9234                 tmp = intel_sbi_read(dev_priv, SBI_SSCCTL, SBI_ICLK);
9235                 tmp &= ~SBI_SSCCTL_PATHALT;
9236                 intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
9237
9238                 if (with_fdi) {
9239                         lpt_reset_fdi_mphy(dev_priv);
9240                         lpt_program_fdi_mphy(dev_priv);
9241                 }
9242         }
9243
9244         reg = HAS_PCH_LPT_LP(dev_priv) ? SBI_GEN0 : SBI_DBUFF0;
9245         tmp = intel_sbi_read(dev_priv, reg, SBI_ICLK);
9246         tmp |= SBI_GEN0_CFG_BUFFENABLE_DISABLE;
9247         intel_sbi_write(dev_priv, reg, tmp, SBI_ICLK);
9248
9249         mutex_unlock(&dev_priv->sb_lock);
9250 }
9251
9252 /* Sequence to disable CLKOUT_DP */
9253 static void lpt_disable_clkout_dp(struct drm_device *dev)
9254 {
9255         struct drm_i915_private *dev_priv = to_i915(dev);
9256         uint32_t reg, tmp;
9257
9258         mutex_lock(&dev_priv->sb_lock);
9259
9260         reg = HAS_PCH_LPT_LP(dev_priv) ? SBI_GEN0 : SBI_DBUFF0;
9261         tmp = intel_sbi_read(dev_priv, reg, SBI_ICLK);
9262         tmp &= ~SBI_GEN0_CFG_BUFFENABLE_DISABLE;
9263         intel_sbi_write(dev_priv, reg, tmp, SBI_ICLK);
9264
9265         tmp = intel_sbi_read(dev_priv, SBI_SSCCTL, SBI_ICLK);
9266         if (!(tmp & SBI_SSCCTL_DISABLE)) {
9267                 if (!(tmp & SBI_SSCCTL_PATHALT)) {
9268                         tmp |= SBI_SSCCTL_PATHALT;
9269                         intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
9270                         udelay(32);
9271                 }
9272                 tmp |= SBI_SSCCTL_DISABLE;
9273                 intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
9274         }
9275
9276         mutex_unlock(&dev_priv->sb_lock);
9277 }
9278
9279 #define BEND_IDX(steps) ((50 + (steps)) / 5)
9280
9281 static const uint16_t sscdivintphase[] = {
9282         [BEND_IDX( 50)] = 0x3B23,
9283         [BEND_IDX( 45)] = 0x3B23,
9284         [BEND_IDX( 40)] = 0x3C23,
9285         [BEND_IDX( 35)] = 0x3C23,
9286         [BEND_IDX( 30)] = 0x3D23,
9287         [BEND_IDX( 25)] = 0x3D23,
9288         [BEND_IDX( 20)] = 0x3E23,
9289         [BEND_IDX( 15)] = 0x3E23,
9290         [BEND_IDX( 10)] = 0x3F23,
9291         [BEND_IDX(  5)] = 0x3F23,
9292         [BEND_IDX(  0)] = 0x0025,
9293         [BEND_IDX( -5)] = 0x0025,
9294         [BEND_IDX(-10)] = 0x0125,
9295         [BEND_IDX(-15)] = 0x0125,
9296         [BEND_IDX(-20)] = 0x0225,
9297         [BEND_IDX(-25)] = 0x0225,
9298         [BEND_IDX(-30)] = 0x0325,
9299         [BEND_IDX(-35)] = 0x0325,
9300         [BEND_IDX(-40)] = 0x0425,
9301         [BEND_IDX(-45)] = 0x0425,
9302         [BEND_IDX(-50)] = 0x0525,
9303 };
9304
9305 /*
9306  * Bend CLKOUT_DP
9307  * steps -50 to 50 inclusive, in steps of 5
9308  * < 0 slow down the clock, > 0 speed up the clock, 0 == no bend (135MHz)
9309  * change in clock period = -(steps / 10) * 5.787 ps
9310  */
9311 static void lpt_bend_clkout_dp(struct drm_i915_private *dev_priv, int steps)
9312 {
9313         uint32_t tmp;
9314         int idx = BEND_IDX(steps);
9315
9316         if (WARN_ON(steps % 5 != 0))
9317                 return;
9318
9319         if (WARN_ON(idx >= ARRAY_SIZE(sscdivintphase)))
9320                 return;
9321
9322         mutex_lock(&dev_priv->sb_lock);
9323
9324         if (steps % 10 != 0)
9325                 tmp = 0xAAAAAAAB;
9326         else
9327                 tmp = 0x00000000;
9328         intel_sbi_write(dev_priv, SBI_SSCDITHPHASE, tmp, SBI_ICLK);
9329
9330         tmp = intel_sbi_read(dev_priv, SBI_SSCDIVINTPHASE, SBI_ICLK);
9331         tmp &= 0xffff0000;
9332         tmp |= sscdivintphase[idx];
9333         intel_sbi_write(dev_priv, SBI_SSCDIVINTPHASE, tmp, SBI_ICLK);
9334
9335         mutex_unlock(&dev_priv->sb_lock);
9336 }
9337
9338 #undef BEND_IDX
9339
9340 static void lpt_init_pch_refclk(struct drm_device *dev)
9341 {
9342         struct intel_encoder *encoder;
9343         bool has_vga = false;
9344
9345         for_each_intel_encoder(dev, encoder) {
9346                 switch (encoder->type) {
9347                 case INTEL_OUTPUT_ANALOG:
9348                         has_vga = true;
9349                         break;
9350                 default:
9351                         break;
9352                 }
9353         }
9354
9355         if (has_vga) {
9356                 lpt_bend_clkout_dp(to_i915(dev), 0);
9357                 lpt_enable_clkout_dp(dev, true, true);
9358         } else {
9359                 lpt_disable_clkout_dp(dev);
9360         }
9361 }
9362
9363 /*
9364  * Initialize reference clocks when the driver loads
9365  */
9366 void intel_init_pch_refclk(struct drm_device *dev)
9367 {
9368         struct drm_i915_private *dev_priv = to_i915(dev);
9369
9370         if (HAS_PCH_IBX(dev_priv) || HAS_PCH_CPT(dev_priv))
9371                 ironlake_init_pch_refclk(dev);
9372         else if (HAS_PCH_LPT(dev_priv))
9373                 lpt_init_pch_refclk(dev);
9374 }
9375
9376 static void ironlake_set_pipeconf(struct drm_crtc *crtc)
9377 {
9378         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
9379         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
9380         int pipe = intel_crtc->pipe;
9381         uint32_t val;
9382
9383         val = 0;
9384
9385         switch (intel_crtc->config->pipe_bpp) {
9386         case 18:
9387                 val |= PIPECONF_6BPC;
9388                 break;
9389         case 24:
9390                 val |= PIPECONF_8BPC;
9391                 break;
9392         case 30:
9393                 val |= PIPECONF_10BPC;
9394                 break;
9395         case 36:
9396                 val |= PIPECONF_12BPC;
9397                 break;
9398         default:
9399                 /* Case prevented by intel_choose_pipe_bpp_dither. */
9400                 BUG();
9401         }
9402
9403         if (intel_crtc->config->dither)
9404                 val |= (PIPECONF_DITHER_EN | PIPECONF_DITHER_TYPE_SP);
9405
9406         if (intel_crtc->config->base.adjusted_mode.flags & DRM_MODE_FLAG_INTERLACE)
9407                 val |= PIPECONF_INTERLACED_ILK;
9408         else
9409                 val |= PIPECONF_PROGRESSIVE;
9410
9411         if (intel_crtc->config->limited_color_range)
9412                 val |= PIPECONF_COLOR_RANGE_SELECT;
9413
9414         I915_WRITE(PIPECONF(pipe), val);
9415         POSTING_READ(PIPECONF(pipe));
9416 }
9417
9418 static void haswell_set_pipeconf(struct drm_crtc *crtc)
9419 {
9420         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
9421         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
9422         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
9423         u32 val = 0;
9424
9425         if (IS_HASWELL(dev_priv) && intel_crtc->config->dither)
9426                 val |= (PIPECONF_DITHER_EN | PIPECONF_DITHER_TYPE_SP);
9427
9428         if (intel_crtc->config->base.adjusted_mode.flags & DRM_MODE_FLAG_INTERLACE)
9429                 val |= PIPECONF_INTERLACED_ILK;
9430         else
9431                 val |= PIPECONF_PROGRESSIVE;
9432
9433         I915_WRITE(PIPECONF(cpu_transcoder), val);
9434         POSTING_READ(PIPECONF(cpu_transcoder));
9435 }
9436
9437 static void haswell_set_pipemisc(struct drm_crtc *crtc)
9438 {
9439         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
9440         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
9441
9442         if (IS_BROADWELL(dev_priv) || INTEL_INFO(dev_priv)->gen >= 9) {
9443                 u32 val = 0;
9444
9445                 switch (intel_crtc->config->pipe_bpp) {
9446                 case 18:
9447                         val |= PIPEMISC_DITHER_6_BPC;
9448                         break;
9449                 case 24:
9450                         val |= PIPEMISC_DITHER_8_BPC;
9451                         break;
9452                 case 30:
9453                         val |= PIPEMISC_DITHER_10_BPC;
9454                         break;
9455                 case 36:
9456                         val |= PIPEMISC_DITHER_12_BPC;
9457                         break;
9458                 default:
9459                         /* Case prevented by pipe_config_set_bpp. */
9460                         BUG();
9461                 }
9462
9463                 if (intel_crtc->config->dither)
9464                         val |= PIPEMISC_DITHER_ENABLE | PIPEMISC_DITHER_TYPE_SP;
9465
9466                 I915_WRITE(PIPEMISC(intel_crtc->pipe), val);
9467         }
9468 }
9469
9470 int ironlake_get_lanes_required(int target_clock, int link_bw, int bpp)
9471 {
9472         /*
9473          * Account for spread spectrum to avoid
9474          * oversubscribing the link. Max center spread
9475          * is 2.5%; use 5% for safety's sake.
9476          */
9477         u32 bps = target_clock * bpp * 21 / 20;
9478         return DIV_ROUND_UP(bps, link_bw * 8);
9479 }
9480
9481 static bool ironlake_needs_fb_cb_tune(struct dpll *dpll, int factor)
9482 {
9483         return i9xx_dpll_compute_m(dpll) < factor * dpll->n;
9484 }
9485
9486 static void ironlake_compute_dpll(struct intel_crtc *intel_crtc,
9487                                   struct intel_crtc_state *crtc_state,
9488                                   struct dpll *reduced_clock)
9489 {
9490         struct drm_crtc *crtc = &intel_crtc->base;
9491         struct drm_device *dev = crtc->dev;
9492         struct drm_i915_private *dev_priv = to_i915(dev);
9493         u32 dpll, fp, fp2;
9494         int factor;
9495
9496         /* Enable autotuning of the PLL clock (if permissible) */
9497         factor = 21;
9498         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
9499                 if ((intel_panel_use_ssc(dev_priv) &&
9500                      dev_priv->vbt.lvds_ssc_freq == 100000) ||
9501                     (HAS_PCH_IBX(dev_priv) && intel_is_dual_link_lvds(dev)))
9502                         factor = 25;
9503         } else if (crtc_state->sdvo_tv_clock)
9504                 factor = 20;
9505
9506         fp = i9xx_dpll_compute_fp(&crtc_state->dpll);
9507
9508         if (ironlake_needs_fb_cb_tune(&crtc_state->dpll, factor))
9509                 fp |= FP_CB_TUNE;
9510
9511         if (reduced_clock) {
9512                 fp2 = i9xx_dpll_compute_fp(reduced_clock);
9513
9514                 if (reduced_clock->m < factor * reduced_clock->n)
9515                         fp2 |= FP_CB_TUNE;
9516         } else {
9517                 fp2 = fp;
9518         }
9519
9520         dpll = 0;
9521
9522         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS))
9523                 dpll |= DPLLB_MODE_LVDS;
9524         else
9525                 dpll |= DPLLB_MODE_DAC_SERIAL;
9526
9527         dpll |= (crtc_state->pixel_multiplier - 1)
9528                 << PLL_REF_SDVO_HDMI_MULTIPLIER_SHIFT;
9529
9530         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_SDVO) ||
9531             intel_crtc_has_type(crtc_state, INTEL_OUTPUT_HDMI))
9532                 dpll |= DPLL_SDVO_HIGH_SPEED;
9533
9534         if (intel_crtc_has_dp_encoder(crtc_state))
9535                 dpll |= DPLL_SDVO_HIGH_SPEED;
9536
9537         /*
9538          * The high speed IO clock is only really required for
9539          * SDVO/HDMI/DP, but we also enable it for CRT to make it
9540          * possible to share the DPLL between CRT and HDMI. Enabling
9541          * the clock needlessly does no real harm, except use up a
9542          * bit of power potentially.
9543          *
9544          * We'll limit this to IVB with 3 pipes, since it has only two
9545          * DPLLs and so DPLL sharing is the only way to get three pipes
9546          * driving PCH ports at the same time. On SNB we could do this,
9547          * and potentially avoid enabling the second DPLL, but it's not
9548          * clear if it''s a win or loss power wise. No point in doing
9549          * this on ILK at all since it has a fixed DPLL<->pipe mapping.
9550          */
9551         if (INTEL_INFO(dev_priv)->num_pipes == 3 &&
9552             intel_crtc_has_type(crtc_state, INTEL_OUTPUT_ANALOG))
9553                 dpll |= DPLL_SDVO_HIGH_SPEED;
9554
9555         /* compute bitmask from p1 value */
9556         dpll |= (1 << (crtc_state->dpll.p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT;
9557         /* also FPA1 */
9558         dpll |= (1 << (crtc_state->dpll.p1 - 1)) << DPLL_FPA1_P1_POST_DIV_SHIFT;
9559
9560         switch (crtc_state->dpll.p2) {
9561         case 5:
9562                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_5;
9563                 break;
9564         case 7:
9565                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_7;
9566                 break;
9567         case 10:
9568                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_10;
9569                 break;
9570         case 14:
9571                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_14;
9572                 break;
9573         }
9574
9575         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS) &&
9576             intel_panel_use_ssc(dev_priv))
9577                 dpll |= PLLB_REF_INPUT_SPREADSPECTRUMIN;
9578         else
9579                 dpll |= PLL_REF_INPUT_DREFCLK;
9580
9581         dpll |= DPLL_VCO_ENABLE;
9582
9583         crtc_state->dpll_hw_state.dpll = dpll;
9584         crtc_state->dpll_hw_state.fp0 = fp;
9585         crtc_state->dpll_hw_state.fp1 = fp2;
9586 }
9587
9588 static int ironlake_crtc_compute_clock(struct intel_crtc *crtc,
9589                                        struct intel_crtc_state *crtc_state)
9590 {
9591         struct drm_device *dev = crtc->base.dev;
9592         struct drm_i915_private *dev_priv = to_i915(dev);
9593         struct dpll reduced_clock;
9594         bool has_reduced_clock = false;
9595         struct intel_shared_dpll *pll;
9596         const struct intel_limit *limit;
9597         int refclk = 120000;
9598
9599         memset(&crtc_state->dpll_hw_state, 0,
9600                sizeof(crtc_state->dpll_hw_state));
9601
9602         crtc->lowfreq_avail = false;
9603
9604         /* CPU eDP is the only output that doesn't need a PCH PLL of its own. */
9605         if (!crtc_state->has_pch_encoder)
9606                 return 0;
9607
9608         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
9609                 if (intel_panel_use_ssc(dev_priv)) {
9610                         DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n",
9611                                       dev_priv->vbt.lvds_ssc_freq);
9612                         refclk = dev_priv->vbt.lvds_ssc_freq;
9613                 }
9614
9615                 if (intel_is_dual_link_lvds(dev)) {
9616                         if (refclk == 100000)
9617                                 limit = &intel_limits_ironlake_dual_lvds_100m;
9618                         else
9619                                 limit = &intel_limits_ironlake_dual_lvds;
9620                 } else {
9621                         if (refclk == 100000)
9622                                 limit = &intel_limits_ironlake_single_lvds_100m;
9623                         else
9624                                 limit = &intel_limits_ironlake_single_lvds;
9625                 }
9626         } else {
9627                 limit = &intel_limits_ironlake_dac;
9628         }
9629
9630         if (!crtc_state->clock_set &&
9631             !g4x_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
9632                                 refclk, NULL, &crtc_state->dpll)) {
9633                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
9634                 return -EINVAL;
9635         }
9636
9637         ironlake_compute_dpll(crtc, crtc_state,
9638                               has_reduced_clock ? &reduced_clock : NULL);
9639
9640         pll = intel_get_shared_dpll(crtc, crtc_state, NULL);
9641         if (pll == NULL) {
9642                 DRM_DEBUG_DRIVER("failed to find PLL for pipe %c\n",
9643                                  pipe_name(crtc->pipe));
9644                 return -EINVAL;
9645         }
9646
9647         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS) &&
9648             has_reduced_clock)
9649                 crtc->lowfreq_avail = true;
9650
9651         return 0;
9652 }
9653
9654 static void intel_pch_transcoder_get_m_n(struct intel_crtc *crtc,
9655                                          struct intel_link_m_n *m_n)
9656 {
9657         struct drm_device *dev = crtc->base.dev;
9658         struct drm_i915_private *dev_priv = to_i915(dev);
9659         enum pipe pipe = crtc->pipe;
9660
9661         m_n->link_m = I915_READ(PCH_TRANS_LINK_M1(pipe));
9662         m_n->link_n = I915_READ(PCH_TRANS_LINK_N1(pipe));
9663         m_n->gmch_m = I915_READ(PCH_TRANS_DATA_M1(pipe))
9664                 & ~TU_SIZE_MASK;
9665         m_n->gmch_n = I915_READ(PCH_TRANS_DATA_N1(pipe));
9666         m_n->tu = ((I915_READ(PCH_TRANS_DATA_M1(pipe))
9667                     & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
9668 }
9669
9670 static void intel_cpu_transcoder_get_m_n(struct intel_crtc *crtc,
9671                                          enum transcoder transcoder,
9672                                          struct intel_link_m_n *m_n,
9673                                          struct intel_link_m_n *m2_n2)
9674 {
9675         struct drm_device *dev = crtc->base.dev;
9676         struct drm_i915_private *dev_priv = to_i915(dev);
9677         enum pipe pipe = crtc->pipe;
9678
9679         if (INTEL_INFO(dev)->gen >= 5) {
9680                 m_n->link_m = I915_READ(PIPE_LINK_M1(transcoder));
9681                 m_n->link_n = I915_READ(PIPE_LINK_N1(transcoder));
9682                 m_n->gmch_m = I915_READ(PIPE_DATA_M1(transcoder))
9683                         & ~TU_SIZE_MASK;
9684                 m_n->gmch_n = I915_READ(PIPE_DATA_N1(transcoder));
9685                 m_n->tu = ((I915_READ(PIPE_DATA_M1(transcoder))
9686                             & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
9687                 /* Read M2_N2 registers only for gen < 8 (M2_N2 available for
9688                  * gen < 8) and if DRRS is supported (to make sure the
9689                  * registers are not unnecessarily read).
9690                  */
9691                 if (m2_n2 && INTEL_INFO(dev)->gen < 8 &&
9692                         crtc->config->has_drrs) {
9693                         m2_n2->link_m = I915_READ(PIPE_LINK_M2(transcoder));
9694                         m2_n2->link_n = I915_READ(PIPE_LINK_N2(transcoder));
9695                         m2_n2->gmch_m = I915_READ(PIPE_DATA_M2(transcoder))
9696                                         & ~TU_SIZE_MASK;
9697                         m2_n2->gmch_n = I915_READ(PIPE_DATA_N2(transcoder));
9698                         m2_n2->tu = ((I915_READ(PIPE_DATA_M2(transcoder))
9699                                         & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
9700                 }
9701         } else {
9702                 m_n->link_m = I915_READ(PIPE_LINK_M_G4X(pipe));
9703                 m_n->link_n = I915_READ(PIPE_LINK_N_G4X(pipe));
9704                 m_n->gmch_m = I915_READ(PIPE_DATA_M_G4X(pipe))
9705                         & ~TU_SIZE_MASK;
9706                 m_n->gmch_n = I915_READ(PIPE_DATA_N_G4X(pipe));
9707                 m_n->tu = ((I915_READ(PIPE_DATA_M_G4X(pipe))
9708                             & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
9709         }
9710 }
9711
9712 void intel_dp_get_m_n(struct intel_crtc *crtc,
9713                       struct intel_crtc_state *pipe_config)
9714 {
9715         if (pipe_config->has_pch_encoder)
9716                 intel_pch_transcoder_get_m_n(crtc, &pipe_config->dp_m_n);
9717         else
9718                 intel_cpu_transcoder_get_m_n(crtc, pipe_config->cpu_transcoder,
9719                                              &pipe_config->dp_m_n,
9720                                              &pipe_config->dp_m2_n2);
9721 }
9722
9723 static void ironlake_get_fdi_m_n_config(struct intel_crtc *crtc,
9724                                         struct intel_crtc_state *pipe_config)
9725 {
9726         intel_cpu_transcoder_get_m_n(crtc, pipe_config->cpu_transcoder,
9727                                      &pipe_config->fdi_m_n, NULL);
9728 }
9729
9730 static void skylake_get_pfit_config(struct intel_crtc *crtc,
9731                                     struct intel_crtc_state *pipe_config)
9732 {
9733         struct drm_device *dev = crtc->base.dev;
9734         struct drm_i915_private *dev_priv = to_i915(dev);
9735         struct intel_crtc_scaler_state *scaler_state = &pipe_config->scaler_state;
9736         uint32_t ps_ctrl = 0;
9737         int id = -1;
9738         int i;
9739
9740         /* find scaler attached to this pipe */
9741         for (i = 0; i < crtc->num_scalers; i++) {
9742                 ps_ctrl = I915_READ(SKL_PS_CTRL(crtc->pipe, i));
9743                 if (ps_ctrl & PS_SCALER_EN && !(ps_ctrl & PS_PLANE_SEL_MASK)) {
9744                         id = i;
9745                         pipe_config->pch_pfit.enabled = true;
9746                         pipe_config->pch_pfit.pos = I915_READ(SKL_PS_WIN_POS(crtc->pipe, i));
9747                         pipe_config->pch_pfit.size = I915_READ(SKL_PS_WIN_SZ(crtc->pipe, i));
9748                         break;
9749                 }
9750         }
9751
9752         scaler_state->scaler_id = id;
9753         if (id >= 0) {
9754                 scaler_state->scaler_users |= (1 << SKL_CRTC_INDEX);
9755         } else {
9756                 scaler_state->scaler_users &= ~(1 << SKL_CRTC_INDEX);
9757         }
9758 }
9759
9760 static void
9761 skylake_get_initial_plane_config(struct intel_crtc *crtc,
9762                                  struct intel_initial_plane_config *plane_config)
9763 {
9764         struct drm_device *dev = crtc->base.dev;
9765         struct drm_i915_private *dev_priv = to_i915(dev);
9766         u32 val, base, offset, stride_mult, tiling;
9767         int pipe = crtc->pipe;
9768         int fourcc, pixel_format;
9769         unsigned int aligned_height;
9770         struct drm_framebuffer *fb;
9771         struct intel_framebuffer *intel_fb;
9772
9773         intel_fb = kzalloc(sizeof(*intel_fb), GFP_KERNEL);
9774         if (!intel_fb) {
9775                 DRM_DEBUG_KMS("failed to alloc fb\n");
9776                 return;
9777         }
9778
9779         fb = &intel_fb->base;
9780
9781         val = I915_READ(PLANE_CTL(pipe, 0));
9782         if (!(val & PLANE_CTL_ENABLE))
9783                 goto error;
9784
9785         pixel_format = val & PLANE_CTL_FORMAT_MASK;
9786         fourcc = skl_format_to_fourcc(pixel_format,
9787                                       val & PLANE_CTL_ORDER_RGBX,
9788                                       val & PLANE_CTL_ALPHA_MASK);
9789         fb->pixel_format = fourcc;
9790         fb->bits_per_pixel = drm_format_plane_cpp(fourcc, 0) * 8;
9791
9792         tiling = val & PLANE_CTL_TILED_MASK;
9793         switch (tiling) {
9794         case PLANE_CTL_TILED_LINEAR:
9795                 fb->modifier[0] = DRM_FORMAT_MOD_NONE;
9796                 break;
9797         case PLANE_CTL_TILED_X:
9798                 plane_config->tiling = I915_TILING_X;
9799                 fb->modifier[0] = I915_FORMAT_MOD_X_TILED;
9800                 break;
9801         case PLANE_CTL_TILED_Y:
9802                 fb->modifier[0] = I915_FORMAT_MOD_Y_TILED;
9803                 break;
9804         case PLANE_CTL_TILED_YF:
9805                 fb->modifier[0] = I915_FORMAT_MOD_Yf_TILED;
9806                 break;
9807         default:
9808                 MISSING_CASE(tiling);
9809                 goto error;
9810         }
9811
9812         base = I915_READ(PLANE_SURF(pipe, 0)) & 0xfffff000;
9813         plane_config->base = base;
9814
9815         offset = I915_READ(PLANE_OFFSET(pipe, 0));
9816
9817         val = I915_READ(PLANE_SIZE(pipe, 0));
9818         fb->height = ((val >> 16) & 0xfff) + 1;
9819         fb->width = ((val >> 0) & 0x1fff) + 1;
9820
9821         val = I915_READ(PLANE_STRIDE(pipe, 0));
9822         stride_mult = intel_fb_stride_alignment(dev_priv, fb->modifier[0],
9823                                                 fb->pixel_format);
9824         fb->pitches[0] = (val & 0x3ff) * stride_mult;
9825
9826         aligned_height = intel_fb_align_height(dev, fb->height,
9827                                                fb->pixel_format,
9828                                                fb->modifier[0]);
9829
9830         plane_config->size = fb->pitches[0] * aligned_height;
9831
9832         DRM_DEBUG_KMS("pipe %c with fb: size=%dx%d@%d, offset=%x, pitch %d, size 0x%x\n",
9833                       pipe_name(pipe), fb->width, fb->height,
9834                       fb->bits_per_pixel, base, fb->pitches[0],
9835                       plane_config->size);
9836
9837         plane_config->fb = intel_fb;
9838         return;
9839
9840 error:
9841         kfree(intel_fb);
9842 }
9843
9844 static void ironlake_get_pfit_config(struct intel_crtc *crtc,
9845                                      struct intel_crtc_state *pipe_config)
9846 {
9847         struct drm_device *dev = crtc->base.dev;
9848         struct drm_i915_private *dev_priv = to_i915(dev);
9849         uint32_t tmp;
9850
9851         tmp = I915_READ(PF_CTL(crtc->pipe));
9852
9853         if (tmp & PF_ENABLE) {
9854                 pipe_config->pch_pfit.enabled = true;
9855                 pipe_config->pch_pfit.pos = I915_READ(PF_WIN_POS(crtc->pipe));
9856                 pipe_config->pch_pfit.size = I915_READ(PF_WIN_SZ(crtc->pipe));
9857
9858                 /* We currently do not free assignements of panel fitters on
9859                  * ivb/hsw (since we don't use the higher upscaling modes which
9860                  * differentiates them) so just WARN about this case for now. */
9861                 if (IS_GEN7(dev_priv)) {
9862                         WARN_ON((tmp & PF_PIPE_SEL_MASK_IVB) !=
9863                                 PF_PIPE_SEL_IVB(crtc->pipe));
9864                 }
9865         }
9866 }
9867
9868 static void
9869 ironlake_get_initial_plane_config(struct intel_crtc *crtc,
9870                                   struct intel_initial_plane_config *plane_config)
9871 {
9872         struct drm_device *dev = crtc->base.dev;
9873         struct drm_i915_private *dev_priv = to_i915(dev);
9874         u32 val, base, offset;
9875         int pipe = crtc->pipe;
9876         int fourcc, pixel_format;
9877         unsigned int aligned_height;
9878         struct drm_framebuffer *fb;
9879         struct intel_framebuffer *intel_fb;
9880
9881         val = I915_READ(DSPCNTR(pipe));
9882         if (!(val & DISPLAY_PLANE_ENABLE))
9883                 return;
9884
9885         intel_fb = kzalloc(sizeof(*intel_fb), GFP_KERNEL);
9886         if (!intel_fb) {
9887                 DRM_DEBUG_KMS("failed to alloc fb\n");
9888                 return;
9889         }
9890
9891         fb = &intel_fb->base;
9892
9893         if (INTEL_INFO(dev)->gen >= 4) {
9894                 if (val & DISPPLANE_TILED) {
9895                         plane_config->tiling = I915_TILING_X;
9896                         fb->modifier[0] = I915_FORMAT_MOD_X_TILED;
9897                 }
9898         }
9899
9900         pixel_format = val & DISPPLANE_PIXFORMAT_MASK;
9901         fourcc = i9xx_format_to_fourcc(pixel_format);
9902         fb->pixel_format = fourcc;
9903         fb->bits_per_pixel = drm_format_plane_cpp(fourcc, 0) * 8;
9904
9905         base = I915_READ(DSPSURF(pipe)) & 0xfffff000;
9906         if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv)) {
9907                 offset = I915_READ(DSPOFFSET(pipe));
9908         } else {
9909                 if (plane_config->tiling)
9910                         offset = I915_READ(DSPTILEOFF(pipe));
9911                 else
9912                         offset = I915_READ(DSPLINOFF(pipe));
9913         }
9914         plane_config->base = base;
9915
9916         val = I915_READ(PIPESRC(pipe));
9917         fb->width = ((val >> 16) & 0xfff) + 1;
9918         fb->height = ((val >> 0) & 0xfff) + 1;
9919
9920         val = I915_READ(DSPSTRIDE(pipe));
9921         fb->pitches[0] = val & 0xffffffc0;
9922
9923         aligned_height = intel_fb_align_height(dev, fb->height,
9924                                                fb->pixel_format,
9925                                                fb->modifier[0]);
9926
9927         plane_config->size = fb->pitches[0] * aligned_height;
9928
9929         DRM_DEBUG_KMS("pipe %c with fb: size=%dx%d@%d, offset=%x, pitch %d, size 0x%x\n",
9930                       pipe_name(pipe), fb->width, fb->height,
9931                       fb->bits_per_pixel, base, fb->pitches[0],
9932                       plane_config->size);
9933
9934         plane_config->fb = intel_fb;
9935 }
9936
9937 static bool ironlake_get_pipe_config(struct intel_crtc *crtc,
9938                                      struct intel_crtc_state *pipe_config)
9939 {
9940         struct drm_device *dev = crtc->base.dev;
9941         struct drm_i915_private *dev_priv = to_i915(dev);
9942         enum intel_display_power_domain power_domain;
9943         uint32_t tmp;
9944         bool ret;
9945
9946         power_domain = POWER_DOMAIN_PIPE(crtc->pipe);
9947         if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
9948                 return false;
9949
9950         pipe_config->cpu_transcoder = (enum transcoder) crtc->pipe;
9951         pipe_config->shared_dpll = NULL;
9952
9953         ret = false;
9954         tmp = I915_READ(PIPECONF(crtc->pipe));
9955         if (!(tmp & PIPECONF_ENABLE))
9956                 goto out;
9957
9958         switch (tmp & PIPECONF_BPC_MASK) {
9959         case PIPECONF_6BPC:
9960                 pipe_config->pipe_bpp = 18;
9961                 break;
9962         case PIPECONF_8BPC:
9963                 pipe_config->pipe_bpp = 24;
9964                 break;
9965         case PIPECONF_10BPC:
9966                 pipe_config->pipe_bpp = 30;
9967                 break;
9968         case PIPECONF_12BPC:
9969                 pipe_config->pipe_bpp = 36;
9970                 break;
9971         default:
9972                 break;
9973         }
9974
9975         if (tmp & PIPECONF_COLOR_RANGE_SELECT)
9976                 pipe_config->limited_color_range = true;
9977
9978         if (I915_READ(PCH_TRANSCONF(crtc->pipe)) & TRANS_ENABLE) {
9979                 struct intel_shared_dpll *pll;
9980                 enum intel_dpll_id pll_id;
9981
9982                 pipe_config->has_pch_encoder = true;
9983
9984                 tmp = I915_READ(FDI_RX_CTL(crtc->pipe));
9985                 pipe_config->fdi_lanes = ((FDI_DP_PORT_WIDTH_MASK & tmp) >>
9986                                           FDI_DP_PORT_WIDTH_SHIFT) + 1;
9987
9988                 ironlake_get_fdi_m_n_config(crtc, pipe_config);
9989
9990                 if (HAS_PCH_IBX(dev_priv)) {
9991                         /*
9992                          * The pipe->pch transcoder and pch transcoder->pll
9993                          * mapping is fixed.
9994                          */
9995                         pll_id = (enum intel_dpll_id) crtc->pipe;
9996                 } else {
9997                         tmp = I915_READ(PCH_DPLL_SEL);
9998                         if (tmp & TRANS_DPLLB_SEL(crtc->pipe))
9999                                 pll_id = DPLL_ID_PCH_PLL_B;
10000                         else
10001                                 pll_id= DPLL_ID_PCH_PLL_A;
10002                 }
10003
10004                 pipe_config->shared_dpll =
10005                         intel_get_shared_dpll_by_id(dev_priv, pll_id);
10006                 pll = pipe_config->shared_dpll;
10007
10008                 WARN_ON(!pll->funcs.get_hw_state(dev_priv, pll,
10009                                                  &pipe_config->dpll_hw_state));
10010
10011                 tmp = pipe_config->dpll_hw_state.dpll;
10012                 pipe_config->pixel_multiplier =
10013                         ((tmp & PLL_REF_SDVO_HDMI_MULTIPLIER_MASK)
10014                          >> PLL_REF_SDVO_HDMI_MULTIPLIER_SHIFT) + 1;
10015
10016                 ironlake_pch_clock_get(crtc, pipe_config);
10017         } else {
10018                 pipe_config->pixel_multiplier = 1;
10019         }
10020
10021         intel_get_pipe_timings(crtc, pipe_config);
10022         intel_get_pipe_src_size(crtc, pipe_config);
10023
10024         ironlake_get_pfit_config(crtc, pipe_config);
10025
10026         ret = true;
10027
10028 out:
10029         intel_display_power_put(dev_priv, power_domain);
10030
10031         return ret;
10032 }
10033
10034 static void assert_can_disable_lcpll(struct drm_i915_private *dev_priv)
10035 {
10036         struct drm_device *dev = &dev_priv->drm;
10037         struct intel_crtc *crtc;
10038
10039         for_each_intel_crtc(dev, crtc)
10040                 I915_STATE_WARN(crtc->active, "CRTC for pipe %c enabled\n",
10041                      pipe_name(crtc->pipe));
10042
10043         I915_STATE_WARN(I915_READ(HSW_PWR_WELL_DRIVER), "Power well on\n");
10044         I915_STATE_WARN(I915_READ(SPLL_CTL) & SPLL_PLL_ENABLE, "SPLL enabled\n");
10045         I915_STATE_WARN(I915_READ(WRPLL_CTL(0)) & WRPLL_PLL_ENABLE, "WRPLL1 enabled\n");
10046         I915_STATE_WARN(I915_READ(WRPLL_CTL(1)) & WRPLL_PLL_ENABLE, "WRPLL2 enabled\n");
10047         I915_STATE_WARN(I915_READ(PP_STATUS(0)) & PP_ON, "Panel power on\n");
10048         I915_STATE_WARN(I915_READ(BLC_PWM_CPU_CTL2) & BLM_PWM_ENABLE,
10049              "CPU PWM1 enabled\n");
10050         if (IS_HASWELL(dev_priv))
10051                 I915_STATE_WARN(I915_READ(HSW_BLC_PWM2_CTL) & BLM_PWM_ENABLE,
10052                      "CPU PWM2 enabled\n");
10053         I915_STATE_WARN(I915_READ(BLC_PWM_PCH_CTL1) & BLM_PCH_PWM_ENABLE,
10054              "PCH PWM1 enabled\n");
10055         I915_STATE_WARN(I915_READ(UTIL_PIN_CTL) & UTIL_PIN_ENABLE,
10056              "Utility pin enabled\n");
10057         I915_STATE_WARN(I915_READ(PCH_GTC_CTL) & PCH_GTC_ENABLE, "PCH GTC enabled\n");
10058
10059         /*
10060          * In theory we can still leave IRQs enabled, as long as only the HPD
10061          * interrupts remain enabled. We used to check for that, but since it's
10062          * gen-specific and since we only disable LCPLL after we fully disable
10063          * the interrupts, the check below should be enough.
10064          */
10065         I915_STATE_WARN(intel_irqs_enabled(dev_priv), "IRQs enabled\n");
10066 }
10067
10068 static uint32_t hsw_read_dcomp(struct drm_i915_private *dev_priv)
10069 {
10070         if (IS_HASWELL(dev_priv))
10071                 return I915_READ(D_COMP_HSW);
10072         else
10073                 return I915_READ(D_COMP_BDW);
10074 }
10075
10076 static void hsw_write_dcomp(struct drm_i915_private *dev_priv, uint32_t val)
10077 {
10078         if (IS_HASWELL(dev_priv)) {
10079                 mutex_lock(&dev_priv->rps.hw_lock);
10080                 if (sandybridge_pcode_write(dev_priv, GEN6_PCODE_WRITE_D_COMP,
10081                                             val))
10082                         DRM_DEBUG_KMS("Failed to write to D_COMP\n");
10083                 mutex_unlock(&dev_priv->rps.hw_lock);
10084         } else {
10085                 I915_WRITE(D_COMP_BDW, val);
10086                 POSTING_READ(D_COMP_BDW);
10087         }
10088 }
10089
10090 /*
10091  * This function implements pieces of two sequences from BSpec:
10092  * - Sequence for display software to disable LCPLL
10093  * - Sequence for display software to allow package C8+
10094  * The steps implemented here are just the steps that actually touch the LCPLL
10095  * register. Callers should take care of disabling all the display engine
10096  * functions, doing the mode unset, fixing interrupts, etc.
10097  */
10098 static void hsw_disable_lcpll(struct drm_i915_private *dev_priv,
10099                               bool switch_to_fclk, bool allow_power_down)
10100 {
10101         uint32_t val;
10102
10103         assert_can_disable_lcpll(dev_priv);
10104
10105         val = I915_READ(LCPLL_CTL);
10106
10107         if (switch_to_fclk) {
10108                 val |= LCPLL_CD_SOURCE_FCLK;
10109                 I915_WRITE(LCPLL_CTL, val);
10110
10111                 if (wait_for_us(I915_READ(LCPLL_CTL) &
10112                                 LCPLL_CD_SOURCE_FCLK_DONE, 1))
10113                         DRM_ERROR("Switching to FCLK failed\n");
10114
10115                 val = I915_READ(LCPLL_CTL);
10116         }
10117
10118         val |= LCPLL_PLL_DISABLE;
10119         I915_WRITE(LCPLL_CTL, val);
10120         POSTING_READ(LCPLL_CTL);
10121
10122         if (intel_wait_for_register(dev_priv, LCPLL_CTL, LCPLL_PLL_LOCK, 0, 1))
10123                 DRM_ERROR("LCPLL still locked\n");
10124
10125         val = hsw_read_dcomp(dev_priv);
10126         val |= D_COMP_COMP_DISABLE;
10127         hsw_write_dcomp(dev_priv, val);
10128         ndelay(100);
10129
10130         if (wait_for((hsw_read_dcomp(dev_priv) & D_COMP_RCOMP_IN_PROGRESS) == 0,
10131                      1))
10132                 DRM_ERROR("D_COMP RCOMP still in progress\n");
10133
10134         if (allow_power_down) {
10135                 val = I915_READ(LCPLL_CTL);
10136                 val |= LCPLL_POWER_DOWN_ALLOW;
10137                 I915_WRITE(LCPLL_CTL, val);
10138                 POSTING_READ(LCPLL_CTL);
10139         }
10140 }
10141
10142 /*
10143  * Fully restores LCPLL, disallowing power down and switching back to LCPLL
10144  * source.
10145  */
10146 static void hsw_restore_lcpll(struct drm_i915_private *dev_priv)
10147 {
10148         uint32_t val;
10149
10150         val = I915_READ(LCPLL_CTL);
10151
10152         if ((val & (LCPLL_PLL_LOCK | LCPLL_PLL_DISABLE | LCPLL_CD_SOURCE_FCLK |
10153                     LCPLL_POWER_DOWN_ALLOW)) == LCPLL_PLL_LOCK)
10154                 return;
10155
10156         /*
10157          * Make sure we're not on PC8 state before disabling PC8, otherwise
10158          * we'll hang the machine. To prevent PC8 state, just enable force_wake.
10159          */
10160         intel_uncore_forcewake_get(dev_priv, FORCEWAKE_ALL);
10161
10162         if (val & LCPLL_POWER_DOWN_ALLOW) {
10163                 val &= ~LCPLL_POWER_DOWN_ALLOW;
10164                 I915_WRITE(LCPLL_CTL, val);
10165                 POSTING_READ(LCPLL_CTL);
10166         }
10167
10168         val = hsw_read_dcomp(dev_priv);
10169         val |= D_COMP_COMP_FORCE;
10170         val &= ~D_COMP_COMP_DISABLE;
10171         hsw_write_dcomp(dev_priv, val);
10172
10173         val = I915_READ(LCPLL_CTL);
10174         val &= ~LCPLL_PLL_DISABLE;
10175         I915_WRITE(LCPLL_CTL, val);
10176
10177         if (intel_wait_for_register(dev_priv,
10178                                     LCPLL_CTL, LCPLL_PLL_LOCK, LCPLL_PLL_LOCK,
10179                                     5))
10180                 DRM_ERROR("LCPLL not locked yet\n");
10181
10182         if (val & LCPLL_CD_SOURCE_FCLK) {
10183                 val = I915_READ(LCPLL_CTL);
10184                 val &= ~LCPLL_CD_SOURCE_FCLK;
10185                 I915_WRITE(LCPLL_CTL, val);
10186
10187                 if (wait_for_us((I915_READ(LCPLL_CTL) &
10188                                  LCPLL_CD_SOURCE_FCLK_DONE) == 0, 1))
10189                         DRM_ERROR("Switching back to LCPLL failed\n");
10190         }
10191
10192         intel_uncore_forcewake_put(dev_priv, FORCEWAKE_ALL);
10193         intel_update_cdclk(&dev_priv->drm);
10194 }
10195
10196 /*
10197  * Package states C8 and deeper are really deep PC states that can only be
10198  * reached when all the devices on the system allow it, so even if the graphics
10199  * device allows PC8+, it doesn't mean the system will actually get to these
10200  * states. Our driver only allows PC8+ when going into runtime PM.
10201  *
10202  * The requirements for PC8+ are that all the outputs are disabled, the power
10203  * well is disabled and most interrupts are disabled, and these are also
10204  * requirements for runtime PM. When these conditions are met, we manually do
10205  * the other conditions: disable the interrupts, clocks and switch LCPLL refclk
10206  * to Fclk. If we're in PC8+ and we get an non-hotplug interrupt, we can hard
10207  * hang the machine.
10208  *
10209  * When we really reach PC8 or deeper states (not just when we allow it) we lose
10210  * the state of some registers, so when we come back from PC8+ we need to
10211  * restore this state. We don't get into PC8+ if we're not in RC6, so we don't
10212  * need to take care of the registers kept by RC6. Notice that this happens even
10213  * if we don't put the device in PCI D3 state (which is what currently happens
10214  * because of the runtime PM support).
10215  *
10216  * For more, read "Display Sequences for Package C8" on the hardware
10217  * documentation.
10218  */
10219 void hsw_enable_pc8(struct drm_i915_private *dev_priv)
10220 {
10221         struct drm_device *dev = &dev_priv->drm;
10222         uint32_t val;
10223
10224         DRM_DEBUG_KMS("Enabling package C8+\n");
10225
10226         if (HAS_PCH_LPT_LP(dev_priv)) {
10227                 val = I915_READ(SOUTH_DSPCLK_GATE_D);
10228                 val &= ~PCH_LP_PARTITION_LEVEL_DISABLE;
10229                 I915_WRITE(SOUTH_DSPCLK_GATE_D, val);
10230         }
10231
10232         lpt_disable_clkout_dp(dev);
10233         hsw_disable_lcpll(dev_priv, true, true);
10234 }
10235
10236 void hsw_disable_pc8(struct drm_i915_private *dev_priv)
10237 {
10238         struct drm_device *dev = &dev_priv->drm;
10239         uint32_t val;
10240
10241         DRM_DEBUG_KMS("Disabling package C8+\n");
10242
10243         hsw_restore_lcpll(dev_priv);
10244         lpt_init_pch_refclk(dev);
10245
10246         if (HAS_PCH_LPT_LP(dev_priv)) {
10247                 val = I915_READ(SOUTH_DSPCLK_GATE_D);
10248                 val |= PCH_LP_PARTITION_LEVEL_DISABLE;
10249                 I915_WRITE(SOUTH_DSPCLK_GATE_D, val);
10250         }
10251 }
10252
10253 static void bxt_modeset_commit_cdclk(struct drm_atomic_state *old_state)
10254 {
10255         struct drm_device *dev = old_state->dev;
10256         struct intel_atomic_state *old_intel_state =
10257                 to_intel_atomic_state(old_state);
10258         unsigned int req_cdclk = old_intel_state->dev_cdclk;
10259
10260         bxt_set_cdclk(to_i915(dev), req_cdclk);
10261 }
10262
10263 /* compute the max rate for new configuration */
10264 static int ilk_max_pixel_rate(struct drm_atomic_state *state)
10265 {
10266         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
10267         struct drm_i915_private *dev_priv = to_i915(state->dev);
10268         struct drm_crtc *crtc;
10269         struct drm_crtc_state *cstate;
10270         struct intel_crtc_state *crtc_state;
10271         unsigned max_pixel_rate = 0, i;
10272         enum pipe pipe;
10273
10274         memcpy(intel_state->min_pixclk, dev_priv->min_pixclk,
10275                sizeof(intel_state->min_pixclk));
10276
10277         for_each_crtc_in_state(state, crtc, cstate, i) {
10278                 int pixel_rate;
10279
10280                 crtc_state = to_intel_crtc_state(cstate);
10281                 if (!crtc_state->base.enable) {
10282                         intel_state->min_pixclk[i] = 0;
10283                         continue;
10284                 }
10285
10286                 pixel_rate = ilk_pipe_pixel_rate(crtc_state);
10287
10288                 /* pixel rate mustn't exceed 95% of cdclk with IPS on BDW */
10289                 if (IS_BROADWELL(dev_priv) && crtc_state->ips_enabled)
10290                         pixel_rate = DIV_ROUND_UP(pixel_rate * 100, 95);
10291
10292                 intel_state->min_pixclk[i] = pixel_rate;
10293         }
10294
10295         for_each_pipe(dev_priv, pipe)
10296                 max_pixel_rate = max(intel_state->min_pixclk[pipe], max_pixel_rate);
10297
10298         return max_pixel_rate;
10299 }
10300
10301 static void broadwell_set_cdclk(struct drm_device *dev, int cdclk)
10302 {
10303         struct drm_i915_private *dev_priv = to_i915(dev);
10304         uint32_t val, data;
10305         int ret;
10306
10307         if (WARN((I915_READ(LCPLL_CTL) &
10308                   (LCPLL_PLL_DISABLE | LCPLL_PLL_LOCK |
10309                    LCPLL_CD_CLOCK_DISABLE | LCPLL_ROOT_CD_CLOCK_DISABLE |
10310                    LCPLL_CD2X_CLOCK_DISABLE | LCPLL_POWER_DOWN_ALLOW |
10311                    LCPLL_CD_SOURCE_FCLK)) != LCPLL_PLL_LOCK,
10312                  "trying to change cdclk frequency with cdclk not enabled\n"))
10313                 return;
10314
10315         mutex_lock(&dev_priv->rps.hw_lock);
10316         ret = sandybridge_pcode_write(dev_priv,
10317                                       BDW_PCODE_DISPLAY_FREQ_CHANGE_REQ, 0x0);
10318         mutex_unlock(&dev_priv->rps.hw_lock);
10319         if (ret) {
10320                 DRM_ERROR("failed to inform pcode about cdclk change\n");
10321                 return;
10322         }
10323
10324         val = I915_READ(LCPLL_CTL);
10325         val |= LCPLL_CD_SOURCE_FCLK;
10326         I915_WRITE(LCPLL_CTL, val);
10327
10328         if (wait_for_us(I915_READ(LCPLL_CTL) &
10329                         LCPLL_CD_SOURCE_FCLK_DONE, 1))
10330                 DRM_ERROR("Switching to FCLK failed\n");
10331
10332         val = I915_READ(LCPLL_CTL);
10333         val &= ~LCPLL_CLK_FREQ_MASK;
10334
10335         switch (cdclk) {
10336         case 450000:
10337                 val |= LCPLL_CLK_FREQ_450;
10338                 data = 0;
10339                 break;
10340         case 540000:
10341                 val |= LCPLL_CLK_FREQ_54O_BDW;
10342                 data = 1;
10343                 break;
10344         case 337500:
10345                 val |= LCPLL_CLK_FREQ_337_5_BDW;
10346                 data = 2;
10347                 break;
10348         case 675000:
10349                 val |= LCPLL_CLK_FREQ_675_BDW;
10350                 data = 3;
10351                 break;
10352         default:
10353                 WARN(1, "invalid cdclk frequency\n");
10354                 return;
10355         }
10356
10357         I915_WRITE(LCPLL_CTL, val);
10358
10359         val = I915_READ(LCPLL_CTL);
10360         val &= ~LCPLL_CD_SOURCE_FCLK;
10361         I915_WRITE(LCPLL_CTL, val);
10362
10363         if (wait_for_us((I915_READ(LCPLL_CTL) &
10364                         LCPLL_CD_SOURCE_FCLK_DONE) == 0, 1))
10365                 DRM_ERROR("Switching back to LCPLL failed\n");
10366
10367         mutex_lock(&dev_priv->rps.hw_lock);
10368         sandybridge_pcode_write(dev_priv, HSW_PCODE_DE_WRITE_FREQ_REQ, data);
10369         mutex_unlock(&dev_priv->rps.hw_lock);
10370
10371         I915_WRITE(CDCLK_FREQ, DIV_ROUND_CLOSEST(cdclk, 1000) - 1);
10372
10373         intel_update_cdclk(dev);
10374
10375         WARN(cdclk != dev_priv->cdclk_freq,
10376              "cdclk requested %d kHz but got %d kHz\n",
10377              cdclk, dev_priv->cdclk_freq);
10378 }
10379
10380 static int broadwell_calc_cdclk(int max_pixclk)
10381 {
10382         if (max_pixclk > 540000)
10383                 return 675000;
10384         else if (max_pixclk > 450000)
10385                 return 540000;
10386         else if (max_pixclk > 337500)
10387                 return 450000;
10388         else
10389                 return 337500;
10390 }
10391
10392 static int broadwell_modeset_calc_cdclk(struct drm_atomic_state *state)
10393 {
10394         struct drm_i915_private *dev_priv = to_i915(state->dev);
10395         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
10396         int max_pixclk = ilk_max_pixel_rate(state);
10397         int cdclk;
10398
10399         /*
10400          * FIXME should also account for plane ratio
10401          * once 64bpp pixel formats are supported.
10402          */
10403         cdclk = broadwell_calc_cdclk(max_pixclk);
10404
10405         if (cdclk > dev_priv->max_cdclk_freq) {
10406                 DRM_DEBUG_KMS("requested cdclk (%d kHz) exceeds max (%d kHz)\n",
10407                               cdclk, dev_priv->max_cdclk_freq);
10408                 return -EINVAL;
10409         }
10410
10411         intel_state->cdclk = intel_state->dev_cdclk = cdclk;
10412         if (!intel_state->active_crtcs)
10413                 intel_state->dev_cdclk = broadwell_calc_cdclk(0);
10414
10415         return 0;
10416 }
10417
10418 static void broadwell_modeset_commit_cdclk(struct drm_atomic_state *old_state)
10419 {
10420         struct drm_device *dev = old_state->dev;
10421         struct intel_atomic_state *old_intel_state =
10422                 to_intel_atomic_state(old_state);
10423         unsigned req_cdclk = old_intel_state->dev_cdclk;
10424
10425         broadwell_set_cdclk(dev, req_cdclk);
10426 }
10427
10428 static int skl_modeset_calc_cdclk(struct drm_atomic_state *state)
10429 {
10430         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
10431         struct drm_i915_private *dev_priv = to_i915(state->dev);
10432         const int max_pixclk = ilk_max_pixel_rate(state);
10433         int vco = intel_state->cdclk_pll_vco;
10434         int cdclk;
10435
10436         /*
10437          * FIXME should also account for plane ratio
10438          * once 64bpp pixel formats are supported.
10439          */
10440         cdclk = skl_calc_cdclk(max_pixclk, vco);
10441
10442         /*
10443          * FIXME move the cdclk caclulation to
10444          * compute_config() so we can fail gracegully.
10445          */
10446         if (cdclk > dev_priv->max_cdclk_freq) {
10447                 DRM_ERROR("requested cdclk (%d kHz) exceeds max (%d kHz)\n",
10448                           cdclk, dev_priv->max_cdclk_freq);
10449                 cdclk = dev_priv->max_cdclk_freq;
10450         }
10451
10452         intel_state->cdclk = intel_state->dev_cdclk = cdclk;
10453         if (!intel_state->active_crtcs)
10454                 intel_state->dev_cdclk = skl_calc_cdclk(0, vco);
10455
10456         return 0;
10457 }
10458
10459 static void skl_modeset_commit_cdclk(struct drm_atomic_state *old_state)
10460 {
10461         struct drm_i915_private *dev_priv = to_i915(old_state->dev);
10462         struct intel_atomic_state *intel_state = to_intel_atomic_state(old_state);
10463         unsigned int req_cdclk = intel_state->dev_cdclk;
10464         unsigned int req_vco = intel_state->cdclk_pll_vco;
10465
10466         skl_set_cdclk(dev_priv, req_cdclk, req_vco);
10467 }
10468
10469 static int haswell_crtc_compute_clock(struct intel_crtc *crtc,
10470                                       struct intel_crtc_state *crtc_state)
10471 {
10472         if (!intel_crtc_has_type(crtc_state, INTEL_OUTPUT_DSI)) {
10473                 if (!intel_ddi_pll_select(crtc, crtc_state))
10474                         return -EINVAL;
10475         }
10476
10477         crtc->lowfreq_avail = false;
10478
10479         return 0;
10480 }
10481
10482 static void bxt_get_ddi_pll(struct drm_i915_private *dev_priv,
10483                                 enum port port,
10484                                 struct intel_crtc_state *pipe_config)
10485 {
10486         enum intel_dpll_id id;
10487
10488         switch (port) {
10489         case PORT_A:
10490                 id = DPLL_ID_SKL_DPLL0;
10491                 break;
10492         case PORT_B:
10493                 id = DPLL_ID_SKL_DPLL1;
10494                 break;
10495         case PORT_C:
10496                 id = DPLL_ID_SKL_DPLL2;
10497                 break;
10498         default:
10499                 DRM_ERROR("Incorrect port type\n");
10500                 return;
10501         }
10502
10503         pipe_config->shared_dpll = intel_get_shared_dpll_by_id(dev_priv, id);
10504 }
10505
10506 static void skylake_get_ddi_pll(struct drm_i915_private *dev_priv,
10507                                 enum port port,
10508                                 struct intel_crtc_state *pipe_config)
10509 {
10510         enum intel_dpll_id id;
10511         u32 temp;
10512
10513         temp = I915_READ(DPLL_CTRL2) & DPLL_CTRL2_DDI_CLK_SEL_MASK(port);
10514         id = temp >> (port * 3 + 1);
10515
10516         if (WARN_ON(id < SKL_DPLL0 || id > SKL_DPLL3))
10517                 return;
10518
10519         pipe_config->shared_dpll = intel_get_shared_dpll_by_id(dev_priv, id);
10520 }
10521
10522 static void haswell_get_ddi_pll(struct drm_i915_private *dev_priv,
10523                                 enum port port,
10524                                 struct intel_crtc_state *pipe_config)
10525 {
10526         enum intel_dpll_id id;
10527         uint32_t ddi_pll_sel = I915_READ(PORT_CLK_SEL(port));
10528
10529         switch (ddi_pll_sel) {
10530         case PORT_CLK_SEL_WRPLL1:
10531                 id = DPLL_ID_WRPLL1;
10532                 break;
10533         case PORT_CLK_SEL_WRPLL2:
10534                 id = DPLL_ID_WRPLL2;
10535                 break;
10536         case PORT_CLK_SEL_SPLL:
10537                 id = DPLL_ID_SPLL;
10538                 break;
10539         case PORT_CLK_SEL_LCPLL_810:
10540                 id = DPLL_ID_LCPLL_810;
10541                 break;
10542         case PORT_CLK_SEL_LCPLL_1350:
10543                 id = DPLL_ID_LCPLL_1350;
10544                 break;
10545         case PORT_CLK_SEL_LCPLL_2700:
10546                 id = DPLL_ID_LCPLL_2700;
10547                 break;
10548         default:
10549                 MISSING_CASE(ddi_pll_sel);
10550                 /* fall through */
10551         case PORT_CLK_SEL_NONE:
10552                 return;
10553         }
10554
10555         pipe_config->shared_dpll = intel_get_shared_dpll_by_id(dev_priv, id);
10556 }
10557
10558 static bool hsw_get_transcoder_state(struct intel_crtc *crtc,
10559                                      struct intel_crtc_state *pipe_config,
10560                                      unsigned long *power_domain_mask)
10561 {
10562         struct drm_device *dev = crtc->base.dev;
10563         struct drm_i915_private *dev_priv = to_i915(dev);
10564         enum intel_display_power_domain power_domain;
10565         u32 tmp;
10566
10567         /*
10568          * The pipe->transcoder mapping is fixed with the exception of the eDP
10569          * transcoder handled below.
10570          */
10571         pipe_config->cpu_transcoder = (enum transcoder) crtc->pipe;
10572
10573         /*
10574          * XXX: Do intel_display_power_get_if_enabled before reading this (for
10575          * consistency and less surprising code; it's in always on power).
10576          */
10577         tmp = I915_READ(TRANS_DDI_FUNC_CTL(TRANSCODER_EDP));
10578         if (tmp & TRANS_DDI_FUNC_ENABLE) {
10579                 enum pipe trans_edp_pipe;
10580                 switch (tmp & TRANS_DDI_EDP_INPUT_MASK) {
10581                 default:
10582                         WARN(1, "unknown pipe linked to edp transcoder\n");
10583                 case TRANS_DDI_EDP_INPUT_A_ONOFF:
10584                 case TRANS_DDI_EDP_INPUT_A_ON:
10585                         trans_edp_pipe = PIPE_A;
10586                         break;
10587                 case TRANS_DDI_EDP_INPUT_B_ONOFF:
10588                         trans_edp_pipe = PIPE_B;
10589                         break;
10590                 case TRANS_DDI_EDP_INPUT_C_ONOFF:
10591                         trans_edp_pipe = PIPE_C;
10592                         break;
10593                 }
10594
10595                 if (trans_edp_pipe == crtc->pipe)
10596                         pipe_config->cpu_transcoder = TRANSCODER_EDP;
10597         }
10598
10599         power_domain = POWER_DOMAIN_TRANSCODER(pipe_config->cpu_transcoder);
10600         if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
10601                 return false;
10602         *power_domain_mask |= BIT(power_domain);
10603
10604         tmp = I915_READ(PIPECONF(pipe_config->cpu_transcoder));
10605
10606         return tmp & PIPECONF_ENABLE;
10607 }
10608
10609 static bool bxt_get_dsi_transcoder_state(struct intel_crtc *crtc,
10610                                          struct intel_crtc_state *pipe_config,
10611                                          unsigned long *power_domain_mask)
10612 {
10613         struct drm_device *dev = crtc->base.dev;
10614         struct drm_i915_private *dev_priv = to_i915(dev);
10615         enum intel_display_power_domain power_domain;
10616         enum port port;
10617         enum transcoder cpu_transcoder;
10618         u32 tmp;
10619
10620         for_each_port_masked(port, BIT(PORT_A) | BIT(PORT_C)) {
10621                 if (port == PORT_A)
10622                         cpu_transcoder = TRANSCODER_DSI_A;
10623                 else
10624                         cpu_transcoder = TRANSCODER_DSI_C;
10625
10626                 power_domain = POWER_DOMAIN_TRANSCODER(cpu_transcoder);
10627                 if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
10628                         continue;
10629                 *power_domain_mask |= BIT(power_domain);
10630
10631                 /*
10632                  * The PLL needs to be enabled with a valid divider
10633                  * configuration, otherwise accessing DSI registers will hang
10634                  * the machine. See BSpec North Display Engine
10635                  * registers/MIPI[BXT]. We can break out here early, since we
10636                  * need the same DSI PLL to be enabled for both DSI ports.
10637                  */
10638                 if (!intel_dsi_pll_is_enabled(dev_priv))
10639                         break;
10640
10641                 /* XXX: this works for video mode only */
10642                 tmp = I915_READ(BXT_MIPI_PORT_CTRL(port));
10643                 if (!(tmp & DPI_ENABLE))
10644                         continue;
10645
10646                 tmp = I915_READ(MIPI_CTRL(port));
10647                 if ((tmp & BXT_PIPE_SELECT_MASK) != BXT_PIPE_SELECT(crtc->pipe))
10648                         continue;
10649
10650                 pipe_config->cpu_transcoder = cpu_transcoder;
10651                 break;
10652         }
10653
10654         return transcoder_is_dsi(pipe_config->cpu_transcoder);
10655 }
10656
10657 static void haswell_get_ddi_port_state(struct intel_crtc *crtc,
10658                                        struct intel_crtc_state *pipe_config)
10659 {
10660         struct drm_device *dev = crtc->base.dev;
10661         struct drm_i915_private *dev_priv = to_i915(dev);
10662         struct intel_shared_dpll *pll;
10663         enum port port;
10664         uint32_t tmp;
10665
10666         tmp = I915_READ(TRANS_DDI_FUNC_CTL(pipe_config->cpu_transcoder));
10667
10668         port = (tmp & TRANS_DDI_PORT_MASK) >> TRANS_DDI_PORT_SHIFT;
10669
10670         if (IS_SKYLAKE(dev_priv) || IS_KABYLAKE(dev_priv))
10671                 skylake_get_ddi_pll(dev_priv, port, pipe_config);
10672         else if (IS_BROXTON(dev_priv))
10673                 bxt_get_ddi_pll(dev_priv, port, pipe_config);
10674         else
10675                 haswell_get_ddi_pll(dev_priv, port, pipe_config);
10676
10677         pll = pipe_config->shared_dpll;
10678         if (pll) {
10679                 WARN_ON(!pll->funcs.get_hw_state(dev_priv, pll,
10680                                                  &pipe_config->dpll_hw_state));
10681         }
10682
10683         /*
10684          * Haswell has only FDI/PCH transcoder A. It is which is connected to
10685          * DDI E. So just check whether this pipe is wired to DDI E and whether
10686          * the PCH transcoder is on.
10687          */
10688         if (INTEL_INFO(dev)->gen < 9 &&
10689             (port == PORT_E) && I915_READ(LPT_TRANSCONF) & TRANS_ENABLE) {
10690                 pipe_config->has_pch_encoder = true;
10691
10692                 tmp = I915_READ(FDI_RX_CTL(PIPE_A));
10693                 pipe_config->fdi_lanes = ((FDI_DP_PORT_WIDTH_MASK & tmp) >>
10694                                           FDI_DP_PORT_WIDTH_SHIFT) + 1;
10695
10696                 ironlake_get_fdi_m_n_config(crtc, pipe_config);
10697         }
10698 }
10699
10700 static bool haswell_get_pipe_config(struct intel_crtc *crtc,
10701                                     struct intel_crtc_state *pipe_config)
10702 {
10703         struct drm_device *dev = crtc->base.dev;
10704         struct drm_i915_private *dev_priv = to_i915(dev);
10705         enum intel_display_power_domain power_domain;
10706         unsigned long power_domain_mask;
10707         bool active;
10708
10709         power_domain = POWER_DOMAIN_PIPE(crtc->pipe);
10710         if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
10711                 return false;
10712         power_domain_mask = BIT(power_domain);
10713
10714         pipe_config->shared_dpll = NULL;
10715
10716         active = hsw_get_transcoder_state(crtc, pipe_config, &power_domain_mask);
10717
10718         if (IS_BROXTON(dev_priv) &&
10719             bxt_get_dsi_transcoder_state(crtc, pipe_config, &power_domain_mask)) {
10720                 WARN_ON(active);
10721                 active = true;
10722         }
10723
10724         if (!active)
10725                 goto out;
10726
10727         if (!transcoder_is_dsi(pipe_config->cpu_transcoder)) {
10728                 haswell_get_ddi_port_state(crtc, pipe_config);
10729                 intel_get_pipe_timings(crtc, pipe_config);
10730         }
10731
10732         intel_get_pipe_src_size(crtc, pipe_config);
10733
10734         pipe_config->gamma_mode =
10735                 I915_READ(GAMMA_MODE(crtc->pipe)) & GAMMA_MODE_MODE_MASK;
10736
10737         if (INTEL_INFO(dev)->gen >= 9) {
10738                 skl_init_scalers(dev, crtc, pipe_config);
10739         }
10740
10741         if (INTEL_INFO(dev)->gen >= 9) {
10742                 pipe_config->scaler_state.scaler_id = -1;
10743                 pipe_config->scaler_state.scaler_users &= ~(1 << SKL_CRTC_INDEX);
10744         }
10745
10746         power_domain = POWER_DOMAIN_PIPE_PANEL_FITTER(crtc->pipe);
10747         if (intel_display_power_get_if_enabled(dev_priv, power_domain)) {
10748                 power_domain_mask |= BIT(power_domain);
10749                 if (INTEL_INFO(dev)->gen >= 9)
10750                         skylake_get_pfit_config(crtc, pipe_config);
10751                 else
10752                         ironlake_get_pfit_config(crtc, pipe_config);
10753         }
10754
10755         if (IS_HASWELL(dev_priv))
10756                 pipe_config->ips_enabled = hsw_crtc_supports_ips(crtc) &&
10757                         (I915_READ(IPS_CTL) & IPS_ENABLE);
10758
10759         if (pipe_config->cpu_transcoder != TRANSCODER_EDP &&
10760             !transcoder_is_dsi(pipe_config->cpu_transcoder)) {
10761                 pipe_config->pixel_multiplier =
10762                         I915_READ(PIPE_MULT(pipe_config->cpu_transcoder)) + 1;
10763         } else {
10764                 pipe_config->pixel_multiplier = 1;
10765         }
10766
10767 out:
10768         for_each_power_domain(power_domain, power_domain_mask)
10769                 intel_display_power_put(dev_priv, power_domain);
10770
10771         return active;
10772 }
10773
10774 static void i845_update_cursor(struct drm_crtc *crtc, u32 base,
10775                                const struct intel_plane_state *plane_state)
10776 {
10777         struct drm_device *dev = crtc->dev;
10778         struct drm_i915_private *dev_priv = to_i915(dev);
10779         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10780         uint32_t cntl = 0, size = 0;
10781
10782         if (plane_state && plane_state->base.visible) {
10783                 unsigned int width = plane_state->base.crtc_w;
10784                 unsigned int height = plane_state->base.crtc_h;
10785                 unsigned int stride = roundup_pow_of_two(width) * 4;
10786
10787                 switch (stride) {
10788                 default:
10789                         WARN_ONCE(1, "Invalid cursor width/stride, width=%u, stride=%u\n",
10790                                   width, stride);
10791                         stride = 256;
10792                         /* fallthrough */
10793                 case 256:
10794                 case 512:
10795                 case 1024:
10796                 case 2048:
10797                         break;
10798                 }
10799
10800                 cntl |= CURSOR_ENABLE |
10801                         CURSOR_GAMMA_ENABLE |
10802                         CURSOR_FORMAT_ARGB |
10803                         CURSOR_STRIDE(stride);
10804
10805                 size = (height << 12) | width;
10806         }
10807
10808         if (intel_crtc->cursor_cntl != 0 &&
10809             (intel_crtc->cursor_base != base ||
10810              intel_crtc->cursor_size != size ||
10811              intel_crtc->cursor_cntl != cntl)) {
10812                 /* On these chipsets we can only modify the base/size/stride
10813                  * whilst the cursor is disabled.
10814                  */
10815                 I915_WRITE(CURCNTR(PIPE_A), 0);
10816                 POSTING_READ(CURCNTR(PIPE_A));
10817                 intel_crtc->cursor_cntl = 0;
10818         }
10819
10820         if (intel_crtc->cursor_base != base) {
10821                 I915_WRITE(CURBASE(PIPE_A), base);
10822                 intel_crtc->cursor_base = base;
10823         }
10824
10825         if (intel_crtc->cursor_size != size) {
10826                 I915_WRITE(CURSIZE, size);
10827                 intel_crtc->cursor_size = size;
10828         }
10829
10830         if (intel_crtc->cursor_cntl != cntl) {
10831                 I915_WRITE(CURCNTR(PIPE_A), cntl);
10832                 POSTING_READ(CURCNTR(PIPE_A));
10833                 intel_crtc->cursor_cntl = cntl;
10834         }
10835 }
10836
10837 static void i9xx_update_cursor(struct drm_crtc *crtc, u32 base,
10838                                const struct intel_plane_state *plane_state)
10839 {
10840         struct drm_device *dev = crtc->dev;
10841         struct drm_i915_private *dev_priv = to_i915(dev);
10842         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10843         struct intel_crtc_state *cstate = to_intel_crtc_state(crtc->state);
10844         const struct skl_wm_values *wm = &dev_priv->wm.skl_results;
10845         const struct skl_plane_wm *p_wm =
10846                 &cstate->wm.skl.optimal.planes[PLANE_CURSOR];
10847         int pipe = intel_crtc->pipe;
10848         uint32_t cntl = 0;
10849
10850         if (INTEL_GEN(dev_priv) >= 9 && wm->dirty_pipes & drm_crtc_mask(crtc))
10851                 skl_write_cursor_wm(intel_crtc, p_wm, &wm->ddb);
10852
10853         if (plane_state && plane_state->base.visible) {
10854                 cntl = MCURSOR_GAMMA_ENABLE;
10855                 switch (plane_state->base.crtc_w) {
10856                         case 64:
10857                                 cntl |= CURSOR_MODE_64_ARGB_AX;
10858                                 break;
10859                         case 128:
10860                                 cntl |= CURSOR_MODE_128_ARGB_AX;
10861                                 break;
10862                         case 256:
10863                                 cntl |= CURSOR_MODE_256_ARGB_AX;
10864                                 break;
10865                         default:
10866                                 MISSING_CASE(plane_state->base.crtc_w);
10867                                 return;
10868                 }
10869                 cntl |= pipe << 28; /* Connect to correct pipe */
10870
10871                 if (HAS_DDI(dev_priv))
10872                         cntl |= CURSOR_PIPE_CSC_ENABLE;
10873
10874                 if (plane_state->base.rotation == DRM_ROTATE_180)
10875                         cntl |= CURSOR_ROTATE_180;
10876         }
10877
10878         if (intel_crtc->cursor_cntl != cntl) {
10879                 I915_WRITE(CURCNTR(pipe), cntl);
10880                 POSTING_READ(CURCNTR(pipe));
10881                 intel_crtc->cursor_cntl = cntl;
10882         }
10883
10884         /* and commit changes on next vblank */
10885         I915_WRITE(CURBASE(pipe), base);
10886         POSTING_READ(CURBASE(pipe));
10887
10888         intel_crtc->cursor_base = base;
10889 }
10890
10891 /* If no-part of the cursor is visible on the framebuffer, then the GPU may hang... */
10892 static void intel_crtc_update_cursor(struct drm_crtc *crtc,
10893                                      const struct intel_plane_state *plane_state)
10894 {
10895         struct drm_device *dev = crtc->dev;
10896         struct drm_i915_private *dev_priv = to_i915(dev);
10897         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10898         int pipe = intel_crtc->pipe;
10899         u32 base = intel_crtc->cursor_addr;
10900         u32 pos = 0;
10901
10902         if (plane_state) {
10903                 int x = plane_state->base.crtc_x;
10904                 int y = plane_state->base.crtc_y;
10905
10906                 if (x < 0) {
10907                         pos |= CURSOR_POS_SIGN << CURSOR_X_SHIFT;
10908                         x = -x;
10909                 }
10910                 pos |= x << CURSOR_X_SHIFT;
10911
10912                 if (y < 0) {
10913                         pos |= CURSOR_POS_SIGN << CURSOR_Y_SHIFT;
10914                         y = -y;
10915                 }
10916                 pos |= y << CURSOR_Y_SHIFT;
10917
10918                 /* ILK+ do this automagically */
10919                 if (HAS_GMCH_DISPLAY(dev_priv) &&
10920                     plane_state->base.rotation == DRM_ROTATE_180) {
10921                         base += (plane_state->base.crtc_h *
10922                                  plane_state->base.crtc_w - 1) * 4;
10923                 }
10924         }
10925
10926         I915_WRITE(CURPOS(pipe), pos);
10927
10928         if (IS_845G(dev_priv) || IS_I865G(dev_priv))
10929                 i845_update_cursor(crtc, base, plane_state);
10930         else
10931                 i9xx_update_cursor(crtc, base, plane_state);
10932 }
10933
10934 static bool cursor_size_ok(struct drm_i915_private *dev_priv,
10935                            uint32_t width, uint32_t height)
10936 {
10937         if (width == 0 || height == 0)
10938                 return false;
10939
10940         /*
10941          * 845g/865g are special in that they are only limited by
10942          * the width of their cursors, the height is arbitrary up to
10943          * the precision of the register. Everything else requires
10944          * square cursors, limited to a few power-of-two sizes.
10945          */
10946         if (IS_845G(dev_priv) || IS_I865G(dev_priv)) {
10947                 if ((width & 63) != 0)
10948                         return false;
10949
10950                 if (width > (IS_845G(dev_priv) ? 64 : 512))
10951                         return false;
10952
10953                 if (height > 1023)
10954                         return false;
10955         } else {
10956                 switch (width | height) {
10957                 case 256:
10958                 case 128:
10959                         if (IS_GEN2(dev_priv))
10960                                 return false;
10961                 case 64:
10962                         break;
10963                 default:
10964                         return false;
10965                 }
10966         }
10967
10968         return true;
10969 }
10970
10971 /* VESA 640x480x72Hz mode to set on the pipe */
10972 static struct drm_display_mode load_detect_mode = {
10973         DRM_MODE("640x480", DRM_MODE_TYPE_DEFAULT, 31500, 640, 664,
10974                  704, 832, 0, 480, 489, 491, 520, 0, DRM_MODE_FLAG_NHSYNC | DRM_MODE_FLAG_NVSYNC),
10975 };
10976
10977 struct drm_framebuffer *
10978 __intel_framebuffer_create(struct drm_device *dev,
10979                            struct drm_mode_fb_cmd2 *mode_cmd,
10980                            struct drm_i915_gem_object *obj)
10981 {
10982         struct intel_framebuffer *intel_fb;
10983         int ret;
10984
10985         intel_fb = kzalloc(sizeof(*intel_fb), GFP_KERNEL);
10986         if (!intel_fb)
10987                 return ERR_PTR(-ENOMEM);
10988
10989         ret = intel_framebuffer_init(dev, intel_fb, mode_cmd, obj);
10990         if (ret)
10991                 goto err;
10992
10993         return &intel_fb->base;
10994
10995 err:
10996         kfree(intel_fb);
10997         return ERR_PTR(ret);
10998 }
10999
11000 static struct drm_framebuffer *
11001 intel_framebuffer_create(struct drm_device *dev,
11002                          struct drm_mode_fb_cmd2 *mode_cmd,
11003                          struct drm_i915_gem_object *obj)
11004 {
11005         struct drm_framebuffer *fb;
11006         int ret;
11007
11008         ret = i915_mutex_lock_interruptible(dev);
11009         if (ret)
11010                 return ERR_PTR(ret);
11011         fb = __intel_framebuffer_create(dev, mode_cmd, obj);
11012         mutex_unlock(&dev->struct_mutex);
11013
11014         return fb;
11015 }
11016
11017 static u32
11018 intel_framebuffer_pitch_for_width(int width, int bpp)
11019 {
11020         u32 pitch = DIV_ROUND_UP(width * bpp, 8);
11021         return ALIGN(pitch, 64);
11022 }
11023
11024 static u32
11025 intel_framebuffer_size_for_mode(struct drm_display_mode *mode, int bpp)
11026 {
11027         u32 pitch = intel_framebuffer_pitch_for_width(mode->hdisplay, bpp);
11028         return PAGE_ALIGN(pitch * mode->vdisplay);
11029 }
11030
11031 static struct drm_framebuffer *
11032 intel_framebuffer_create_for_mode(struct drm_device *dev,
11033                                   struct drm_display_mode *mode,
11034                                   int depth, int bpp)
11035 {
11036         struct drm_framebuffer *fb;
11037         struct drm_i915_gem_object *obj;
11038         struct drm_mode_fb_cmd2 mode_cmd = { 0 };
11039
11040         obj = i915_gem_object_create(dev,
11041                                     intel_framebuffer_size_for_mode(mode, bpp));
11042         if (IS_ERR(obj))
11043                 return ERR_CAST(obj);
11044
11045         mode_cmd.width = mode->hdisplay;
11046         mode_cmd.height = mode->vdisplay;
11047         mode_cmd.pitches[0] = intel_framebuffer_pitch_for_width(mode_cmd.width,
11048                                                                 bpp);
11049         mode_cmd.pixel_format = drm_mode_legacy_fb_format(bpp, depth);
11050
11051         fb = intel_framebuffer_create(dev, &mode_cmd, obj);
11052         if (IS_ERR(fb))
11053                 i915_gem_object_put_unlocked(obj);
11054
11055         return fb;
11056 }
11057
11058 static struct drm_framebuffer *
11059 mode_fits_in_fbdev(struct drm_device *dev,
11060                    struct drm_display_mode *mode)
11061 {
11062 #ifdef CONFIG_DRM_FBDEV_EMULATION
11063         struct drm_i915_private *dev_priv = to_i915(dev);
11064         struct drm_i915_gem_object *obj;
11065         struct drm_framebuffer *fb;
11066
11067         if (!dev_priv->fbdev)
11068                 return NULL;
11069
11070         if (!dev_priv->fbdev->fb)
11071                 return NULL;
11072
11073         obj = dev_priv->fbdev->fb->obj;
11074         BUG_ON(!obj);
11075
11076         fb = &dev_priv->fbdev->fb->base;
11077         if (fb->pitches[0] < intel_framebuffer_pitch_for_width(mode->hdisplay,
11078                                                                fb->bits_per_pixel))
11079                 return NULL;
11080
11081         if (obj->base.size < mode->vdisplay * fb->pitches[0])
11082                 return NULL;
11083
11084         drm_framebuffer_reference(fb);
11085         return fb;
11086 #else
11087         return NULL;
11088 #endif
11089 }
11090
11091 static int intel_modeset_setup_plane_state(struct drm_atomic_state *state,
11092                                            struct drm_crtc *crtc,
11093                                            struct drm_display_mode *mode,
11094                                            struct drm_framebuffer *fb,
11095                                            int x, int y)
11096 {
11097         struct drm_plane_state *plane_state;
11098         int hdisplay, vdisplay;
11099         int ret;
11100
11101         plane_state = drm_atomic_get_plane_state(state, crtc->primary);
11102         if (IS_ERR(plane_state))
11103                 return PTR_ERR(plane_state);
11104
11105         if (mode)
11106                 drm_crtc_get_hv_timing(mode, &hdisplay, &vdisplay);
11107         else
11108                 hdisplay = vdisplay = 0;
11109
11110         ret = drm_atomic_set_crtc_for_plane(plane_state, fb ? crtc : NULL);
11111         if (ret)
11112                 return ret;
11113         drm_atomic_set_fb_for_plane(plane_state, fb);
11114         plane_state->crtc_x = 0;
11115         plane_state->crtc_y = 0;
11116         plane_state->crtc_w = hdisplay;
11117         plane_state->crtc_h = vdisplay;
11118         plane_state->src_x = x << 16;
11119         plane_state->src_y = y << 16;
11120         plane_state->src_w = hdisplay << 16;
11121         plane_state->src_h = vdisplay << 16;
11122
11123         return 0;
11124 }
11125
11126 bool intel_get_load_detect_pipe(struct drm_connector *connector,
11127                                 struct drm_display_mode *mode,
11128                                 struct intel_load_detect_pipe *old,
11129                                 struct drm_modeset_acquire_ctx *ctx)
11130 {
11131         struct intel_crtc *intel_crtc;
11132         struct intel_encoder *intel_encoder =
11133                 intel_attached_encoder(connector);
11134         struct drm_crtc *possible_crtc;
11135         struct drm_encoder *encoder = &intel_encoder->base;
11136         struct drm_crtc *crtc = NULL;
11137         struct drm_device *dev = encoder->dev;
11138         struct drm_framebuffer *fb;
11139         struct drm_mode_config *config = &dev->mode_config;
11140         struct drm_atomic_state *state = NULL, *restore_state = NULL;
11141         struct drm_connector_state *connector_state;
11142         struct intel_crtc_state *crtc_state;
11143         int ret, i = -1;
11144
11145         DRM_DEBUG_KMS("[CONNECTOR:%d:%s], [ENCODER:%d:%s]\n",
11146                       connector->base.id, connector->name,
11147                       encoder->base.id, encoder->name);
11148
11149         old->restore_state = NULL;
11150
11151 retry:
11152         ret = drm_modeset_lock(&config->connection_mutex, ctx);
11153         if (ret)
11154                 goto fail;
11155
11156         /*
11157          * Algorithm gets a little messy:
11158          *
11159          *   - if the connector already has an assigned crtc, use it (but make
11160          *     sure it's on first)
11161          *
11162          *   - try to find the first unused crtc that can drive this connector,
11163          *     and use that if we find one
11164          */
11165
11166         /* See if we already have a CRTC for this connector */
11167         if (connector->state->crtc) {
11168                 crtc = connector->state->crtc;
11169
11170                 ret = drm_modeset_lock(&crtc->mutex, ctx);
11171                 if (ret)
11172                         goto fail;
11173
11174                 /* Make sure the crtc and connector are running */
11175                 goto found;
11176         }
11177
11178         /* Find an unused one (if possible) */
11179         for_each_crtc(dev, possible_crtc) {
11180                 i++;
11181                 if (!(encoder->possible_crtcs & (1 << i)))
11182                         continue;
11183
11184                 ret = drm_modeset_lock(&possible_crtc->mutex, ctx);
11185                 if (ret)
11186                         goto fail;
11187
11188                 if (possible_crtc->state->enable) {
11189                         drm_modeset_unlock(&possible_crtc->mutex);
11190                         continue;
11191                 }
11192
11193                 crtc = possible_crtc;
11194                 break;
11195         }
11196
11197         /*
11198          * If we didn't find an unused CRTC, don't use any.
11199          */
11200         if (!crtc) {
11201                 DRM_DEBUG_KMS("no pipe available for load-detect\n");
11202                 goto fail;
11203         }
11204
11205 found:
11206         intel_crtc = to_intel_crtc(crtc);
11207
11208         ret = drm_modeset_lock(&crtc->primary->mutex, ctx);
11209         if (ret)
11210                 goto fail;
11211
11212         state = drm_atomic_state_alloc(dev);
11213         restore_state = drm_atomic_state_alloc(dev);
11214         if (!state || !restore_state) {
11215                 ret = -ENOMEM;
11216                 goto fail;
11217         }
11218
11219         state->acquire_ctx = ctx;
11220         restore_state->acquire_ctx = ctx;
11221
11222         connector_state = drm_atomic_get_connector_state(state, connector);
11223         if (IS_ERR(connector_state)) {
11224                 ret = PTR_ERR(connector_state);
11225                 goto fail;
11226         }
11227
11228         ret = drm_atomic_set_crtc_for_connector(connector_state, crtc);
11229         if (ret)
11230                 goto fail;
11231
11232         crtc_state = intel_atomic_get_crtc_state(state, intel_crtc);
11233         if (IS_ERR(crtc_state)) {
11234                 ret = PTR_ERR(crtc_state);
11235                 goto fail;
11236         }
11237
11238         crtc_state->base.active = crtc_state->base.enable = true;
11239
11240         if (!mode)
11241                 mode = &load_detect_mode;
11242
11243         /* We need a framebuffer large enough to accommodate all accesses
11244          * that the plane may generate whilst we perform load detection.
11245          * We can not rely on the fbcon either being present (we get called
11246          * during its initialisation to detect all boot displays, or it may
11247          * not even exist) or that it is large enough to satisfy the
11248          * requested mode.
11249          */
11250         fb = mode_fits_in_fbdev(dev, mode);
11251         if (fb == NULL) {
11252                 DRM_DEBUG_KMS("creating tmp fb for load-detection\n");
11253                 fb = intel_framebuffer_create_for_mode(dev, mode, 24, 32);
11254         } else
11255                 DRM_DEBUG_KMS("reusing fbdev for load-detection framebuffer\n");
11256         if (IS_ERR(fb)) {
11257                 DRM_DEBUG_KMS("failed to allocate framebuffer for load-detection\n");
11258                 goto fail;
11259         }
11260
11261         ret = intel_modeset_setup_plane_state(state, crtc, mode, fb, 0, 0);
11262         if (ret)
11263                 goto fail;
11264
11265         drm_framebuffer_unreference(fb);
11266
11267         ret = drm_atomic_set_mode_for_crtc(&crtc_state->base, mode);
11268         if (ret)
11269                 goto fail;
11270
11271         ret = PTR_ERR_OR_ZERO(drm_atomic_get_connector_state(restore_state, connector));
11272         if (!ret)
11273                 ret = PTR_ERR_OR_ZERO(drm_atomic_get_crtc_state(restore_state, crtc));
11274         if (!ret)
11275                 ret = PTR_ERR_OR_ZERO(drm_atomic_get_plane_state(restore_state, crtc->primary));
11276         if (ret) {
11277                 DRM_DEBUG_KMS("Failed to create a copy of old state to restore: %i\n", ret);
11278                 goto fail;
11279         }
11280
11281         ret = drm_atomic_commit(state);
11282         if (ret) {
11283                 DRM_DEBUG_KMS("failed to set mode on load-detect pipe\n");
11284                 goto fail;
11285         }
11286
11287         old->restore_state = restore_state;
11288
11289         /* let the connector get through one full cycle before testing */
11290         intel_wait_for_vblank(dev, intel_crtc->pipe);
11291         return true;
11292
11293 fail:
11294         if (state) {
11295                 drm_atomic_state_put(state);
11296                 state = NULL;
11297         }
11298         if (restore_state) {
11299                 drm_atomic_state_put(restore_state);
11300                 restore_state = NULL;
11301         }
11302
11303         if (ret == -EDEADLK) {
11304                 drm_modeset_backoff(ctx);
11305                 goto retry;
11306         }
11307
11308         return false;
11309 }
11310
11311 void intel_release_load_detect_pipe(struct drm_connector *connector,
11312                                     struct intel_load_detect_pipe *old,
11313                                     struct drm_modeset_acquire_ctx *ctx)
11314 {
11315         struct intel_encoder *intel_encoder =
11316                 intel_attached_encoder(connector);
11317         struct drm_encoder *encoder = &intel_encoder->base;
11318         struct drm_atomic_state *state = old->restore_state;
11319         int ret;
11320
11321         DRM_DEBUG_KMS("[CONNECTOR:%d:%s], [ENCODER:%d:%s]\n",
11322                       connector->base.id, connector->name,
11323                       encoder->base.id, encoder->name);
11324
11325         if (!state)
11326                 return;
11327
11328         ret = drm_atomic_commit(state);
11329         if (ret)
11330                 DRM_DEBUG_KMS("Couldn't release load detect pipe: %i\n", ret);
11331         drm_atomic_state_put(state);
11332 }
11333
11334 static int i9xx_pll_refclk(struct drm_device *dev,
11335                            const struct intel_crtc_state *pipe_config)
11336 {
11337         struct drm_i915_private *dev_priv = to_i915(dev);
11338         u32 dpll = pipe_config->dpll_hw_state.dpll;
11339
11340         if ((dpll & PLL_REF_INPUT_MASK) == PLLB_REF_INPUT_SPREADSPECTRUMIN)
11341                 return dev_priv->vbt.lvds_ssc_freq;
11342         else if (HAS_PCH_SPLIT(dev_priv))
11343                 return 120000;
11344         else if (!IS_GEN2(dev_priv))
11345                 return 96000;
11346         else
11347                 return 48000;
11348 }
11349
11350 /* Returns the clock of the currently programmed mode of the given pipe. */
11351 static void i9xx_crtc_clock_get(struct intel_crtc *crtc,
11352                                 struct intel_crtc_state *pipe_config)
11353 {
11354         struct drm_device *dev = crtc->base.dev;
11355         struct drm_i915_private *dev_priv = to_i915(dev);
11356         int pipe = pipe_config->cpu_transcoder;
11357         u32 dpll = pipe_config->dpll_hw_state.dpll;
11358         u32 fp;
11359         struct dpll clock;
11360         int port_clock;
11361         int refclk = i9xx_pll_refclk(dev, pipe_config);
11362
11363         if ((dpll & DISPLAY_RATE_SELECT_FPA1) == 0)
11364                 fp = pipe_config->dpll_hw_state.fp0;
11365         else
11366                 fp = pipe_config->dpll_hw_state.fp1;
11367
11368         clock.m1 = (fp & FP_M1_DIV_MASK) >> FP_M1_DIV_SHIFT;
11369         if (IS_PINEVIEW(dev)) {
11370                 clock.n = ffs((fp & FP_N_PINEVIEW_DIV_MASK) >> FP_N_DIV_SHIFT) - 1;
11371                 clock.m2 = (fp & FP_M2_PINEVIEW_DIV_MASK) >> FP_M2_DIV_SHIFT;
11372         } else {
11373                 clock.n = (fp & FP_N_DIV_MASK) >> FP_N_DIV_SHIFT;
11374                 clock.m2 = (fp & FP_M2_DIV_MASK) >> FP_M2_DIV_SHIFT;
11375         }
11376
11377         if (!IS_GEN2(dev_priv)) {
11378                 if (IS_PINEVIEW(dev))
11379                         clock.p1 = ffs((dpll & DPLL_FPA01_P1_POST_DIV_MASK_PINEVIEW) >>
11380                                 DPLL_FPA01_P1_POST_DIV_SHIFT_PINEVIEW);
11381                 else
11382                         clock.p1 = ffs((dpll & DPLL_FPA01_P1_POST_DIV_MASK) >>
11383                                DPLL_FPA01_P1_POST_DIV_SHIFT);
11384
11385                 switch (dpll & DPLL_MODE_MASK) {
11386                 case DPLLB_MODE_DAC_SERIAL:
11387                         clock.p2 = dpll & DPLL_DAC_SERIAL_P2_CLOCK_DIV_5 ?
11388                                 5 : 10;
11389                         break;
11390                 case DPLLB_MODE_LVDS:
11391                         clock.p2 = dpll & DPLLB_LVDS_P2_CLOCK_DIV_7 ?
11392                                 7 : 14;
11393                         break;
11394                 default:
11395                         DRM_DEBUG_KMS("Unknown DPLL mode %08x in programmed "
11396                                   "mode\n", (int)(dpll & DPLL_MODE_MASK));
11397                         return;
11398                 }
11399
11400                 if (IS_PINEVIEW(dev))
11401                         port_clock = pnv_calc_dpll_params(refclk, &clock);
11402                 else
11403                         port_clock = i9xx_calc_dpll_params(refclk, &clock);
11404         } else {
11405                 u32 lvds = IS_I830(dev_priv) ? 0 : I915_READ(LVDS);
11406                 bool is_lvds = (pipe == 1) && (lvds & LVDS_PORT_EN);
11407
11408                 if (is_lvds) {
11409                         clock.p1 = ffs((dpll & DPLL_FPA01_P1_POST_DIV_MASK_I830_LVDS) >>
11410                                        DPLL_FPA01_P1_POST_DIV_SHIFT);
11411
11412                         if (lvds & LVDS_CLKB_POWER_UP)
11413                                 clock.p2 = 7;
11414                         else
11415                                 clock.p2 = 14;
11416                 } else {
11417                         if (dpll & PLL_P1_DIVIDE_BY_TWO)
11418                                 clock.p1 = 2;
11419                         else {
11420                                 clock.p1 = ((dpll & DPLL_FPA01_P1_POST_DIV_MASK_I830) >>
11421                                             DPLL_FPA01_P1_POST_DIV_SHIFT) + 2;
11422                         }
11423                         if (dpll & PLL_P2_DIVIDE_BY_4)
11424                                 clock.p2 = 4;
11425                         else
11426                                 clock.p2 = 2;
11427                 }
11428
11429                 port_clock = i9xx_calc_dpll_params(refclk, &clock);
11430         }
11431
11432         /*
11433          * This value includes pixel_multiplier. We will use
11434          * port_clock to compute adjusted_mode.crtc_clock in the
11435          * encoder's get_config() function.
11436          */
11437         pipe_config->port_clock = port_clock;
11438 }
11439
11440 int intel_dotclock_calculate(int link_freq,
11441                              const struct intel_link_m_n *m_n)
11442 {
11443         /*
11444          * The calculation for the data clock is:
11445          * pixel_clock = ((m/n)*(link_clock * nr_lanes))/bpp
11446          * But we want to avoid losing precison if possible, so:
11447          * pixel_clock = ((m * link_clock * nr_lanes)/(n*bpp))
11448          *
11449          * and the link clock is simpler:
11450          * link_clock = (m * link_clock) / n
11451          */
11452
11453         if (!m_n->link_n)
11454                 return 0;
11455
11456         return div_u64((u64)m_n->link_m * link_freq, m_n->link_n);
11457 }
11458
11459 static void ironlake_pch_clock_get(struct intel_crtc *crtc,
11460                                    struct intel_crtc_state *pipe_config)
11461 {
11462         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
11463
11464         /* read out port_clock from the DPLL */
11465         i9xx_crtc_clock_get(crtc, pipe_config);
11466
11467         /*
11468          * In case there is an active pipe without active ports,
11469          * we may need some idea for the dotclock anyway.
11470          * Calculate one based on the FDI configuration.
11471          */
11472         pipe_config->base.adjusted_mode.crtc_clock =
11473                 intel_dotclock_calculate(intel_fdi_link_freq(dev_priv, pipe_config),
11474                                          &pipe_config->fdi_m_n);
11475 }
11476
11477 /** Returns the currently programmed mode of the given pipe. */
11478 struct drm_display_mode *intel_crtc_mode_get(struct drm_device *dev,
11479                                              struct drm_crtc *crtc)
11480 {
11481         struct drm_i915_private *dev_priv = to_i915(dev);
11482         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11483         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
11484         struct drm_display_mode *mode;
11485         struct intel_crtc_state *pipe_config;
11486         int htot = I915_READ(HTOTAL(cpu_transcoder));
11487         int hsync = I915_READ(HSYNC(cpu_transcoder));
11488         int vtot = I915_READ(VTOTAL(cpu_transcoder));
11489         int vsync = I915_READ(VSYNC(cpu_transcoder));
11490         enum pipe pipe = intel_crtc->pipe;
11491
11492         mode = kzalloc(sizeof(*mode), GFP_KERNEL);
11493         if (!mode)
11494                 return NULL;
11495
11496         pipe_config = kzalloc(sizeof(*pipe_config), GFP_KERNEL);
11497         if (!pipe_config) {
11498                 kfree(mode);
11499                 return NULL;
11500         }
11501
11502         /*
11503          * Construct a pipe_config sufficient for getting the clock info
11504          * back out of crtc_clock_get.
11505          *
11506          * Note, if LVDS ever uses a non-1 pixel multiplier, we'll need
11507          * to use a real value here instead.
11508          */
11509         pipe_config->cpu_transcoder = (enum transcoder) pipe;
11510         pipe_config->pixel_multiplier = 1;
11511         pipe_config->dpll_hw_state.dpll = I915_READ(DPLL(pipe));
11512         pipe_config->dpll_hw_state.fp0 = I915_READ(FP0(pipe));
11513         pipe_config->dpll_hw_state.fp1 = I915_READ(FP1(pipe));
11514         i9xx_crtc_clock_get(intel_crtc, pipe_config);
11515
11516         mode->clock = pipe_config->port_clock / pipe_config->pixel_multiplier;
11517         mode->hdisplay = (htot & 0xffff) + 1;
11518         mode->htotal = ((htot & 0xffff0000) >> 16) + 1;
11519         mode->hsync_start = (hsync & 0xffff) + 1;
11520         mode->hsync_end = ((hsync & 0xffff0000) >> 16) + 1;
11521         mode->vdisplay = (vtot & 0xffff) + 1;
11522         mode->vtotal = ((vtot & 0xffff0000) >> 16) + 1;
11523         mode->vsync_start = (vsync & 0xffff) + 1;
11524         mode->vsync_end = ((vsync & 0xffff0000) >> 16) + 1;
11525
11526         drm_mode_set_name(mode);
11527
11528         kfree(pipe_config);
11529
11530         return mode;
11531 }
11532
11533 static void intel_crtc_destroy(struct drm_crtc *crtc)
11534 {
11535         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11536         struct drm_device *dev = crtc->dev;
11537         struct intel_flip_work *work;
11538
11539         spin_lock_irq(&dev->event_lock);
11540         work = intel_crtc->flip_work;
11541         intel_crtc->flip_work = NULL;
11542         spin_unlock_irq(&dev->event_lock);
11543
11544         if (work) {
11545                 cancel_work_sync(&work->mmio_work);
11546                 cancel_work_sync(&work->unpin_work);
11547                 kfree(work);
11548         }
11549
11550         drm_crtc_cleanup(crtc);
11551
11552         kfree(intel_crtc);
11553 }
11554
11555 static void intel_unpin_work_fn(struct work_struct *__work)
11556 {
11557         struct intel_flip_work *work =
11558                 container_of(__work, struct intel_flip_work, unpin_work);
11559         struct intel_crtc *crtc = to_intel_crtc(work->crtc);
11560         struct drm_device *dev = crtc->base.dev;
11561         struct drm_plane *primary = crtc->base.primary;
11562
11563         if (is_mmio_work(work))
11564                 flush_work(&work->mmio_work);
11565
11566         mutex_lock(&dev->struct_mutex);
11567         intel_unpin_fb_obj(work->old_fb, primary->state->rotation);
11568         i915_gem_object_put(work->pending_flip_obj);
11569         mutex_unlock(&dev->struct_mutex);
11570
11571         i915_gem_request_put(work->flip_queued_req);
11572
11573         intel_frontbuffer_flip_complete(to_i915(dev),
11574                                         to_intel_plane(primary)->frontbuffer_bit);
11575         intel_fbc_post_update(crtc);
11576         drm_framebuffer_unreference(work->old_fb);
11577
11578         BUG_ON(atomic_read(&crtc->unpin_work_count) == 0);
11579         atomic_dec(&crtc->unpin_work_count);
11580
11581         kfree(work);
11582 }
11583
11584 /* Is 'a' after or equal to 'b'? */
11585 static bool g4x_flip_count_after_eq(u32 a, u32 b)
11586 {
11587         return !((a - b) & 0x80000000);
11588 }
11589
11590 static bool __pageflip_finished_cs(struct intel_crtc *crtc,
11591                                    struct intel_flip_work *work)
11592 {
11593         struct drm_device *dev = crtc->base.dev;
11594         struct drm_i915_private *dev_priv = to_i915(dev);
11595
11596         if (abort_flip_on_reset(crtc))
11597                 return true;
11598
11599         /*
11600          * The relevant registers doen't exist on pre-ctg.
11601          * As the flip done interrupt doesn't trigger for mmio
11602          * flips on gmch platforms, a flip count check isn't
11603          * really needed there. But since ctg has the registers,
11604          * include it in the check anyway.
11605          */
11606         if (INTEL_GEN(dev_priv) < 5 && !IS_G4X(dev_priv))
11607                 return true;
11608
11609         /*
11610          * BDW signals flip done immediately if the plane
11611          * is disabled, even if the plane enable is already
11612          * armed to occur at the next vblank :(
11613          */
11614
11615         /*
11616          * A DSPSURFLIVE check isn't enough in case the mmio and CS flips
11617          * used the same base address. In that case the mmio flip might
11618          * have completed, but the CS hasn't even executed the flip yet.
11619          *
11620          * A flip count check isn't enough as the CS might have updated
11621          * the base address just after start of vblank, but before we
11622          * managed to process the interrupt. This means we'd complete the
11623          * CS flip too soon.
11624          *
11625          * Combining both checks should get us a good enough result. It may
11626          * still happen that the CS flip has been executed, but has not
11627          * yet actually completed. But in case the base address is the same
11628          * anyway, we don't really care.
11629          */
11630         return (I915_READ(DSPSURFLIVE(crtc->plane)) & ~0xfff) ==
11631                 crtc->flip_work->gtt_offset &&
11632                 g4x_flip_count_after_eq(I915_READ(PIPE_FLIPCOUNT_G4X(crtc->pipe)),
11633                                     crtc->flip_work->flip_count);
11634 }
11635
11636 static bool
11637 __pageflip_finished_mmio(struct intel_crtc *crtc,
11638                                struct intel_flip_work *work)
11639 {
11640         /*
11641          * MMIO work completes when vblank is different from
11642          * flip_queued_vblank.
11643          *
11644          * Reset counter value doesn't matter, this is handled by
11645          * i915_wait_request finishing early, so no need to handle
11646          * reset here.
11647          */
11648         return intel_crtc_get_vblank_counter(crtc) != work->flip_queued_vblank;
11649 }
11650
11651
11652 static bool pageflip_finished(struct intel_crtc *crtc,
11653                               struct intel_flip_work *work)
11654 {
11655         if (!atomic_read(&work->pending))
11656                 return false;
11657
11658         smp_rmb();
11659
11660         if (is_mmio_work(work))
11661                 return __pageflip_finished_mmio(crtc, work);
11662         else
11663                 return __pageflip_finished_cs(crtc, work);
11664 }
11665
11666 void intel_finish_page_flip_cs(struct drm_i915_private *dev_priv, int pipe)
11667 {
11668         struct drm_device *dev = &dev_priv->drm;
11669         struct drm_crtc *crtc = dev_priv->pipe_to_crtc_mapping[pipe];
11670         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11671         struct intel_flip_work *work;
11672         unsigned long flags;
11673
11674         /* Ignore early vblank irqs */
11675         if (!crtc)
11676                 return;
11677
11678         /*
11679          * This is called both by irq handlers and the reset code (to complete
11680          * lost pageflips) so needs the full irqsave spinlocks.
11681          */
11682         spin_lock_irqsave(&dev->event_lock, flags);
11683         work = intel_crtc->flip_work;
11684
11685         if (work != NULL &&
11686             !is_mmio_work(work) &&
11687             pageflip_finished(intel_crtc, work))
11688                 page_flip_completed(intel_crtc);
11689
11690         spin_unlock_irqrestore(&dev->event_lock, flags);
11691 }
11692
11693 void intel_finish_page_flip_mmio(struct drm_i915_private *dev_priv, int pipe)
11694 {
11695         struct drm_device *dev = &dev_priv->drm;
11696         struct drm_crtc *crtc = dev_priv->pipe_to_crtc_mapping[pipe];
11697         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11698         struct intel_flip_work *work;
11699         unsigned long flags;
11700
11701         /* Ignore early vblank irqs */
11702         if (!crtc)
11703                 return;
11704
11705         /*
11706          * This is called both by irq handlers and the reset code (to complete
11707          * lost pageflips) so needs the full irqsave spinlocks.
11708          */
11709         spin_lock_irqsave(&dev->event_lock, flags);
11710         work = intel_crtc->flip_work;
11711
11712         if (work != NULL &&
11713             is_mmio_work(work) &&
11714             pageflip_finished(intel_crtc, work))
11715                 page_flip_completed(intel_crtc);
11716
11717         spin_unlock_irqrestore(&dev->event_lock, flags);
11718 }
11719
11720 static inline void intel_mark_page_flip_active(struct intel_crtc *crtc,
11721                                                struct intel_flip_work *work)
11722 {
11723         work->flip_queued_vblank = intel_crtc_get_vblank_counter(crtc);
11724
11725         /* Ensure that the work item is consistent when activating it ... */
11726         smp_mb__before_atomic();
11727         atomic_set(&work->pending, 1);
11728 }
11729
11730 static int intel_gen2_queue_flip(struct drm_device *dev,
11731                                  struct drm_crtc *crtc,
11732                                  struct drm_framebuffer *fb,
11733                                  struct drm_i915_gem_object *obj,
11734                                  struct drm_i915_gem_request *req,
11735                                  uint32_t flags)
11736 {
11737         struct intel_ring *ring = req->ring;
11738         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11739         u32 flip_mask;
11740         int ret;
11741
11742         ret = intel_ring_begin(req, 6);
11743         if (ret)
11744                 return ret;
11745
11746         /* Can't queue multiple flips, so wait for the previous
11747          * one to finish before executing the next.
11748          */
11749         if (intel_crtc->plane)
11750                 flip_mask = MI_WAIT_FOR_PLANE_B_FLIP;
11751         else
11752                 flip_mask = MI_WAIT_FOR_PLANE_A_FLIP;
11753         intel_ring_emit(ring, MI_WAIT_FOR_EVENT | flip_mask);
11754         intel_ring_emit(ring, MI_NOOP);
11755         intel_ring_emit(ring, MI_DISPLAY_FLIP |
11756                         MI_DISPLAY_FLIP_PLANE(intel_crtc->plane));
11757         intel_ring_emit(ring, fb->pitches[0]);
11758         intel_ring_emit(ring, intel_crtc->flip_work->gtt_offset);
11759         intel_ring_emit(ring, 0); /* aux display base address, unused */
11760
11761         return 0;
11762 }
11763
11764 static int intel_gen3_queue_flip(struct drm_device *dev,
11765                                  struct drm_crtc *crtc,
11766                                  struct drm_framebuffer *fb,
11767                                  struct drm_i915_gem_object *obj,
11768                                  struct drm_i915_gem_request *req,
11769                                  uint32_t flags)
11770 {
11771         struct intel_ring *ring = req->ring;
11772         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11773         u32 flip_mask;
11774         int ret;
11775
11776         ret = intel_ring_begin(req, 6);
11777         if (ret)
11778                 return ret;
11779
11780         if (intel_crtc->plane)
11781                 flip_mask = MI_WAIT_FOR_PLANE_B_FLIP;
11782         else
11783                 flip_mask = MI_WAIT_FOR_PLANE_A_FLIP;
11784         intel_ring_emit(ring, MI_WAIT_FOR_EVENT | flip_mask);
11785         intel_ring_emit(ring, MI_NOOP);
11786         intel_ring_emit(ring, MI_DISPLAY_FLIP_I915 |
11787                         MI_DISPLAY_FLIP_PLANE(intel_crtc->plane));
11788         intel_ring_emit(ring, fb->pitches[0]);
11789         intel_ring_emit(ring, intel_crtc->flip_work->gtt_offset);
11790         intel_ring_emit(ring, MI_NOOP);
11791
11792         return 0;
11793 }
11794
11795 static int intel_gen4_queue_flip(struct drm_device *dev,
11796                                  struct drm_crtc *crtc,
11797                                  struct drm_framebuffer *fb,
11798                                  struct drm_i915_gem_object *obj,
11799                                  struct drm_i915_gem_request *req,
11800                                  uint32_t flags)
11801 {
11802         struct intel_ring *ring = req->ring;
11803         struct drm_i915_private *dev_priv = to_i915(dev);
11804         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11805         uint32_t pf, pipesrc;
11806         int ret;
11807
11808         ret = intel_ring_begin(req, 4);
11809         if (ret)
11810                 return ret;
11811
11812         /* i965+ uses the linear or tiled offsets from the
11813          * Display Registers (which do not change across a page-flip)
11814          * so we need only reprogram the base address.
11815          */
11816         intel_ring_emit(ring, MI_DISPLAY_FLIP |
11817                         MI_DISPLAY_FLIP_PLANE(intel_crtc->plane));
11818         intel_ring_emit(ring, fb->pitches[0]);
11819         intel_ring_emit(ring, intel_crtc->flip_work->gtt_offset |
11820                         intel_fb_modifier_to_tiling(fb->modifier[0]));
11821
11822         /* XXX Enabling the panel-fitter across page-flip is so far
11823          * untested on non-native modes, so ignore it for now.
11824          * pf = I915_READ(pipe == 0 ? PFA_CTL_1 : PFB_CTL_1) & PF_ENABLE;
11825          */
11826         pf = 0;
11827         pipesrc = I915_READ(PIPESRC(intel_crtc->pipe)) & 0x0fff0fff;
11828         intel_ring_emit(ring, pf | pipesrc);
11829
11830         return 0;
11831 }
11832
11833 static int intel_gen6_queue_flip(struct drm_device *dev,
11834                                  struct drm_crtc *crtc,
11835                                  struct drm_framebuffer *fb,
11836                                  struct drm_i915_gem_object *obj,
11837                                  struct drm_i915_gem_request *req,
11838                                  uint32_t flags)
11839 {
11840         struct intel_ring *ring = req->ring;
11841         struct drm_i915_private *dev_priv = to_i915(dev);
11842         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11843         uint32_t pf, pipesrc;
11844         int ret;
11845
11846         ret = intel_ring_begin(req, 4);
11847         if (ret)
11848                 return ret;
11849
11850         intel_ring_emit(ring, MI_DISPLAY_FLIP |
11851                         MI_DISPLAY_FLIP_PLANE(intel_crtc->plane));
11852         intel_ring_emit(ring, fb->pitches[0] |
11853                         intel_fb_modifier_to_tiling(fb->modifier[0]));
11854         intel_ring_emit(ring, intel_crtc->flip_work->gtt_offset);
11855
11856         /* Contrary to the suggestions in the documentation,
11857          * "Enable Panel Fitter" does not seem to be required when page
11858          * flipping with a non-native mode, and worse causes a normal
11859          * modeset to fail.
11860          * pf = I915_READ(PF_CTL(intel_crtc->pipe)) & PF_ENABLE;
11861          */
11862         pf = 0;
11863         pipesrc = I915_READ(PIPESRC(intel_crtc->pipe)) & 0x0fff0fff;
11864         intel_ring_emit(ring, pf | pipesrc);
11865
11866         return 0;
11867 }
11868
11869 static int intel_gen7_queue_flip(struct drm_device *dev,
11870                                  struct drm_crtc *crtc,
11871                                  struct drm_framebuffer *fb,
11872                                  struct drm_i915_gem_object *obj,
11873                                  struct drm_i915_gem_request *req,
11874                                  uint32_t flags)
11875 {
11876         struct drm_i915_private *dev_priv = to_i915(dev);
11877         struct intel_ring *ring = req->ring;
11878         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11879         uint32_t plane_bit = 0;
11880         int len, ret;
11881
11882         switch (intel_crtc->plane) {
11883         case PLANE_A:
11884                 plane_bit = MI_DISPLAY_FLIP_IVB_PLANE_A;
11885                 break;
11886         case PLANE_B:
11887                 plane_bit = MI_DISPLAY_FLIP_IVB_PLANE_B;
11888                 break;
11889         case PLANE_C:
11890                 plane_bit = MI_DISPLAY_FLIP_IVB_PLANE_C;
11891                 break;
11892         default:
11893                 WARN_ONCE(1, "unknown plane in flip command\n");
11894                 return -ENODEV;
11895         }
11896
11897         len = 4;
11898         if (req->engine->id == RCS) {
11899                 len += 6;
11900                 /*
11901                  * On Gen 8, SRM is now taking an extra dword to accommodate
11902                  * 48bits addresses, and we need a NOOP for the batch size to
11903                  * stay even.
11904                  */
11905                 if (IS_GEN8(dev_priv))
11906                         len += 2;
11907         }
11908
11909         /*
11910          * BSpec MI_DISPLAY_FLIP for IVB:
11911          * "The full packet must be contained within the same cache line."
11912          *
11913          * Currently the LRI+SRM+MI_DISPLAY_FLIP all fit within the same
11914          * cacheline, if we ever start emitting more commands before
11915          * the MI_DISPLAY_FLIP we may need to first emit everything else,
11916          * then do the cacheline alignment, and finally emit the
11917          * MI_DISPLAY_FLIP.
11918          */
11919         ret = intel_ring_cacheline_align(req);
11920         if (ret)
11921                 return ret;
11922
11923         ret = intel_ring_begin(req, len);
11924         if (ret)
11925                 return ret;
11926
11927         /* Unmask the flip-done completion message. Note that the bspec says that
11928          * we should do this for both the BCS and RCS, and that we must not unmask
11929          * more than one flip event at any time (or ensure that one flip message
11930          * can be sent by waiting for flip-done prior to queueing new flips).
11931          * Experimentation says that BCS works despite DERRMR masking all
11932          * flip-done completion events and that unmasking all planes at once
11933          * for the RCS also doesn't appear to drop events. Setting the DERRMR
11934          * to zero does lead to lockups within MI_DISPLAY_FLIP.
11935          */
11936         if (req->engine->id == RCS) {
11937                 intel_ring_emit(ring, MI_LOAD_REGISTER_IMM(1));
11938                 intel_ring_emit_reg(ring, DERRMR);
11939                 intel_ring_emit(ring, ~(DERRMR_PIPEA_PRI_FLIP_DONE |
11940                                           DERRMR_PIPEB_PRI_FLIP_DONE |
11941                                           DERRMR_PIPEC_PRI_FLIP_DONE));
11942                 if (IS_GEN8(dev_priv))
11943                         intel_ring_emit(ring, MI_STORE_REGISTER_MEM_GEN8 |
11944                                               MI_SRM_LRM_GLOBAL_GTT);
11945                 else
11946                         intel_ring_emit(ring, MI_STORE_REGISTER_MEM |
11947                                               MI_SRM_LRM_GLOBAL_GTT);
11948                 intel_ring_emit_reg(ring, DERRMR);
11949                 intel_ring_emit(ring,
11950                                 i915_ggtt_offset(req->engine->scratch) + 256);
11951                 if (IS_GEN8(dev_priv)) {
11952                         intel_ring_emit(ring, 0);
11953                         intel_ring_emit(ring, MI_NOOP);
11954                 }
11955         }
11956
11957         intel_ring_emit(ring, MI_DISPLAY_FLIP_I915 | plane_bit);
11958         intel_ring_emit(ring, fb->pitches[0] |
11959                         intel_fb_modifier_to_tiling(fb->modifier[0]));
11960         intel_ring_emit(ring, intel_crtc->flip_work->gtt_offset);
11961         intel_ring_emit(ring, (MI_NOOP));
11962
11963         return 0;
11964 }
11965
11966 static bool use_mmio_flip(struct intel_engine_cs *engine,
11967                           struct drm_i915_gem_object *obj)
11968 {
11969         struct reservation_object *resv;
11970
11971         /*
11972          * This is not being used for older platforms, because
11973          * non-availability of flip done interrupt forces us to use
11974          * CS flips. Older platforms derive flip done using some clever
11975          * tricks involving the flip_pending status bits and vblank irqs.
11976          * So using MMIO flips there would disrupt this mechanism.
11977          */
11978
11979         if (engine == NULL)
11980                 return true;
11981
11982         if (INTEL_GEN(engine->i915) < 5)
11983                 return false;
11984
11985         if (i915.use_mmio_flip < 0)
11986                 return false;
11987         else if (i915.use_mmio_flip > 0)
11988                 return true;
11989         else if (i915.enable_execlists)
11990                 return true;
11991
11992         resv = i915_gem_object_get_dmabuf_resv(obj);
11993         if (resv && !reservation_object_test_signaled_rcu(resv, false))
11994                 return true;
11995
11996         return engine != i915_gem_active_get_engine(&obj->last_write,
11997                                                     &obj->base.dev->struct_mutex);
11998 }
11999
12000 static void skl_do_mmio_flip(struct intel_crtc *intel_crtc,
12001                              unsigned int rotation,
12002                              struct intel_flip_work *work)
12003 {
12004         struct drm_device *dev = intel_crtc->base.dev;
12005         struct drm_i915_private *dev_priv = to_i915(dev);
12006         struct drm_framebuffer *fb = intel_crtc->base.primary->fb;
12007         const enum pipe pipe = intel_crtc->pipe;
12008         u32 ctl, stride = skl_plane_stride(fb, 0, rotation);
12009
12010         ctl = I915_READ(PLANE_CTL(pipe, 0));
12011         ctl &= ~PLANE_CTL_TILED_MASK;
12012         switch (fb->modifier[0]) {
12013         case DRM_FORMAT_MOD_NONE:
12014                 break;
12015         case I915_FORMAT_MOD_X_TILED:
12016                 ctl |= PLANE_CTL_TILED_X;
12017                 break;
12018         case I915_FORMAT_MOD_Y_TILED:
12019                 ctl |= PLANE_CTL_TILED_Y;
12020                 break;
12021         case I915_FORMAT_MOD_Yf_TILED:
12022                 ctl |= PLANE_CTL_TILED_YF;
12023                 break;
12024         default:
12025                 MISSING_CASE(fb->modifier[0]);
12026         }
12027
12028         /*
12029          * Both PLANE_CTL and PLANE_STRIDE are not updated on vblank but on
12030          * PLANE_SURF updates, the update is then guaranteed to be atomic.
12031          */
12032         I915_WRITE(PLANE_CTL(pipe, 0), ctl);
12033         I915_WRITE(PLANE_STRIDE(pipe, 0), stride);
12034
12035         I915_WRITE(PLANE_SURF(pipe, 0), work->gtt_offset);
12036         POSTING_READ(PLANE_SURF(pipe, 0));
12037 }
12038
12039 static void ilk_do_mmio_flip(struct intel_crtc *intel_crtc,
12040                              struct intel_flip_work *work)
12041 {
12042         struct drm_device *dev = intel_crtc->base.dev;
12043         struct drm_i915_private *dev_priv = to_i915(dev);
12044         struct drm_framebuffer *fb = intel_crtc->base.primary->fb;
12045         i915_reg_t reg = DSPCNTR(intel_crtc->plane);
12046         u32 dspcntr;
12047
12048         dspcntr = I915_READ(reg);
12049
12050         if (fb->modifier[0] == I915_FORMAT_MOD_X_TILED)
12051                 dspcntr |= DISPPLANE_TILED;
12052         else
12053                 dspcntr &= ~DISPPLANE_TILED;
12054
12055         I915_WRITE(reg, dspcntr);
12056
12057         I915_WRITE(DSPSURF(intel_crtc->plane), work->gtt_offset);
12058         POSTING_READ(DSPSURF(intel_crtc->plane));
12059 }
12060
12061 static void intel_mmio_flip_work_func(struct work_struct *w)
12062 {
12063         struct intel_flip_work *work =
12064                 container_of(w, struct intel_flip_work, mmio_work);
12065         struct intel_crtc *crtc = to_intel_crtc(work->crtc);
12066         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
12067         struct intel_framebuffer *intel_fb =
12068                 to_intel_framebuffer(crtc->base.primary->fb);
12069         struct drm_i915_gem_object *obj = intel_fb->obj;
12070         struct reservation_object *resv;
12071
12072         if (work->flip_queued_req)
12073                 WARN_ON(i915_wait_request(work->flip_queued_req,
12074                                           0, NULL, NO_WAITBOOST));
12075
12076         /* For framebuffer backed by dmabuf, wait for fence */
12077         resv = i915_gem_object_get_dmabuf_resv(obj);
12078         if (resv)
12079                 WARN_ON(reservation_object_wait_timeout_rcu(resv, false, false,
12080                                                             MAX_SCHEDULE_TIMEOUT) < 0);
12081
12082         intel_pipe_update_start(crtc);
12083
12084         if (INTEL_GEN(dev_priv) >= 9)
12085                 skl_do_mmio_flip(crtc, work->rotation, work);
12086         else
12087                 /* use_mmio_flip() retricts MMIO flips to ilk+ */
12088                 ilk_do_mmio_flip(crtc, work);
12089
12090         intel_pipe_update_end(crtc, work);
12091 }
12092
12093 static int intel_default_queue_flip(struct drm_device *dev,
12094                                     struct drm_crtc *crtc,
12095                                     struct drm_framebuffer *fb,
12096                                     struct drm_i915_gem_object *obj,
12097                                     struct drm_i915_gem_request *req,
12098                                     uint32_t flags)
12099 {
12100         return -ENODEV;
12101 }
12102
12103 static bool __pageflip_stall_check_cs(struct drm_i915_private *dev_priv,
12104                                       struct intel_crtc *intel_crtc,
12105                                       struct intel_flip_work *work)
12106 {
12107         u32 addr, vblank;
12108
12109         if (!atomic_read(&work->pending))
12110                 return false;
12111
12112         smp_rmb();
12113
12114         vblank = intel_crtc_get_vblank_counter(intel_crtc);
12115         if (work->flip_ready_vblank == 0) {
12116                 if (work->flip_queued_req &&
12117                     !i915_gem_request_completed(work->flip_queued_req))
12118                         return false;
12119
12120                 work->flip_ready_vblank = vblank;
12121         }
12122
12123         if (vblank - work->flip_ready_vblank < 3)
12124                 return false;
12125
12126         /* Potential stall - if we see that the flip has happened,
12127          * assume a missed interrupt. */
12128         if (INTEL_GEN(dev_priv) >= 4)
12129                 addr = I915_HI_DISPBASE(I915_READ(DSPSURF(intel_crtc->plane)));
12130         else
12131                 addr = I915_READ(DSPADDR(intel_crtc->plane));
12132
12133         /* There is a potential issue here with a false positive after a flip
12134          * to the same address. We could address this by checking for a
12135          * non-incrementing frame counter.
12136          */
12137         return addr == work->gtt_offset;
12138 }
12139
12140 void intel_check_page_flip(struct drm_i915_private *dev_priv, int pipe)
12141 {
12142         struct drm_device *dev = &dev_priv->drm;
12143         struct drm_crtc *crtc = dev_priv->pipe_to_crtc_mapping[pipe];
12144         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
12145         struct intel_flip_work *work;
12146
12147         WARN_ON(!in_interrupt());
12148
12149         if (crtc == NULL)
12150                 return;
12151
12152         spin_lock(&dev->event_lock);
12153         work = intel_crtc->flip_work;
12154
12155         if (work != NULL && !is_mmio_work(work) &&
12156             __pageflip_stall_check_cs(dev_priv, intel_crtc, work)) {
12157                 WARN_ONCE(1,
12158                           "Kicking stuck page flip: queued at %d, now %d\n",
12159                         work->flip_queued_vblank, intel_crtc_get_vblank_counter(intel_crtc));
12160                 page_flip_completed(intel_crtc);
12161                 work = NULL;
12162         }
12163
12164         if (work != NULL && !is_mmio_work(work) &&
12165             intel_crtc_get_vblank_counter(intel_crtc) - work->flip_queued_vblank > 1)
12166                 intel_queue_rps_boost_for_request(work->flip_queued_req);
12167         spin_unlock(&dev->event_lock);
12168 }
12169
12170 static int intel_crtc_page_flip(struct drm_crtc *crtc,
12171                                 struct drm_framebuffer *fb,
12172                                 struct drm_pending_vblank_event *event,
12173                                 uint32_t page_flip_flags)
12174 {
12175         struct drm_device *dev = crtc->dev;
12176         struct drm_i915_private *dev_priv = to_i915(dev);
12177         struct drm_framebuffer *old_fb = crtc->primary->fb;
12178         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
12179         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
12180         struct drm_plane *primary = crtc->primary;
12181         enum pipe pipe = intel_crtc->pipe;
12182         struct intel_flip_work *work;
12183         struct intel_engine_cs *engine;
12184         bool mmio_flip;
12185         struct drm_i915_gem_request *request;
12186         struct i915_vma *vma;
12187         int ret;
12188
12189         /*
12190          * drm_mode_page_flip_ioctl() should already catch this, but double
12191          * check to be safe.  In the future we may enable pageflipping from
12192          * a disabled primary plane.
12193          */
12194         if (WARN_ON(intel_fb_obj(old_fb) == NULL))
12195                 return -EBUSY;
12196
12197         /* Can't change pixel format via MI display flips. */
12198         if (fb->pixel_format != crtc->primary->fb->pixel_format)
12199                 return -EINVAL;
12200
12201         /*
12202          * TILEOFF/LINOFF registers can't be changed via MI display flips.
12203          * Note that pitch changes could also affect these register.
12204          */
12205         if (INTEL_INFO(dev)->gen > 3 &&
12206             (fb->offsets[0] != crtc->primary->fb->offsets[0] ||
12207              fb->pitches[0] != crtc->primary->fb->pitches[0]))
12208                 return -EINVAL;
12209
12210         if (i915_terminally_wedged(&dev_priv->gpu_error))
12211                 goto out_hang;
12212
12213         work = kzalloc(sizeof(*work), GFP_KERNEL);
12214         if (work == NULL)
12215                 return -ENOMEM;
12216
12217         work->event = event;
12218         work->crtc = crtc;
12219         work->old_fb = old_fb;
12220         INIT_WORK(&work->unpin_work, intel_unpin_work_fn);
12221
12222         ret = drm_crtc_vblank_get(crtc);
12223         if (ret)
12224                 goto free_work;
12225
12226         /* We borrow the event spin lock for protecting flip_work */
12227         spin_lock_irq(&dev->event_lock);
12228         if (intel_crtc->flip_work) {
12229                 /* Before declaring the flip queue wedged, check if
12230                  * the hardware completed the operation behind our backs.
12231                  */
12232                 if (pageflip_finished(intel_crtc, intel_crtc->flip_work)) {
12233                         DRM_DEBUG_DRIVER("flip queue: previous flip completed, continuing\n");
12234                         page_flip_completed(intel_crtc);
12235                 } else {
12236                         DRM_DEBUG_DRIVER("flip queue: crtc already busy\n");
12237                         spin_unlock_irq(&dev->event_lock);
12238
12239                         drm_crtc_vblank_put(crtc);
12240                         kfree(work);
12241                         return -EBUSY;
12242                 }
12243         }
12244         intel_crtc->flip_work = work;
12245         spin_unlock_irq(&dev->event_lock);
12246
12247         if (atomic_read(&intel_crtc->unpin_work_count) >= 2)
12248                 flush_workqueue(dev_priv->wq);
12249
12250         /* Reference the objects for the scheduled work. */
12251         drm_framebuffer_reference(work->old_fb);
12252
12253         crtc->primary->fb = fb;
12254         update_state_fb(crtc->primary);
12255
12256         work->pending_flip_obj = i915_gem_object_get(obj);
12257
12258         ret = i915_mutex_lock_interruptible(dev);
12259         if (ret)
12260                 goto cleanup;
12261
12262         intel_crtc->reset_count = i915_reset_count(&dev_priv->gpu_error);
12263         if (i915_reset_in_progress_or_wedged(&dev_priv->gpu_error)) {
12264                 ret = -EIO;
12265                 goto cleanup;
12266         }
12267
12268         atomic_inc(&intel_crtc->unpin_work_count);
12269
12270         if (INTEL_GEN(dev_priv) >= 5 || IS_G4X(dev_priv))
12271                 work->flip_count = I915_READ(PIPE_FLIPCOUNT_G4X(pipe)) + 1;
12272
12273         if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv)) {
12274                 engine = dev_priv->engine[BCS];
12275                 if (fb->modifier[0] != old_fb->modifier[0])
12276                         /* vlv: DISPLAY_FLIP fails to change tiling */
12277                         engine = NULL;
12278         } else if (IS_IVYBRIDGE(dev_priv) || IS_HASWELL(dev_priv)) {
12279                 engine = dev_priv->engine[BCS];
12280         } else if (INTEL_INFO(dev)->gen >= 7) {
12281                 engine = i915_gem_active_get_engine(&obj->last_write,
12282                                                     &obj->base.dev->struct_mutex);
12283                 if (engine == NULL || engine->id != RCS)
12284                         engine = dev_priv->engine[BCS];
12285         } else {
12286                 engine = dev_priv->engine[RCS];
12287         }
12288
12289         mmio_flip = use_mmio_flip(engine, obj);
12290
12291         vma = intel_pin_and_fence_fb_obj(fb, primary->state->rotation);
12292         if (IS_ERR(vma)) {
12293                 ret = PTR_ERR(vma);
12294                 goto cleanup_pending;
12295         }
12296
12297         work->gtt_offset = intel_fb_gtt_offset(fb, primary->state->rotation);
12298         work->gtt_offset += intel_crtc->dspaddr_offset;
12299         work->rotation = crtc->primary->state->rotation;
12300
12301         /*
12302          * There's the potential that the next frame will not be compatible with
12303          * FBC, so we want to call pre_update() before the actual page flip.
12304          * The problem is that pre_update() caches some information about the fb
12305          * object, so we want to do this only after the object is pinned. Let's
12306          * be on the safe side and do this immediately before scheduling the
12307          * flip.
12308          */
12309         intel_fbc_pre_update(intel_crtc, intel_crtc->config,
12310                              to_intel_plane_state(primary->state));
12311
12312         if (mmio_flip) {
12313                 INIT_WORK(&work->mmio_work, intel_mmio_flip_work_func);
12314
12315                 work->flip_queued_req = i915_gem_active_get(&obj->last_write,
12316                                                             &obj->base.dev->struct_mutex);
12317                 queue_work(system_unbound_wq, &work->mmio_work);
12318         } else {
12319                 request = i915_gem_request_alloc(engine, engine->last_context);
12320                 if (IS_ERR(request)) {
12321                         ret = PTR_ERR(request);
12322                         goto cleanup_unpin;
12323                 }
12324
12325                 ret = i915_gem_request_await_object(request, obj, false);
12326                 if (ret)
12327                         goto cleanup_request;
12328
12329                 ret = dev_priv->display.queue_flip(dev, crtc, fb, obj, request,
12330                                                    page_flip_flags);
12331                 if (ret)
12332                         goto cleanup_request;
12333
12334                 intel_mark_page_flip_active(intel_crtc, work);
12335
12336                 work->flip_queued_req = i915_gem_request_get(request);
12337                 i915_add_request_no_flush(request);
12338         }
12339
12340         i915_gem_track_fb(intel_fb_obj(old_fb), obj,
12341                           to_intel_plane(primary)->frontbuffer_bit);
12342         mutex_unlock(&dev->struct_mutex);
12343
12344         intel_frontbuffer_flip_prepare(to_i915(dev),
12345                                        to_intel_plane(primary)->frontbuffer_bit);
12346
12347         trace_i915_flip_request(intel_crtc->plane, obj);
12348
12349         return 0;
12350
12351 cleanup_request:
12352         i915_add_request_no_flush(request);
12353 cleanup_unpin:
12354         intel_unpin_fb_obj(fb, crtc->primary->state->rotation);
12355 cleanup_pending:
12356         atomic_dec(&intel_crtc->unpin_work_count);
12357         mutex_unlock(&dev->struct_mutex);
12358 cleanup:
12359         crtc->primary->fb = old_fb;
12360         update_state_fb(crtc->primary);
12361
12362         i915_gem_object_put_unlocked(obj);
12363         drm_framebuffer_unreference(work->old_fb);
12364
12365         spin_lock_irq(&dev->event_lock);
12366         intel_crtc->flip_work = NULL;
12367         spin_unlock_irq(&dev->event_lock);
12368
12369         drm_crtc_vblank_put(crtc);
12370 free_work:
12371         kfree(work);
12372
12373         if (ret == -EIO) {
12374                 struct drm_atomic_state *state;
12375                 struct drm_plane_state *plane_state;
12376
12377 out_hang:
12378                 state = drm_atomic_state_alloc(dev);
12379                 if (!state)
12380                         return -ENOMEM;
12381                 state->acquire_ctx = drm_modeset_legacy_acquire_ctx(crtc);
12382
12383 retry:
12384                 plane_state = drm_atomic_get_plane_state(state, primary);
12385                 ret = PTR_ERR_OR_ZERO(plane_state);
12386                 if (!ret) {
12387                         drm_atomic_set_fb_for_plane(plane_state, fb);
12388
12389                         ret = drm_atomic_set_crtc_for_plane(plane_state, crtc);
12390                         if (!ret)
12391                                 ret = drm_atomic_commit(state);
12392                 }
12393
12394                 if (ret == -EDEADLK) {
12395                         drm_modeset_backoff(state->acquire_ctx);
12396                         drm_atomic_state_clear(state);
12397                         goto retry;
12398                 }
12399
12400                 drm_atomic_state_put(state);
12401
12402                 if (ret == 0 && event) {
12403                         spin_lock_irq(&dev->event_lock);
12404                         drm_crtc_send_vblank_event(crtc, event);
12405                         spin_unlock_irq(&dev->event_lock);
12406                 }
12407         }
12408         return ret;
12409 }
12410
12411
12412 /**
12413  * intel_wm_need_update - Check whether watermarks need updating
12414  * @plane: drm plane
12415  * @state: new plane state
12416  *
12417  * Check current plane state versus the new one to determine whether
12418  * watermarks need to be recalculated.
12419  *
12420  * Returns true or false.
12421  */
12422 static bool intel_wm_need_update(struct drm_plane *plane,
12423                                  struct drm_plane_state *state)
12424 {
12425         struct intel_plane_state *new = to_intel_plane_state(state);
12426         struct intel_plane_state *cur = to_intel_plane_state(plane->state);
12427
12428         /* Update watermarks on tiling or size changes. */
12429         if (new->base.visible != cur->base.visible)
12430                 return true;
12431
12432         if (!cur->base.fb || !new->base.fb)
12433                 return false;
12434
12435         if (cur->base.fb->modifier[0] != new->base.fb->modifier[0] ||
12436             cur->base.rotation != new->base.rotation ||
12437             drm_rect_width(&new->base.src) != drm_rect_width(&cur->base.src) ||
12438             drm_rect_height(&new->base.src) != drm_rect_height(&cur->base.src) ||
12439             drm_rect_width(&new->base.dst) != drm_rect_width(&cur->base.dst) ||
12440             drm_rect_height(&new->base.dst) != drm_rect_height(&cur->base.dst))
12441                 return true;
12442
12443         return false;
12444 }
12445
12446 static bool needs_scaling(struct intel_plane_state *state)
12447 {
12448         int src_w = drm_rect_width(&state->base.src) >> 16;
12449         int src_h = drm_rect_height(&state->base.src) >> 16;
12450         int dst_w = drm_rect_width(&state->base.dst);
12451         int dst_h = drm_rect_height(&state->base.dst);
12452
12453         return (src_w != dst_w || src_h != dst_h);
12454 }
12455
12456 int intel_plane_atomic_calc_changes(struct drm_crtc_state *crtc_state,
12457                                     struct drm_plane_state *plane_state)
12458 {
12459         struct intel_crtc_state *pipe_config = to_intel_crtc_state(crtc_state);
12460         struct drm_crtc *crtc = crtc_state->crtc;
12461         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
12462         struct drm_plane *plane = plane_state->plane;
12463         struct drm_device *dev = crtc->dev;
12464         struct drm_i915_private *dev_priv = to_i915(dev);
12465         struct intel_plane_state *old_plane_state =
12466                 to_intel_plane_state(plane->state);
12467         bool mode_changed = needs_modeset(crtc_state);
12468         bool was_crtc_enabled = crtc->state->active;
12469         bool is_crtc_enabled = crtc_state->active;
12470         bool turn_off, turn_on, visible, was_visible;
12471         struct drm_framebuffer *fb = plane_state->fb;
12472         int ret;
12473
12474         if (INTEL_GEN(dev_priv) >= 9 && plane->type != DRM_PLANE_TYPE_CURSOR) {
12475                 ret = skl_update_scaler_plane(
12476                         to_intel_crtc_state(crtc_state),
12477                         to_intel_plane_state(plane_state));
12478                 if (ret)
12479                         return ret;
12480         }
12481
12482         was_visible = old_plane_state->base.visible;
12483         visible = to_intel_plane_state(plane_state)->base.visible;
12484
12485         if (!was_crtc_enabled && WARN_ON(was_visible))
12486                 was_visible = false;
12487
12488         /*
12489          * Visibility is calculated as if the crtc was on, but
12490          * after scaler setup everything depends on it being off
12491          * when the crtc isn't active.
12492          *
12493          * FIXME this is wrong for watermarks. Watermarks should also
12494          * be computed as if the pipe would be active. Perhaps move
12495          * per-plane wm computation to the .check_plane() hook, and
12496          * only combine the results from all planes in the current place?
12497          */
12498         if (!is_crtc_enabled)
12499                 to_intel_plane_state(plane_state)->base.visible = visible = false;
12500
12501         if (!was_visible && !visible)
12502                 return 0;
12503
12504         if (fb != old_plane_state->base.fb)
12505                 pipe_config->fb_changed = true;
12506
12507         turn_off = was_visible && (!visible || mode_changed);
12508         turn_on = visible && (!was_visible || mode_changed);
12509
12510         DRM_DEBUG_ATOMIC("[CRTC:%d:%s] has [PLANE:%d:%s] with fb %i\n",
12511                          intel_crtc->base.base.id,
12512                          intel_crtc->base.name,
12513                          plane->base.id, plane->name,
12514                          fb ? fb->base.id : -1);
12515
12516         DRM_DEBUG_ATOMIC("[PLANE:%d:%s] visible %i -> %i, off %i, on %i, ms %i\n",
12517                          plane->base.id, plane->name,
12518                          was_visible, visible,
12519                          turn_off, turn_on, mode_changed);
12520
12521         if (turn_on) {
12522                 pipe_config->update_wm_pre = true;
12523
12524                 /* must disable cxsr around plane enable/disable */
12525                 if (plane->type != DRM_PLANE_TYPE_CURSOR)
12526                         pipe_config->disable_cxsr = true;
12527         } else if (turn_off) {
12528                 pipe_config->update_wm_post = true;
12529
12530                 /* must disable cxsr around plane enable/disable */
12531                 if (plane->type != DRM_PLANE_TYPE_CURSOR)
12532                         pipe_config->disable_cxsr = true;
12533         } else if (intel_wm_need_update(plane, plane_state)) {
12534                 /* FIXME bollocks */
12535                 pipe_config->update_wm_pre = true;
12536                 pipe_config->update_wm_post = true;
12537         }
12538
12539         /* Pre-gen9 platforms need two-step watermark updates */
12540         if ((pipe_config->update_wm_pre || pipe_config->update_wm_post) &&
12541             INTEL_INFO(dev)->gen < 9 && dev_priv->display.optimize_watermarks)
12542                 to_intel_crtc_state(crtc_state)->wm.need_postvbl_update = true;
12543
12544         if (visible || was_visible)
12545                 pipe_config->fb_bits |= to_intel_plane(plane)->frontbuffer_bit;
12546
12547         /*
12548          * WaCxSRDisabledForSpriteScaling:ivb
12549          *
12550          * cstate->update_wm was already set above, so this flag will
12551          * take effect when we commit and program watermarks.
12552          */
12553         if (plane->type == DRM_PLANE_TYPE_OVERLAY && IS_IVYBRIDGE(dev_priv) &&
12554             needs_scaling(to_intel_plane_state(plane_state)) &&
12555             !needs_scaling(old_plane_state))
12556                 pipe_config->disable_lp_wm = true;
12557
12558         return 0;
12559 }
12560
12561 static bool encoders_cloneable(const struct intel_encoder *a,
12562                                const struct intel_encoder *b)
12563 {
12564         /* masks could be asymmetric, so check both ways */
12565         return a == b || (a->cloneable & (1 << b->type) &&
12566                           b->cloneable & (1 << a->type));
12567 }
12568
12569 static bool check_single_encoder_cloning(struct drm_atomic_state *state,
12570                                          struct intel_crtc *crtc,
12571                                          struct intel_encoder *encoder)
12572 {
12573         struct intel_encoder *source_encoder;
12574         struct drm_connector *connector;
12575         struct drm_connector_state *connector_state;
12576         int i;
12577
12578         for_each_connector_in_state(state, connector, connector_state, i) {
12579                 if (connector_state->crtc != &crtc->base)
12580                         continue;
12581
12582                 source_encoder =
12583                         to_intel_encoder(connector_state->best_encoder);
12584                 if (!encoders_cloneable(encoder, source_encoder))
12585                         return false;
12586         }
12587
12588         return true;
12589 }
12590
12591 static int intel_crtc_atomic_check(struct drm_crtc *crtc,
12592                                    struct drm_crtc_state *crtc_state)
12593 {
12594         struct drm_device *dev = crtc->dev;
12595         struct drm_i915_private *dev_priv = to_i915(dev);
12596         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
12597         struct intel_crtc_state *pipe_config =
12598                 to_intel_crtc_state(crtc_state);
12599         struct drm_atomic_state *state = crtc_state->state;
12600         int ret;
12601         bool mode_changed = needs_modeset(crtc_state);
12602
12603         if (mode_changed && !crtc_state->active)
12604                 pipe_config->update_wm_post = true;
12605
12606         if (mode_changed && crtc_state->enable &&
12607             dev_priv->display.crtc_compute_clock &&
12608             !WARN_ON(pipe_config->shared_dpll)) {
12609                 ret = dev_priv->display.crtc_compute_clock(intel_crtc,
12610                                                            pipe_config);
12611                 if (ret)
12612                         return ret;
12613         }
12614
12615         if (crtc_state->color_mgmt_changed) {
12616                 ret = intel_color_check(crtc, crtc_state);
12617                 if (ret)
12618                         return ret;
12619
12620                 /*
12621                  * Changing color management on Intel hardware is
12622                  * handled as part of planes update.
12623                  */
12624                 crtc_state->planes_changed = true;
12625         }
12626
12627         ret = 0;
12628         if (dev_priv->display.compute_pipe_wm) {
12629                 ret = dev_priv->display.compute_pipe_wm(pipe_config);
12630                 if (ret) {
12631                         DRM_DEBUG_KMS("Target pipe watermarks are invalid\n");
12632                         return ret;
12633                 }
12634         }
12635
12636         if (dev_priv->display.compute_intermediate_wm &&
12637             !to_intel_atomic_state(state)->skip_intermediate_wm) {
12638                 if (WARN_ON(!dev_priv->display.compute_pipe_wm))
12639                         return 0;
12640
12641                 /*
12642                  * Calculate 'intermediate' watermarks that satisfy both the
12643                  * old state and the new state.  We can program these
12644                  * immediately.
12645                  */
12646                 ret = dev_priv->display.compute_intermediate_wm(crtc->dev,
12647                                                                 intel_crtc,
12648                                                                 pipe_config);
12649                 if (ret) {
12650                         DRM_DEBUG_KMS("No valid intermediate pipe watermarks are possible\n");
12651                         return ret;
12652                 }
12653         } else if (dev_priv->display.compute_intermediate_wm) {
12654                 if (HAS_PCH_SPLIT(dev_priv) && INTEL_GEN(dev_priv) < 9)
12655                         pipe_config->wm.ilk.intermediate = pipe_config->wm.ilk.optimal;
12656         }
12657
12658         if (INTEL_INFO(dev)->gen >= 9) {
12659                 if (mode_changed)
12660                         ret = skl_update_scaler_crtc(pipe_config);
12661
12662                 if (!ret)
12663                         ret = intel_atomic_setup_scalers(dev, intel_crtc,
12664                                                          pipe_config);
12665         }
12666
12667         return ret;
12668 }
12669
12670 static const struct drm_crtc_helper_funcs intel_helper_funcs = {
12671         .mode_set_base_atomic = intel_pipe_set_base_atomic,
12672         .atomic_begin = intel_begin_crtc_commit,
12673         .atomic_flush = intel_finish_crtc_commit,
12674         .atomic_check = intel_crtc_atomic_check,
12675 };
12676
12677 static void intel_modeset_update_connector_atomic_state(struct drm_device *dev)
12678 {
12679         struct intel_connector *connector;
12680
12681         for_each_intel_connector(dev, connector) {
12682                 if (connector->base.state->crtc)
12683                         drm_connector_unreference(&connector->base);
12684
12685                 if (connector->base.encoder) {
12686                         connector->base.state->best_encoder =
12687                                 connector->base.encoder;
12688                         connector->base.state->crtc =
12689                                 connector->base.encoder->crtc;
12690
12691                         drm_connector_reference(&connector->base);
12692                 } else {
12693                         connector->base.state->best_encoder = NULL;
12694                         connector->base.state->crtc = NULL;
12695                 }
12696         }
12697 }
12698
12699 static void
12700 connected_sink_compute_bpp(struct intel_connector *connector,
12701                            struct intel_crtc_state *pipe_config)
12702 {
12703         const struct drm_display_info *info = &connector->base.display_info;
12704         int bpp = pipe_config->pipe_bpp;
12705
12706         DRM_DEBUG_KMS("[CONNECTOR:%d:%s] checking for sink bpp constrains\n",
12707                       connector->base.base.id,
12708                       connector->base.name);
12709
12710         /* Don't use an invalid EDID bpc value */
12711         if (info->bpc != 0 && info->bpc * 3 < bpp) {
12712                 DRM_DEBUG_KMS("clamping display bpp (was %d) to EDID reported max of %d\n",
12713                               bpp, info->bpc * 3);
12714                 pipe_config->pipe_bpp = info->bpc * 3;
12715         }
12716
12717         /* Clamp bpp to 8 on screens without EDID 1.4 */
12718         if (info->bpc == 0 && bpp > 24) {
12719                 DRM_DEBUG_KMS("clamping display bpp (was %d) to default limit of 24\n",
12720                               bpp);
12721                 pipe_config->pipe_bpp = 24;
12722         }
12723 }
12724
12725 static int
12726 compute_baseline_pipe_bpp(struct intel_crtc *crtc,
12727                           struct intel_crtc_state *pipe_config)
12728 {
12729         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
12730         struct drm_atomic_state *state;
12731         struct drm_connector *connector;
12732         struct drm_connector_state *connector_state;
12733         int bpp, i;
12734
12735         if ((IS_G4X(dev_priv) || IS_VALLEYVIEW(dev_priv) ||
12736             IS_CHERRYVIEW(dev_priv)))
12737                 bpp = 10*3;
12738         else if (INTEL_GEN(dev_priv) >= 5)
12739                 bpp = 12*3;
12740         else
12741                 bpp = 8*3;
12742
12743
12744         pipe_config->pipe_bpp = bpp;
12745
12746         state = pipe_config->base.state;
12747
12748         /* Clamp display bpp to EDID value */
12749         for_each_connector_in_state(state, connector, connector_state, i) {
12750                 if (connector_state->crtc != &crtc->base)
12751                         continue;
12752
12753                 connected_sink_compute_bpp(to_intel_connector(connector),
12754                                            pipe_config);
12755         }
12756
12757         return bpp;
12758 }
12759
12760 static void intel_dump_crtc_timings(const struct drm_display_mode *mode)
12761 {
12762         DRM_DEBUG_KMS("crtc timings: %d %d %d %d %d %d %d %d %d, "
12763                         "type: 0x%x flags: 0x%x\n",
12764                 mode->crtc_clock,
12765                 mode->crtc_hdisplay, mode->crtc_hsync_start,
12766                 mode->crtc_hsync_end, mode->crtc_htotal,
12767                 mode->crtc_vdisplay, mode->crtc_vsync_start,
12768                 mode->crtc_vsync_end, mode->crtc_vtotal, mode->type, mode->flags);
12769 }
12770
12771 static void intel_dump_pipe_config(struct intel_crtc *crtc,
12772                                    struct intel_crtc_state *pipe_config,
12773                                    const char *context)
12774 {
12775         struct drm_device *dev = crtc->base.dev;
12776         struct drm_i915_private *dev_priv = to_i915(dev);
12777         struct drm_plane *plane;
12778         struct intel_plane *intel_plane;
12779         struct intel_plane_state *state;
12780         struct drm_framebuffer *fb;
12781
12782         DRM_DEBUG_KMS("[CRTC:%d:%s]%s config %p for pipe %c\n",
12783                       crtc->base.base.id, crtc->base.name,
12784                       context, pipe_config, pipe_name(crtc->pipe));
12785
12786         DRM_DEBUG_KMS("cpu_transcoder: %s\n", transcoder_name(pipe_config->cpu_transcoder));
12787         DRM_DEBUG_KMS("pipe bpp: %i, dithering: %i\n",
12788                       pipe_config->pipe_bpp, pipe_config->dither);
12789         DRM_DEBUG_KMS("fdi/pch: %i, lanes: %i, gmch_m: %u, gmch_n: %u, link_m: %u, link_n: %u, tu: %u\n",
12790                       pipe_config->has_pch_encoder,
12791                       pipe_config->fdi_lanes,
12792                       pipe_config->fdi_m_n.gmch_m, pipe_config->fdi_m_n.gmch_n,
12793                       pipe_config->fdi_m_n.link_m, pipe_config->fdi_m_n.link_n,
12794                       pipe_config->fdi_m_n.tu);
12795         DRM_DEBUG_KMS("dp: %i, lanes: %i, gmch_m: %u, gmch_n: %u, link_m: %u, link_n: %u, tu: %u\n",
12796                       intel_crtc_has_dp_encoder(pipe_config),
12797                       pipe_config->lane_count,
12798                       pipe_config->dp_m_n.gmch_m, pipe_config->dp_m_n.gmch_n,
12799                       pipe_config->dp_m_n.link_m, pipe_config->dp_m_n.link_n,
12800                       pipe_config->dp_m_n.tu);
12801
12802         DRM_DEBUG_KMS("dp: %i, lanes: %i, gmch_m2: %u, gmch_n2: %u, link_m2: %u, link_n2: %u, tu2: %u\n",
12803                       intel_crtc_has_dp_encoder(pipe_config),
12804                       pipe_config->lane_count,
12805                       pipe_config->dp_m2_n2.gmch_m,
12806                       pipe_config->dp_m2_n2.gmch_n,
12807                       pipe_config->dp_m2_n2.link_m,
12808                       pipe_config->dp_m2_n2.link_n,
12809                       pipe_config->dp_m2_n2.tu);
12810
12811         DRM_DEBUG_KMS("audio: %i, infoframes: %i\n",
12812                       pipe_config->has_audio,
12813                       pipe_config->has_infoframe);
12814
12815         DRM_DEBUG_KMS("requested mode:\n");
12816         drm_mode_debug_printmodeline(&pipe_config->base.mode);
12817         DRM_DEBUG_KMS("adjusted mode:\n");
12818         drm_mode_debug_printmodeline(&pipe_config->base.adjusted_mode);
12819         intel_dump_crtc_timings(&pipe_config->base.adjusted_mode);
12820         DRM_DEBUG_KMS("port clock: %d\n", pipe_config->port_clock);
12821         DRM_DEBUG_KMS("pipe src size: %dx%d\n",
12822                       pipe_config->pipe_src_w, pipe_config->pipe_src_h);
12823         DRM_DEBUG_KMS("num_scalers: %d, scaler_users: 0x%x, scaler_id: %d\n",
12824                       crtc->num_scalers,
12825                       pipe_config->scaler_state.scaler_users,
12826                       pipe_config->scaler_state.scaler_id);
12827         DRM_DEBUG_KMS("gmch pfit: control: 0x%08x, ratios: 0x%08x, lvds border: 0x%08x\n",
12828                       pipe_config->gmch_pfit.control,
12829                       pipe_config->gmch_pfit.pgm_ratios,
12830                       pipe_config->gmch_pfit.lvds_border_bits);
12831         DRM_DEBUG_KMS("pch pfit: pos: 0x%08x, size: 0x%08x, %s\n",
12832                       pipe_config->pch_pfit.pos,
12833                       pipe_config->pch_pfit.size,
12834                       pipe_config->pch_pfit.enabled ? "enabled" : "disabled");
12835         DRM_DEBUG_KMS("ips: %i\n", pipe_config->ips_enabled);
12836         DRM_DEBUG_KMS("double wide: %i\n", pipe_config->double_wide);
12837
12838         if (IS_BROXTON(dev_priv)) {
12839                 DRM_DEBUG_KMS("dpll_hw_state: ebb0: 0x%x, ebb4: 0x%x,"
12840                               "pll0: 0x%x, pll1: 0x%x, pll2: 0x%x, pll3: 0x%x, "
12841                               "pll6: 0x%x, pll8: 0x%x, pll9: 0x%x, pll10: 0x%x, pcsdw12: 0x%x\n",
12842                               pipe_config->dpll_hw_state.ebb0,
12843                               pipe_config->dpll_hw_state.ebb4,
12844                               pipe_config->dpll_hw_state.pll0,
12845                               pipe_config->dpll_hw_state.pll1,
12846                               pipe_config->dpll_hw_state.pll2,
12847                               pipe_config->dpll_hw_state.pll3,
12848                               pipe_config->dpll_hw_state.pll6,
12849                               pipe_config->dpll_hw_state.pll8,
12850                               pipe_config->dpll_hw_state.pll9,
12851                               pipe_config->dpll_hw_state.pll10,
12852                               pipe_config->dpll_hw_state.pcsdw12);
12853         } else if (IS_SKYLAKE(dev_priv) || IS_KABYLAKE(dev_priv)) {
12854                 DRM_DEBUG_KMS("dpll_hw_state: "
12855                               "ctrl1: 0x%x, cfgcr1: 0x%x, cfgcr2: 0x%x\n",
12856                               pipe_config->dpll_hw_state.ctrl1,
12857                               pipe_config->dpll_hw_state.cfgcr1,
12858                               pipe_config->dpll_hw_state.cfgcr2);
12859         } else if (HAS_DDI(dev_priv)) {
12860                 DRM_DEBUG_KMS("dpll_hw_state: wrpll: 0x%x spll: 0x%x\n",
12861                               pipe_config->dpll_hw_state.wrpll,
12862                               pipe_config->dpll_hw_state.spll);
12863         } else {
12864                 DRM_DEBUG_KMS("dpll_hw_state: dpll: 0x%x, dpll_md: 0x%x, "
12865                               "fp0: 0x%x, fp1: 0x%x\n",
12866                               pipe_config->dpll_hw_state.dpll,
12867                               pipe_config->dpll_hw_state.dpll_md,
12868                               pipe_config->dpll_hw_state.fp0,
12869                               pipe_config->dpll_hw_state.fp1);
12870         }
12871
12872         DRM_DEBUG_KMS("planes on this crtc\n");
12873         list_for_each_entry(plane, &dev->mode_config.plane_list, head) {
12874                 char *format_name;
12875                 intel_plane = to_intel_plane(plane);
12876                 if (intel_plane->pipe != crtc->pipe)
12877                         continue;
12878
12879                 state = to_intel_plane_state(plane->state);
12880                 fb = state->base.fb;
12881                 if (!fb) {
12882                         DRM_DEBUG_KMS("[PLANE:%d:%s] disabled, scaler_id = %d\n",
12883                                       plane->base.id, plane->name, state->scaler_id);
12884                         continue;
12885                 }
12886
12887                 format_name = drm_get_format_name(fb->pixel_format);
12888
12889                 DRM_DEBUG_KMS("[PLANE:%d:%s] enabled",
12890                               plane->base.id, plane->name);
12891                 DRM_DEBUG_KMS("\tFB:%d, fb = %ux%u format = %s",
12892                               fb->base.id, fb->width, fb->height, format_name);
12893                 DRM_DEBUG_KMS("\tscaler:%d src %dx%d+%d+%d dst %dx%d+%d+%d\n",
12894                               state->scaler_id,
12895                               state->base.src.x1 >> 16,
12896                               state->base.src.y1 >> 16,
12897                               drm_rect_width(&state->base.src) >> 16,
12898                               drm_rect_height(&state->base.src) >> 16,
12899                               state->base.dst.x1, state->base.dst.y1,
12900                               drm_rect_width(&state->base.dst),
12901                               drm_rect_height(&state->base.dst));
12902
12903                 kfree(format_name);
12904         }
12905 }
12906
12907 static bool check_digital_port_conflicts(struct drm_atomic_state *state)
12908 {
12909         struct drm_device *dev = state->dev;
12910         struct drm_connector *connector;
12911         unsigned int used_ports = 0;
12912         unsigned int used_mst_ports = 0;
12913
12914         /*
12915          * Walk the connector list instead of the encoder
12916          * list to detect the problem on ddi platforms
12917          * where there's just one encoder per digital port.
12918          */
12919         drm_for_each_connector(connector, dev) {
12920                 struct drm_connector_state *connector_state;
12921                 struct intel_encoder *encoder;
12922
12923                 connector_state = drm_atomic_get_existing_connector_state(state, connector);
12924                 if (!connector_state)
12925                         connector_state = connector->state;
12926
12927                 if (!connector_state->best_encoder)
12928                         continue;
12929
12930                 encoder = to_intel_encoder(connector_state->best_encoder);
12931
12932                 WARN_ON(!connector_state->crtc);
12933
12934                 switch (encoder->type) {
12935                         unsigned int port_mask;
12936                 case INTEL_OUTPUT_UNKNOWN:
12937                         if (WARN_ON(!HAS_DDI(to_i915(dev))))
12938                                 break;
12939                 case INTEL_OUTPUT_DP:
12940                 case INTEL_OUTPUT_HDMI:
12941                 case INTEL_OUTPUT_EDP:
12942                         port_mask = 1 << enc_to_dig_port(&encoder->base)->port;
12943
12944                         /* the same port mustn't appear more than once */
12945                         if (used_ports & port_mask)
12946                                 return false;
12947
12948                         used_ports |= port_mask;
12949                         break;
12950                 case INTEL_OUTPUT_DP_MST:
12951                         used_mst_ports |=
12952                                 1 << enc_to_mst(&encoder->base)->primary->port;
12953                         break;
12954                 default:
12955                         break;
12956                 }
12957         }
12958
12959         /* can't mix MST and SST/HDMI on the same port */
12960         if (used_ports & used_mst_ports)
12961                 return false;
12962
12963         return true;
12964 }
12965
12966 static void
12967 clear_intel_crtc_state(struct intel_crtc_state *crtc_state)
12968 {
12969         struct drm_crtc_state tmp_state;
12970         struct intel_crtc_scaler_state scaler_state;
12971         struct intel_dpll_hw_state dpll_hw_state;
12972         struct intel_shared_dpll *shared_dpll;
12973         bool force_thru;
12974
12975         /* FIXME: before the switch to atomic started, a new pipe_config was
12976          * kzalloc'd. Code that depends on any field being zero should be
12977          * fixed, so that the crtc_state can be safely duplicated. For now,
12978          * only fields that are know to not cause problems are preserved. */
12979
12980         tmp_state = crtc_state->base;
12981         scaler_state = crtc_state->scaler_state;
12982         shared_dpll = crtc_state->shared_dpll;
12983         dpll_hw_state = crtc_state->dpll_hw_state;
12984         force_thru = crtc_state->pch_pfit.force_thru;
12985
12986         memset(crtc_state, 0, sizeof *crtc_state);
12987
12988         crtc_state->base = tmp_state;
12989         crtc_state->scaler_state = scaler_state;
12990         crtc_state->shared_dpll = shared_dpll;
12991         crtc_state->dpll_hw_state = dpll_hw_state;
12992         crtc_state->pch_pfit.force_thru = force_thru;
12993 }
12994
12995 static int
12996 intel_modeset_pipe_config(struct drm_crtc *crtc,
12997                           struct intel_crtc_state *pipe_config)
12998 {
12999         struct drm_atomic_state *state = pipe_config->base.state;
13000         struct intel_encoder *encoder;
13001         struct drm_connector *connector;
13002         struct drm_connector_state *connector_state;
13003         int base_bpp, ret = -EINVAL;
13004         int i;
13005         bool retry = true;
13006
13007         clear_intel_crtc_state(pipe_config);
13008
13009         pipe_config->cpu_transcoder =
13010                 (enum transcoder) to_intel_crtc(crtc)->pipe;
13011
13012         /*
13013          * Sanitize sync polarity flags based on requested ones. If neither
13014          * positive or negative polarity is requested, treat this as meaning
13015          * negative polarity.
13016          */
13017         if (!(pipe_config->base.adjusted_mode.flags &
13018               (DRM_MODE_FLAG_PHSYNC | DRM_MODE_FLAG_NHSYNC)))
13019                 pipe_config->base.adjusted_mode.flags |= DRM_MODE_FLAG_NHSYNC;
13020
13021         if (!(pipe_config->base.adjusted_mode.flags &
13022               (DRM_MODE_FLAG_PVSYNC | DRM_MODE_FLAG_NVSYNC)))
13023                 pipe_config->base.adjusted_mode.flags |= DRM_MODE_FLAG_NVSYNC;
13024
13025         base_bpp = compute_baseline_pipe_bpp(to_intel_crtc(crtc),
13026                                              pipe_config);
13027         if (base_bpp < 0)
13028                 goto fail;
13029
13030         /*
13031          * Determine the real pipe dimensions. Note that stereo modes can
13032          * increase the actual pipe size due to the frame doubling and
13033          * insertion of additional space for blanks between the frame. This
13034          * is stored in the crtc timings. We use the requested mode to do this
13035          * computation to clearly distinguish it from the adjusted mode, which
13036          * can be changed by the connectors in the below retry loop.
13037          */
13038         drm_crtc_get_hv_timing(&pipe_config->base.mode,
13039                                &pipe_config->pipe_src_w,
13040                                &pipe_config->pipe_src_h);
13041
13042         for_each_connector_in_state(state, connector, connector_state, i) {
13043                 if (connector_state->crtc != crtc)
13044                         continue;
13045
13046                 encoder = to_intel_encoder(connector_state->best_encoder);
13047
13048                 if (!check_single_encoder_cloning(state, to_intel_crtc(crtc), encoder)) {
13049                         DRM_DEBUG_KMS("rejecting invalid cloning configuration\n");
13050                         goto fail;
13051                 }
13052
13053                 /*
13054                  * Determine output_types before calling the .compute_config()
13055                  * hooks so that the hooks can use this information safely.
13056                  */
13057                 pipe_config->output_types |= 1 << encoder->type;
13058         }
13059
13060 encoder_retry:
13061         /* Ensure the port clock defaults are reset when retrying. */
13062         pipe_config->port_clock = 0;
13063         pipe_config->pixel_multiplier = 1;
13064
13065         /* Fill in default crtc timings, allow encoders to overwrite them. */
13066         drm_mode_set_crtcinfo(&pipe_config->base.adjusted_mode,
13067                               CRTC_STEREO_DOUBLE);
13068
13069         /* Pass our mode to the connectors and the CRTC to give them a chance to
13070          * adjust it according to limitations or connector properties, and also
13071          * a chance to reject the mode entirely.
13072          */
13073         for_each_connector_in_state(state, connector, connector_state, i) {
13074                 if (connector_state->crtc != crtc)
13075                         continue;
13076
13077                 encoder = to_intel_encoder(connector_state->best_encoder);
13078
13079                 if (!(encoder->compute_config(encoder, pipe_config, connector_state))) {
13080                         DRM_DEBUG_KMS("Encoder config failure\n");
13081                         goto fail;
13082                 }
13083         }
13084
13085         /* Set default port clock if not overwritten by the encoder. Needs to be
13086          * done afterwards in case the encoder adjusts the mode. */
13087         if (!pipe_config->port_clock)
13088                 pipe_config->port_clock = pipe_config->base.adjusted_mode.crtc_clock
13089                         * pipe_config->pixel_multiplier;
13090
13091         ret = intel_crtc_compute_config(to_intel_crtc(crtc), pipe_config);
13092         if (ret < 0) {
13093                 DRM_DEBUG_KMS("CRTC fixup failed\n");
13094                 goto fail;
13095         }
13096
13097         if (ret == RETRY) {
13098                 if (WARN(!retry, "loop in pipe configuration computation\n")) {
13099                         ret = -EINVAL;
13100                         goto fail;
13101                 }
13102
13103                 DRM_DEBUG_KMS("CRTC bw constrained, retrying\n");
13104                 retry = false;
13105                 goto encoder_retry;
13106         }
13107
13108         /* Dithering seems to not pass-through bits correctly when it should, so
13109          * only enable it on 6bpc panels. */
13110         pipe_config->dither = pipe_config->pipe_bpp == 6*3;
13111         DRM_DEBUG_KMS("hw max bpp: %i, pipe bpp: %i, dithering: %i\n",
13112                       base_bpp, pipe_config->pipe_bpp, pipe_config->dither);
13113
13114 fail:
13115         return ret;
13116 }
13117
13118 static void
13119 intel_modeset_update_crtc_state(struct drm_atomic_state *state)
13120 {
13121         struct drm_crtc *crtc;
13122         struct drm_crtc_state *crtc_state;
13123         int i;
13124
13125         /* Double check state. */
13126         for_each_crtc_in_state(state, crtc, crtc_state, i) {
13127                 to_intel_crtc(crtc)->config = to_intel_crtc_state(crtc->state);
13128
13129                 /* Update hwmode for vblank functions */
13130                 if (crtc->state->active)
13131                         crtc->hwmode = crtc->state->adjusted_mode;
13132                 else
13133                         crtc->hwmode.crtc_clock = 0;
13134
13135                 /*
13136                  * Update legacy state to satisfy fbc code. This can
13137                  * be removed when fbc uses the atomic state.
13138                  */
13139                 if (drm_atomic_get_existing_plane_state(state, crtc->primary)) {
13140                         struct drm_plane_state *plane_state = crtc->primary->state;
13141
13142                         crtc->primary->fb = plane_state->fb;
13143                         crtc->x = plane_state->src_x >> 16;
13144                         crtc->y = plane_state->src_y >> 16;
13145                 }
13146         }
13147 }
13148
13149 static bool intel_fuzzy_clock_check(int clock1, int clock2)
13150 {
13151         int diff;
13152
13153         if (clock1 == clock2)
13154                 return true;
13155
13156         if (!clock1 || !clock2)
13157                 return false;
13158
13159         diff = abs(clock1 - clock2);
13160
13161         if (((((diff + clock1 + clock2) * 100)) / (clock1 + clock2)) < 105)
13162                 return true;
13163
13164         return false;
13165 }
13166
13167 static bool
13168 intel_compare_m_n(unsigned int m, unsigned int n,
13169                   unsigned int m2, unsigned int n2,
13170                   bool exact)
13171 {
13172         if (m == m2 && n == n2)
13173                 return true;
13174
13175         if (exact || !m || !n || !m2 || !n2)
13176                 return false;
13177
13178         BUILD_BUG_ON(DATA_LINK_M_N_MASK > INT_MAX);
13179
13180         if (n > n2) {
13181                 while (n > n2) {
13182                         m2 <<= 1;
13183                         n2 <<= 1;
13184                 }
13185         } else if (n < n2) {
13186                 while (n < n2) {
13187                         m <<= 1;
13188                         n <<= 1;
13189                 }
13190         }
13191
13192         if (n != n2)
13193                 return false;
13194
13195         return intel_fuzzy_clock_check(m, m2);
13196 }
13197
13198 static bool
13199 intel_compare_link_m_n(const struct intel_link_m_n *m_n,
13200                        struct intel_link_m_n *m2_n2,
13201                        bool adjust)
13202 {
13203         if (m_n->tu == m2_n2->tu &&
13204             intel_compare_m_n(m_n->gmch_m, m_n->gmch_n,
13205                               m2_n2->gmch_m, m2_n2->gmch_n, !adjust) &&
13206             intel_compare_m_n(m_n->link_m, m_n->link_n,
13207                               m2_n2->link_m, m2_n2->link_n, !adjust)) {
13208                 if (adjust)
13209                         *m2_n2 = *m_n;
13210
13211                 return true;
13212         }
13213
13214         return false;
13215 }
13216
13217 static bool
13218 intel_pipe_config_compare(struct drm_device *dev,
13219                           struct intel_crtc_state *current_config,
13220                           struct intel_crtc_state *pipe_config,
13221                           bool adjust)
13222 {
13223         struct drm_i915_private *dev_priv = to_i915(dev);
13224         bool ret = true;
13225
13226 #define INTEL_ERR_OR_DBG_KMS(fmt, ...) \
13227         do { \
13228                 if (!adjust) \
13229                         DRM_ERROR(fmt, ##__VA_ARGS__); \
13230                 else \
13231                         DRM_DEBUG_KMS(fmt, ##__VA_ARGS__); \
13232         } while (0)
13233
13234 #define PIPE_CONF_CHECK_X(name) \
13235         if (current_config->name != pipe_config->name) { \
13236                 INTEL_ERR_OR_DBG_KMS("mismatch in " #name " " \
13237                           "(expected 0x%08x, found 0x%08x)\n", \
13238                           current_config->name, \
13239                           pipe_config->name); \
13240                 ret = false; \
13241         }
13242
13243 #define PIPE_CONF_CHECK_I(name) \
13244         if (current_config->name != pipe_config->name) { \
13245                 INTEL_ERR_OR_DBG_KMS("mismatch in " #name " " \
13246                           "(expected %i, found %i)\n", \
13247                           current_config->name, \
13248                           pipe_config->name); \
13249                 ret = false; \
13250         }
13251
13252 #define PIPE_CONF_CHECK_P(name) \
13253         if (current_config->name != pipe_config->name) { \
13254                 INTEL_ERR_OR_DBG_KMS("mismatch in " #name " " \
13255                           "(expected %p, found %p)\n", \
13256                           current_config->name, \
13257                           pipe_config->name); \
13258                 ret = false; \
13259         }
13260
13261 #define PIPE_CONF_CHECK_M_N(name) \
13262         if (!intel_compare_link_m_n(&current_config->name, \
13263                                     &pipe_config->name,\
13264                                     adjust)) { \
13265                 INTEL_ERR_OR_DBG_KMS("mismatch in " #name " " \
13266                           "(expected tu %i gmch %i/%i link %i/%i, " \
13267                           "found tu %i, gmch %i/%i link %i/%i)\n", \
13268                           current_config->name.tu, \
13269                           current_config->name.gmch_m, \
13270                           current_config->name.gmch_n, \
13271                           current_config->name.link_m, \
13272                           current_config->name.link_n, \
13273                           pipe_config->name.tu, \
13274                           pipe_config->name.gmch_m, \
13275                           pipe_config->name.gmch_n, \
13276                           pipe_config->name.link_m, \
13277                           pipe_config->name.link_n); \
13278                 ret = false; \
13279         }
13280
13281 /* This is required for BDW+ where there is only one set of registers for
13282  * switching between high and low RR.
13283  * This macro can be used whenever a comparison has to be made between one
13284  * hw state and multiple sw state variables.
13285  */
13286 #define PIPE_CONF_CHECK_M_N_ALT(name, alt_name) \
13287         if (!intel_compare_link_m_n(&current_config->name, \
13288                                     &pipe_config->name, adjust) && \
13289             !intel_compare_link_m_n(&current_config->alt_name, \
13290                                     &pipe_config->name, adjust)) { \
13291                 INTEL_ERR_OR_DBG_KMS("mismatch in " #name " " \
13292                           "(expected tu %i gmch %i/%i link %i/%i, " \
13293                           "or tu %i gmch %i/%i link %i/%i, " \
13294                           "found tu %i, gmch %i/%i link %i/%i)\n", \
13295                           current_config->name.tu, \
13296                           current_config->name.gmch_m, \
13297                           current_config->name.gmch_n, \
13298                           current_config->name.link_m, \
13299                           current_config->name.link_n, \
13300                           current_config->alt_name.tu, \
13301                           current_config->alt_name.gmch_m, \
13302                           current_config->alt_name.gmch_n, \
13303                           current_config->alt_name.link_m, \
13304                           current_config->alt_name.link_n, \
13305                           pipe_config->name.tu, \
13306                           pipe_config->name.gmch_m, \
13307                           pipe_config->name.gmch_n, \
13308                           pipe_config->name.link_m, \
13309                           pipe_config->name.link_n); \
13310                 ret = false; \
13311         }
13312
13313 #define PIPE_CONF_CHECK_FLAGS(name, mask)       \
13314         if ((current_config->name ^ pipe_config->name) & (mask)) { \
13315                 INTEL_ERR_OR_DBG_KMS("mismatch in " #name "(" #mask ") " \
13316                           "(expected %i, found %i)\n", \
13317                           current_config->name & (mask), \
13318                           pipe_config->name & (mask)); \
13319                 ret = false; \
13320         }
13321
13322 #define PIPE_CONF_CHECK_CLOCK_FUZZY(name) \
13323         if (!intel_fuzzy_clock_check(current_config->name, pipe_config->name)) { \
13324                 INTEL_ERR_OR_DBG_KMS("mismatch in " #name " " \
13325                           "(expected %i, found %i)\n", \
13326                           current_config->name, \
13327                           pipe_config->name); \
13328                 ret = false; \
13329         }
13330
13331 #define PIPE_CONF_QUIRK(quirk)  \
13332         ((current_config->quirks | pipe_config->quirks) & (quirk))
13333
13334         PIPE_CONF_CHECK_I(cpu_transcoder);
13335
13336         PIPE_CONF_CHECK_I(has_pch_encoder);
13337         PIPE_CONF_CHECK_I(fdi_lanes);
13338         PIPE_CONF_CHECK_M_N(fdi_m_n);
13339
13340         PIPE_CONF_CHECK_I(lane_count);
13341         PIPE_CONF_CHECK_X(lane_lat_optim_mask);
13342
13343         if (INTEL_INFO(dev)->gen < 8) {
13344                 PIPE_CONF_CHECK_M_N(dp_m_n);
13345
13346                 if (current_config->has_drrs)
13347                         PIPE_CONF_CHECK_M_N(dp_m2_n2);
13348         } else
13349                 PIPE_CONF_CHECK_M_N_ALT(dp_m_n, dp_m2_n2);
13350
13351         PIPE_CONF_CHECK_X(output_types);
13352
13353         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hdisplay);
13354         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_htotal);
13355         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hblank_start);
13356         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hblank_end);
13357         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hsync_start);
13358         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hsync_end);
13359
13360         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vdisplay);
13361         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vtotal);
13362         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vblank_start);
13363         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vblank_end);
13364         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vsync_start);
13365         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vsync_end);
13366
13367         PIPE_CONF_CHECK_I(pixel_multiplier);
13368         PIPE_CONF_CHECK_I(has_hdmi_sink);
13369         if ((INTEL_GEN(dev_priv) < 8 && !IS_HASWELL(dev_priv)) ||
13370             IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
13371                 PIPE_CONF_CHECK_I(limited_color_range);
13372         PIPE_CONF_CHECK_I(has_infoframe);
13373
13374         PIPE_CONF_CHECK_I(has_audio);
13375
13376         PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
13377                               DRM_MODE_FLAG_INTERLACE);
13378
13379         if (!PIPE_CONF_QUIRK(PIPE_CONFIG_QUIRK_MODE_SYNC_FLAGS)) {
13380                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
13381                                       DRM_MODE_FLAG_PHSYNC);
13382                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
13383                                       DRM_MODE_FLAG_NHSYNC);
13384                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
13385                                       DRM_MODE_FLAG_PVSYNC);
13386                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
13387                                       DRM_MODE_FLAG_NVSYNC);
13388         }
13389
13390         PIPE_CONF_CHECK_X(gmch_pfit.control);
13391         /* pfit ratios are autocomputed by the hw on gen4+ */
13392         if (INTEL_INFO(dev)->gen < 4)
13393                 PIPE_CONF_CHECK_X(gmch_pfit.pgm_ratios);
13394         PIPE_CONF_CHECK_X(gmch_pfit.lvds_border_bits);
13395
13396         if (!adjust) {
13397                 PIPE_CONF_CHECK_I(pipe_src_w);
13398                 PIPE_CONF_CHECK_I(pipe_src_h);
13399
13400                 PIPE_CONF_CHECK_I(pch_pfit.enabled);
13401                 if (current_config->pch_pfit.enabled) {
13402                         PIPE_CONF_CHECK_X(pch_pfit.pos);
13403                         PIPE_CONF_CHECK_X(pch_pfit.size);
13404                 }
13405
13406                 PIPE_CONF_CHECK_I(scaler_state.scaler_id);
13407         }
13408
13409         /* BDW+ don't expose a synchronous way to read the state */
13410         if (IS_HASWELL(dev_priv))
13411                 PIPE_CONF_CHECK_I(ips_enabled);
13412
13413         PIPE_CONF_CHECK_I(double_wide);
13414
13415         PIPE_CONF_CHECK_P(shared_dpll);
13416         PIPE_CONF_CHECK_X(dpll_hw_state.dpll);
13417         PIPE_CONF_CHECK_X(dpll_hw_state.dpll_md);
13418         PIPE_CONF_CHECK_X(dpll_hw_state.fp0);
13419         PIPE_CONF_CHECK_X(dpll_hw_state.fp1);
13420         PIPE_CONF_CHECK_X(dpll_hw_state.wrpll);
13421         PIPE_CONF_CHECK_X(dpll_hw_state.spll);
13422         PIPE_CONF_CHECK_X(dpll_hw_state.ctrl1);
13423         PIPE_CONF_CHECK_X(dpll_hw_state.cfgcr1);
13424         PIPE_CONF_CHECK_X(dpll_hw_state.cfgcr2);
13425
13426         PIPE_CONF_CHECK_X(dsi_pll.ctrl);
13427         PIPE_CONF_CHECK_X(dsi_pll.div);
13428
13429         if (IS_G4X(dev_priv) || INTEL_GEN(dev_priv) >= 5)
13430                 PIPE_CONF_CHECK_I(pipe_bpp);
13431
13432         PIPE_CONF_CHECK_CLOCK_FUZZY(base.adjusted_mode.crtc_clock);
13433         PIPE_CONF_CHECK_CLOCK_FUZZY(port_clock);
13434
13435 #undef PIPE_CONF_CHECK_X
13436 #undef PIPE_CONF_CHECK_I
13437 #undef PIPE_CONF_CHECK_P
13438 #undef PIPE_CONF_CHECK_FLAGS
13439 #undef PIPE_CONF_CHECK_CLOCK_FUZZY
13440 #undef PIPE_CONF_QUIRK
13441 #undef INTEL_ERR_OR_DBG_KMS
13442
13443         return ret;
13444 }
13445
13446 static void intel_pipe_config_sanity_check(struct drm_i915_private *dev_priv,
13447                                            const struct intel_crtc_state *pipe_config)
13448 {
13449         if (pipe_config->has_pch_encoder) {
13450                 int fdi_dotclock = intel_dotclock_calculate(intel_fdi_link_freq(dev_priv, pipe_config),
13451                                                             &pipe_config->fdi_m_n);
13452                 int dotclock = pipe_config->base.adjusted_mode.crtc_clock;
13453
13454                 /*
13455                  * FDI already provided one idea for the dotclock.
13456                  * Yell if the encoder disagrees.
13457                  */
13458                 WARN(!intel_fuzzy_clock_check(fdi_dotclock, dotclock),
13459                      "FDI dotclock and encoder dotclock mismatch, fdi: %i, encoder: %i\n",
13460                      fdi_dotclock, dotclock);
13461         }
13462 }
13463
13464 static void verify_wm_state(struct drm_crtc *crtc,
13465                             struct drm_crtc_state *new_state)
13466 {
13467         struct drm_device *dev = crtc->dev;
13468         struct drm_i915_private *dev_priv = to_i915(dev);
13469         struct skl_ddb_allocation hw_ddb, *sw_ddb;
13470         struct skl_pipe_wm hw_wm, *sw_wm;
13471         struct skl_plane_wm *hw_plane_wm, *sw_plane_wm;
13472         struct skl_ddb_entry *hw_ddb_entry, *sw_ddb_entry;
13473         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
13474         const enum pipe pipe = intel_crtc->pipe;
13475         int plane, level, max_level = ilk_wm_max_level(dev_priv);
13476
13477         if (INTEL_INFO(dev)->gen < 9 || !new_state->active)
13478                 return;
13479
13480         skl_pipe_wm_get_hw_state(crtc, &hw_wm);
13481         sw_wm = &intel_crtc->wm.active.skl;
13482
13483         skl_ddb_get_hw_state(dev_priv, &hw_ddb);
13484         sw_ddb = &dev_priv->wm.skl_hw.ddb;
13485
13486         /* planes */
13487         for_each_plane(dev_priv, pipe, plane) {
13488                 hw_plane_wm = &hw_wm.planes[plane];
13489                 sw_plane_wm = &sw_wm->planes[plane];
13490
13491                 /* Watermarks */
13492                 for (level = 0; level <= max_level; level++) {
13493                         if (skl_wm_level_equals(&hw_plane_wm->wm[level],
13494                                                 &sw_plane_wm->wm[level]))
13495                                 continue;
13496
13497                         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",
13498                                   pipe_name(pipe), plane + 1, level,
13499                                   sw_plane_wm->wm[level].plane_en,
13500                                   sw_plane_wm->wm[level].plane_res_b,
13501                                   sw_plane_wm->wm[level].plane_res_l,
13502                                   hw_plane_wm->wm[level].plane_en,
13503                                   hw_plane_wm->wm[level].plane_res_b,
13504                                   hw_plane_wm->wm[level].plane_res_l);
13505                 }
13506
13507                 if (!skl_wm_level_equals(&hw_plane_wm->trans_wm,
13508                                          &sw_plane_wm->trans_wm)) {
13509                         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",
13510                                   pipe_name(pipe), plane + 1,
13511                                   sw_plane_wm->trans_wm.plane_en,
13512                                   sw_plane_wm->trans_wm.plane_res_b,
13513                                   sw_plane_wm->trans_wm.plane_res_l,
13514                                   hw_plane_wm->trans_wm.plane_en,
13515                                   hw_plane_wm->trans_wm.plane_res_b,
13516                                   hw_plane_wm->trans_wm.plane_res_l);
13517                 }
13518
13519                 /* DDB */
13520                 hw_ddb_entry = &hw_ddb.plane[pipe][plane];
13521                 sw_ddb_entry = &sw_ddb->plane[pipe][plane];
13522
13523                 if (!skl_ddb_entry_equal(hw_ddb_entry, sw_ddb_entry)) {
13524                         DRM_ERROR("mismatch in DDB state pipe %c plane %d (expected (%u,%u), found (%u,%u))\n",
13525                                   pipe_name(pipe), plane + 1,
13526                                   sw_ddb_entry->start, sw_ddb_entry->end,
13527                                   hw_ddb_entry->start, hw_ddb_entry->end);
13528                 }
13529         }
13530
13531         /*
13532          * cursor
13533          * If the cursor plane isn't active, we may not have updated it's ddb
13534          * allocation. In that case since the ddb allocation will be updated
13535          * once the plane becomes visible, we can skip this check
13536          */
13537         if (intel_crtc->cursor_addr) {
13538                 hw_plane_wm = &hw_wm.planes[PLANE_CURSOR];
13539                 sw_plane_wm = &sw_wm->planes[PLANE_CURSOR];
13540
13541                 /* Watermarks */
13542                 for (level = 0; level <= max_level; level++) {
13543                         if (skl_wm_level_equals(&hw_plane_wm->wm[level],
13544                                                 &sw_plane_wm->wm[level]))
13545                                 continue;
13546
13547                         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",
13548                                   pipe_name(pipe), level,
13549                                   sw_plane_wm->wm[level].plane_en,
13550                                   sw_plane_wm->wm[level].plane_res_b,
13551                                   sw_plane_wm->wm[level].plane_res_l,
13552                                   hw_plane_wm->wm[level].plane_en,
13553                                   hw_plane_wm->wm[level].plane_res_b,
13554                                   hw_plane_wm->wm[level].plane_res_l);
13555                 }
13556
13557                 if (!skl_wm_level_equals(&hw_plane_wm->trans_wm,
13558                                          &sw_plane_wm->trans_wm)) {
13559                         DRM_ERROR("mismatch in trans WM pipe %c cursor (expected e=%d b=%u l=%u, got e=%d b=%u l=%u)\n",
13560                                   pipe_name(pipe),
13561                                   sw_plane_wm->trans_wm.plane_en,
13562                                   sw_plane_wm->trans_wm.plane_res_b,
13563                                   sw_plane_wm->trans_wm.plane_res_l,
13564                                   hw_plane_wm->trans_wm.plane_en,
13565                                   hw_plane_wm->trans_wm.plane_res_b,
13566                                   hw_plane_wm->trans_wm.plane_res_l);
13567                 }
13568
13569                 /* DDB */
13570                 hw_ddb_entry = &hw_ddb.plane[pipe][PLANE_CURSOR];
13571                 sw_ddb_entry = &sw_ddb->plane[pipe][PLANE_CURSOR];
13572
13573                 if (!skl_ddb_entry_equal(hw_ddb_entry, sw_ddb_entry)) {
13574                         DRM_ERROR("mismatch in DDB state pipe %c cursor (expected (%u,%u), found (%u,%u))\n",
13575                                   pipe_name(pipe),
13576                                   sw_ddb_entry->start, sw_ddb_entry->end,
13577                                   hw_ddb_entry->start, hw_ddb_entry->end);
13578                 }
13579         }
13580 }
13581
13582 static void
13583 verify_connector_state(struct drm_device *dev, struct drm_crtc *crtc)
13584 {
13585         struct drm_connector *connector;
13586
13587         drm_for_each_connector(connector, dev) {
13588                 struct drm_encoder *encoder = connector->encoder;
13589                 struct drm_connector_state *state = connector->state;
13590
13591                 if (state->crtc != crtc)
13592                         continue;
13593
13594                 intel_connector_verify_state(to_intel_connector(connector));
13595
13596                 I915_STATE_WARN(state->best_encoder != encoder,
13597                      "connector's atomic encoder doesn't match legacy encoder\n");
13598         }
13599 }
13600
13601 static void
13602 verify_encoder_state(struct drm_device *dev)
13603 {
13604         struct intel_encoder *encoder;
13605         struct intel_connector *connector;
13606
13607         for_each_intel_encoder(dev, encoder) {
13608                 bool enabled = false;
13609                 enum pipe pipe;
13610
13611                 DRM_DEBUG_KMS("[ENCODER:%d:%s]\n",
13612                               encoder->base.base.id,
13613                               encoder->base.name);
13614
13615                 for_each_intel_connector(dev, connector) {
13616                         if (connector->base.state->best_encoder != &encoder->base)
13617                                 continue;
13618                         enabled = true;
13619
13620                         I915_STATE_WARN(connector->base.state->crtc !=
13621                                         encoder->base.crtc,
13622                              "connector's crtc doesn't match encoder crtc\n");
13623                 }
13624
13625                 I915_STATE_WARN(!!encoder->base.crtc != enabled,
13626                      "encoder's enabled state mismatch "
13627                      "(expected %i, found %i)\n",
13628                      !!encoder->base.crtc, enabled);
13629
13630                 if (!encoder->base.crtc) {
13631                         bool active;
13632
13633                         active = encoder->get_hw_state(encoder, &pipe);
13634                         I915_STATE_WARN(active,
13635                              "encoder detached but still enabled on pipe %c.\n",
13636                              pipe_name(pipe));
13637                 }
13638         }
13639 }
13640
13641 static void
13642 verify_crtc_state(struct drm_crtc *crtc,
13643                   struct drm_crtc_state *old_crtc_state,
13644                   struct drm_crtc_state *new_crtc_state)
13645 {
13646         struct drm_device *dev = crtc->dev;
13647         struct drm_i915_private *dev_priv = to_i915(dev);
13648         struct intel_encoder *encoder;
13649         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
13650         struct intel_crtc_state *pipe_config, *sw_config;
13651         struct drm_atomic_state *old_state;
13652         bool active;
13653
13654         old_state = old_crtc_state->state;
13655         __drm_atomic_helper_crtc_destroy_state(old_crtc_state);
13656         pipe_config = to_intel_crtc_state(old_crtc_state);
13657         memset(pipe_config, 0, sizeof(*pipe_config));
13658         pipe_config->base.crtc = crtc;
13659         pipe_config->base.state = old_state;
13660
13661         DRM_DEBUG_KMS("[CRTC:%d:%s]\n", crtc->base.id, crtc->name);
13662
13663         active = dev_priv->display.get_pipe_config(intel_crtc, pipe_config);
13664
13665         /* hw state is inconsistent with the pipe quirk */
13666         if ((intel_crtc->pipe == PIPE_A && dev_priv->quirks & QUIRK_PIPEA_FORCE) ||
13667             (intel_crtc->pipe == PIPE_B && dev_priv->quirks & QUIRK_PIPEB_FORCE))
13668                 active = new_crtc_state->active;
13669
13670         I915_STATE_WARN(new_crtc_state->active != active,
13671              "crtc active state doesn't match with hw state "
13672              "(expected %i, found %i)\n", new_crtc_state->active, active);
13673
13674         I915_STATE_WARN(intel_crtc->active != new_crtc_state->active,
13675              "transitional active state does not match atomic hw state "
13676              "(expected %i, found %i)\n", new_crtc_state->active, intel_crtc->active);
13677
13678         for_each_encoder_on_crtc(dev, crtc, encoder) {
13679                 enum pipe pipe;
13680
13681                 active = encoder->get_hw_state(encoder, &pipe);
13682                 I915_STATE_WARN(active != new_crtc_state->active,
13683                         "[ENCODER:%i] active %i with crtc active %i\n",
13684                         encoder->base.base.id, active, new_crtc_state->active);
13685
13686                 I915_STATE_WARN(active && intel_crtc->pipe != pipe,
13687                                 "Encoder connected to wrong pipe %c\n",
13688                                 pipe_name(pipe));
13689
13690                 if (active) {
13691                         pipe_config->output_types |= 1 << encoder->type;
13692                         encoder->get_config(encoder, pipe_config);
13693                 }
13694         }
13695
13696         if (!new_crtc_state->active)
13697                 return;
13698
13699         intel_pipe_config_sanity_check(dev_priv, pipe_config);
13700
13701         sw_config = to_intel_crtc_state(crtc->state);
13702         if (!intel_pipe_config_compare(dev, sw_config,
13703                                        pipe_config, false)) {
13704                 I915_STATE_WARN(1, "pipe state doesn't match!\n");
13705                 intel_dump_pipe_config(intel_crtc, pipe_config,
13706                                        "[hw state]");
13707                 intel_dump_pipe_config(intel_crtc, sw_config,
13708                                        "[sw state]");
13709         }
13710 }
13711
13712 static void
13713 verify_single_dpll_state(struct drm_i915_private *dev_priv,
13714                          struct intel_shared_dpll *pll,
13715                          struct drm_crtc *crtc,
13716                          struct drm_crtc_state *new_state)
13717 {
13718         struct intel_dpll_hw_state dpll_hw_state;
13719         unsigned crtc_mask;
13720         bool active;
13721
13722         memset(&dpll_hw_state, 0, sizeof(dpll_hw_state));
13723
13724         DRM_DEBUG_KMS("%s\n", pll->name);
13725
13726         active = pll->funcs.get_hw_state(dev_priv, pll, &dpll_hw_state);
13727
13728         if (!(pll->flags & INTEL_DPLL_ALWAYS_ON)) {
13729                 I915_STATE_WARN(!pll->on && pll->active_mask,
13730                      "pll in active use but not on in sw tracking\n");
13731                 I915_STATE_WARN(pll->on && !pll->active_mask,
13732                      "pll is on but not used by any active crtc\n");
13733                 I915_STATE_WARN(pll->on != active,
13734                      "pll on state mismatch (expected %i, found %i)\n",
13735                      pll->on, active);
13736         }
13737
13738         if (!crtc) {
13739                 I915_STATE_WARN(pll->active_mask & ~pll->config.crtc_mask,
13740                                 "more active pll users than references: %x vs %x\n",
13741                                 pll->active_mask, pll->config.crtc_mask);
13742
13743                 return;
13744         }
13745
13746         crtc_mask = 1 << drm_crtc_index(crtc);
13747
13748         if (new_state->active)
13749                 I915_STATE_WARN(!(pll->active_mask & crtc_mask),
13750                                 "pll active mismatch (expected pipe %c in active mask 0x%02x)\n",
13751                                 pipe_name(drm_crtc_index(crtc)), pll->active_mask);
13752         else
13753                 I915_STATE_WARN(pll->active_mask & crtc_mask,
13754                                 "pll active mismatch (didn't expect pipe %c in active mask 0x%02x)\n",
13755                                 pipe_name(drm_crtc_index(crtc)), pll->active_mask);
13756
13757         I915_STATE_WARN(!(pll->config.crtc_mask & crtc_mask),
13758                         "pll enabled crtcs mismatch (expected 0x%x in 0x%02x)\n",
13759                         crtc_mask, pll->config.crtc_mask);
13760
13761         I915_STATE_WARN(pll->on && memcmp(&pll->config.hw_state,
13762                                           &dpll_hw_state,
13763                                           sizeof(dpll_hw_state)),
13764                         "pll hw state mismatch\n");
13765 }
13766
13767 static void
13768 verify_shared_dpll_state(struct drm_device *dev, struct drm_crtc *crtc,
13769                          struct drm_crtc_state *old_crtc_state,
13770                          struct drm_crtc_state *new_crtc_state)
13771 {
13772         struct drm_i915_private *dev_priv = to_i915(dev);
13773         struct intel_crtc_state *old_state = to_intel_crtc_state(old_crtc_state);
13774         struct intel_crtc_state *new_state = to_intel_crtc_state(new_crtc_state);
13775
13776         if (new_state->shared_dpll)
13777                 verify_single_dpll_state(dev_priv, new_state->shared_dpll, crtc, new_crtc_state);
13778
13779         if (old_state->shared_dpll &&
13780             old_state->shared_dpll != new_state->shared_dpll) {
13781                 unsigned crtc_mask = 1 << drm_crtc_index(crtc);
13782                 struct intel_shared_dpll *pll = old_state->shared_dpll;
13783
13784                 I915_STATE_WARN(pll->active_mask & crtc_mask,
13785                                 "pll active mismatch (didn't expect pipe %c in active mask)\n",
13786                                 pipe_name(drm_crtc_index(crtc)));
13787                 I915_STATE_WARN(pll->config.crtc_mask & crtc_mask,
13788                                 "pll enabled crtcs mismatch (found %x in enabled mask)\n",
13789                                 pipe_name(drm_crtc_index(crtc)));
13790         }
13791 }
13792
13793 static void
13794 intel_modeset_verify_crtc(struct drm_crtc *crtc,
13795                          struct drm_crtc_state *old_state,
13796                          struct drm_crtc_state *new_state)
13797 {
13798         if (!needs_modeset(new_state) &&
13799             !to_intel_crtc_state(new_state)->update_pipe)
13800                 return;
13801
13802         verify_wm_state(crtc, new_state);
13803         verify_connector_state(crtc->dev, crtc);
13804         verify_crtc_state(crtc, old_state, new_state);
13805         verify_shared_dpll_state(crtc->dev, crtc, old_state, new_state);
13806 }
13807
13808 static void
13809 verify_disabled_dpll_state(struct drm_device *dev)
13810 {
13811         struct drm_i915_private *dev_priv = to_i915(dev);
13812         int i;
13813
13814         for (i = 0; i < dev_priv->num_shared_dpll; i++)
13815                 verify_single_dpll_state(dev_priv, &dev_priv->shared_dplls[i], NULL, NULL);
13816 }
13817
13818 static void
13819 intel_modeset_verify_disabled(struct drm_device *dev)
13820 {
13821         verify_encoder_state(dev);
13822         verify_connector_state(dev, NULL);
13823         verify_disabled_dpll_state(dev);
13824 }
13825
13826 static void update_scanline_offset(struct intel_crtc *crtc)
13827 {
13828         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
13829
13830         /*
13831          * The scanline counter increments at the leading edge of hsync.
13832          *
13833          * On most platforms it starts counting from vtotal-1 on the
13834          * first active line. That means the scanline counter value is
13835          * always one less than what we would expect. Ie. just after
13836          * start of vblank, which also occurs at start of hsync (on the
13837          * last active line), the scanline counter will read vblank_start-1.
13838          *
13839          * On gen2 the scanline counter starts counting from 1 instead
13840          * of vtotal-1, so we have to subtract one (or rather add vtotal-1
13841          * to keep the value positive), instead of adding one.
13842          *
13843          * On HSW+ the behaviour of the scanline counter depends on the output
13844          * type. For DP ports it behaves like most other platforms, but on HDMI
13845          * there's an extra 1 line difference. So we need to add two instead of
13846          * one to the value.
13847          */
13848         if (IS_GEN2(dev_priv)) {
13849                 const struct drm_display_mode *adjusted_mode = &crtc->config->base.adjusted_mode;
13850                 int vtotal;
13851
13852                 vtotal = adjusted_mode->crtc_vtotal;
13853                 if (adjusted_mode->flags & DRM_MODE_FLAG_INTERLACE)
13854                         vtotal /= 2;
13855
13856                 crtc->scanline_offset = vtotal - 1;
13857         } else if (HAS_DDI(dev_priv) &&
13858                    intel_crtc_has_type(crtc->config, INTEL_OUTPUT_HDMI)) {
13859                 crtc->scanline_offset = 2;
13860         } else
13861                 crtc->scanline_offset = 1;
13862 }
13863
13864 static void intel_modeset_clear_plls(struct drm_atomic_state *state)
13865 {
13866         struct drm_device *dev = state->dev;
13867         struct drm_i915_private *dev_priv = to_i915(dev);
13868         struct intel_shared_dpll_config *shared_dpll = NULL;
13869         struct drm_crtc *crtc;
13870         struct drm_crtc_state *crtc_state;
13871         int i;
13872
13873         if (!dev_priv->display.crtc_compute_clock)
13874                 return;
13875
13876         for_each_crtc_in_state(state, crtc, crtc_state, i) {
13877                 struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
13878                 struct intel_shared_dpll *old_dpll =
13879                         to_intel_crtc_state(crtc->state)->shared_dpll;
13880
13881                 if (!needs_modeset(crtc_state))
13882                         continue;
13883
13884                 to_intel_crtc_state(crtc_state)->shared_dpll = NULL;
13885
13886                 if (!old_dpll)
13887                         continue;
13888
13889                 if (!shared_dpll)
13890                         shared_dpll = intel_atomic_get_shared_dpll_state(state);
13891
13892                 intel_shared_dpll_config_put(shared_dpll, old_dpll, intel_crtc);
13893         }
13894 }
13895
13896 /*
13897  * This implements the workaround described in the "notes" section of the mode
13898  * set sequence documentation. When going from no pipes or single pipe to
13899  * multiple pipes, and planes are enabled after the pipe, we need to wait at
13900  * least 2 vblanks on the first pipe before enabling planes on the second pipe.
13901  */
13902 static int haswell_mode_set_planes_workaround(struct drm_atomic_state *state)
13903 {
13904         struct drm_crtc_state *crtc_state;
13905         struct intel_crtc *intel_crtc;
13906         struct drm_crtc *crtc;
13907         struct intel_crtc_state *first_crtc_state = NULL;
13908         struct intel_crtc_state *other_crtc_state = NULL;
13909         enum pipe first_pipe = INVALID_PIPE, enabled_pipe = INVALID_PIPE;
13910         int i;
13911
13912         /* look at all crtc's that are going to be enabled in during modeset */
13913         for_each_crtc_in_state(state, crtc, crtc_state, i) {
13914                 intel_crtc = to_intel_crtc(crtc);
13915
13916                 if (!crtc_state->active || !needs_modeset(crtc_state))
13917                         continue;
13918
13919                 if (first_crtc_state) {
13920                         other_crtc_state = to_intel_crtc_state(crtc_state);
13921                         break;
13922                 } else {
13923                         first_crtc_state = to_intel_crtc_state(crtc_state);
13924                         first_pipe = intel_crtc->pipe;
13925                 }
13926         }
13927
13928         /* No workaround needed? */
13929         if (!first_crtc_state)
13930                 return 0;
13931
13932         /* w/a possibly needed, check how many crtc's are already enabled. */
13933         for_each_intel_crtc(state->dev, intel_crtc) {
13934                 struct intel_crtc_state *pipe_config;
13935
13936                 pipe_config = intel_atomic_get_crtc_state(state, intel_crtc);
13937                 if (IS_ERR(pipe_config))
13938                         return PTR_ERR(pipe_config);
13939
13940                 pipe_config->hsw_workaround_pipe = INVALID_PIPE;
13941
13942                 if (!pipe_config->base.active ||
13943                     needs_modeset(&pipe_config->base))
13944                         continue;
13945
13946                 /* 2 or more enabled crtcs means no need for w/a */
13947                 if (enabled_pipe != INVALID_PIPE)
13948                         return 0;
13949
13950                 enabled_pipe = intel_crtc->pipe;
13951         }
13952
13953         if (enabled_pipe != INVALID_PIPE)
13954                 first_crtc_state->hsw_workaround_pipe = enabled_pipe;
13955         else if (other_crtc_state)
13956                 other_crtc_state->hsw_workaround_pipe = first_pipe;
13957
13958         return 0;
13959 }
13960
13961 static int intel_modeset_all_pipes(struct drm_atomic_state *state)
13962 {
13963         struct drm_crtc *crtc;
13964         struct drm_crtc_state *crtc_state;
13965         int ret = 0;
13966
13967         /* add all active pipes to the state */
13968         for_each_crtc(state->dev, crtc) {
13969                 crtc_state = drm_atomic_get_crtc_state(state, crtc);
13970                 if (IS_ERR(crtc_state))
13971                         return PTR_ERR(crtc_state);
13972
13973                 if (!crtc_state->active || needs_modeset(crtc_state))
13974                         continue;
13975
13976                 crtc_state->mode_changed = true;
13977
13978                 ret = drm_atomic_add_affected_connectors(state, crtc);
13979                 if (ret)
13980                         break;
13981
13982                 ret = drm_atomic_add_affected_planes(state, crtc);
13983                 if (ret)
13984                         break;
13985         }
13986
13987         return ret;
13988 }
13989
13990 static int intel_modeset_checks(struct drm_atomic_state *state)
13991 {
13992         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
13993         struct drm_i915_private *dev_priv = to_i915(state->dev);
13994         struct drm_crtc *crtc;
13995         struct drm_crtc_state *crtc_state;
13996         int ret = 0, i;
13997
13998         if (!check_digital_port_conflicts(state)) {
13999                 DRM_DEBUG_KMS("rejecting conflicting digital port configuration\n");
14000                 return -EINVAL;
14001         }
14002
14003         intel_state->modeset = true;
14004         intel_state->active_crtcs = dev_priv->active_crtcs;
14005
14006         for_each_crtc_in_state(state, crtc, crtc_state, i) {
14007                 if (crtc_state->active)
14008                         intel_state->active_crtcs |= 1 << i;
14009                 else
14010                         intel_state->active_crtcs &= ~(1 << i);
14011
14012                 if (crtc_state->active != crtc->state->active)
14013                         intel_state->active_pipe_changes |= drm_crtc_mask(crtc);
14014         }
14015
14016         /*
14017          * See if the config requires any additional preparation, e.g.
14018          * to adjust global state with pipes off.  We need to do this
14019          * here so we can get the modeset_pipe updated config for the new
14020          * mode set on this crtc.  For other crtcs we need to use the
14021          * adjusted_mode bits in the crtc directly.
14022          */
14023         if (dev_priv->display.modeset_calc_cdclk) {
14024                 if (!intel_state->cdclk_pll_vco)
14025                         intel_state->cdclk_pll_vco = dev_priv->cdclk_pll.vco;
14026                 if (!intel_state->cdclk_pll_vco)
14027                         intel_state->cdclk_pll_vco = dev_priv->skl_preferred_vco_freq;
14028
14029                 ret = dev_priv->display.modeset_calc_cdclk(state);
14030                 if (ret < 0)
14031                         return ret;
14032
14033                 if (intel_state->dev_cdclk != dev_priv->cdclk_freq ||
14034                     intel_state->cdclk_pll_vco != dev_priv->cdclk_pll.vco)
14035                         ret = intel_modeset_all_pipes(state);
14036
14037                 if (ret < 0)
14038                         return ret;
14039
14040                 DRM_DEBUG_KMS("New cdclk calculated to be atomic %u, actual %u\n",
14041                               intel_state->cdclk, intel_state->dev_cdclk);
14042         } else
14043                 to_intel_atomic_state(state)->cdclk = dev_priv->atomic_cdclk_freq;
14044
14045         intel_modeset_clear_plls(state);
14046
14047         if (IS_HASWELL(dev_priv))
14048                 return haswell_mode_set_planes_workaround(state);
14049
14050         return 0;
14051 }
14052
14053 /*
14054  * Handle calculation of various watermark data at the end of the atomic check
14055  * phase.  The code here should be run after the per-crtc and per-plane 'check'
14056  * handlers to ensure that all derived state has been updated.
14057  */
14058 static int calc_watermark_data(struct drm_atomic_state *state)
14059 {
14060         struct drm_device *dev = state->dev;
14061         struct drm_i915_private *dev_priv = to_i915(dev);
14062
14063         /* Is there platform-specific watermark information to calculate? */
14064         if (dev_priv->display.compute_global_watermarks)
14065                 return dev_priv->display.compute_global_watermarks(state);
14066
14067         return 0;
14068 }
14069
14070 /**
14071  * intel_atomic_check - validate state object
14072  * @dev: drm device
14073  * @state: state to validate
14074  */
14075 static int intel_atomic_check(struct drm_device *dev,
14076                               struct drm_atomic_state *state)
14077 {
14078         struct drm_i915_private *dev_priv = to_i915(dev);
14079         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
14080         struct drm_crtc *crtc;
14081         struct drm_crtc_state *crtc_state;
14082         int ret, i;
14083         bool any_ms = false;
14084
14085         ret = drm_atomic_helper_check_modeset(dev, state);
14086         if (ret)
14087                 return ret;
14088
14089         for_each_crtc_in_state(state, crtc, crtc_state, i) {
14090                 struct intel_crtc_state *pipe_config =
14091                         to_intel_crtc_state(crtc_state);
14092
14093                 /* Catch I915_MODE_FLAG_INHERITED */
14094                 if (crtc_state->mode.private_flags != crtc->state->mode.private_flags)
14095                         crtc_state->mode_changed = true;
14096
14097                 if (!needs_modeset(crtc_state))
14098                         continue;
14099
14100                 if (!crtc_state->enable) {
14101                         any_ms = true;
14102                         continue;
14103                 }
14104
14105                 /* FIXME: For only active_changed we shouldn't need to do any
14106                  * state recomputation at all. */
14107
14108                 ret = drm_atomic_add_affected_connectors(state, crtc);
14109                 if (ret)
14110                         return ret;
14111
14112                 ret = intel_modeset_pipe_config(crtc, pipe_config);
14113                 if (ret) {
14114                         intel_dump_pipe_config(to_intel_crtc(crtc),
14115                                                pipe_config, "[failed]");
14116                         return ret;
14117                 }
14118
14119                 if (i915.fastboot &&
14120                     intel_pipe_config_compare(dev,
14121                                         to_intel_crtc_state(crtc->state),
14122                                         pipe_config, true)) {
14123                         crtc_state->mode_changed = false;
14124                         to_intel_crtc_state(crtc_state)->update_pipe = true;
14125                 }
14126
14127                 if (needs_modeset(crtc_state))
14128                         any_ms = true;
14129
14130                 ret = drm_atomic_add_affected_planes(state, crtc);
14131                 if (ret)
14132                         return ret;
14133
14134                 intel_dump_pipe_config(to_intel_crtc(crtc), pipe_config,
14135                                        needs_modeset(crtc_state) ?
14136                                        "[modeset]" : "[fastset]");
14137         }
14138
14139         if (any_ms) {
14140                 ret = intel_modeset_checks(state);
14141
14142                 if (ret)
14143                         return ret;
14144         } else
14145                 intel_state->cdclk = dev_priv->cdclk_freq;
14146
14147         ret = drm_atomic_helper_check_planes(dev, state);
14148         if (ret)
14149                 return ret;
14150
14151         intel_fbc_choose_crtc(dev_priv, state);
14152         return calc_watermark_data(state);
14153 }
14154
14155 static int intel_atomic_prepare_commit(struct drm_device *dev,
14156                                        struct drm_atomic_state *state,
14157                                        bool nonblock)
14158 {
14159         struct drm_i915_private *dev_priv = to_i915(dev);
14160         struct drm_plane_state *plane_state;
14161         struct drm_crtc_state *crtc_state;
14162         struct drm_plane *plane;
14163         struct drm_crtc *crtc;
14164         int i, ret;
14165
14166         for_each_crtc_in_state(state, crtc, crtc_state, i) {
14167                 if (state->legacy_cursor_update)
14168                         continue;
14169
14170                 ret = intel_crtc_wait_for_pending_flips(crtc);
14171                 if (ret)
14172                         return ret;
14173
14174                 if (atomic_read(&to_intel_crtc(crtc)->unpin_work_count) >= 2)
14175                         flush_workqueue(dev_priv->wq);
14176         }
14177
14178         ret = mutex_lock_interruptible(&dev->struct_mutex);
14179         if (ret)
14180                 return ret;
14181
14182         ret = drm_atomic_helper_prepare_planes(dev, state);
14183         mutex_unlock(&dev->struct_mutex);
14184
14185         if (!ret && !nonblock) {
14186                 for_each_plane_in_state(state, plane, plane_state, i) {
14187                         struct intel_plane_state *intel_plane_state =
14188                                 to_intel_plane_state(plane_state);
14189
14190                         if (!intel_plane_state->wait_req)
14191                                 continue;
14192
14193                         ret = i915_wait_request(intel_plane_state->wait_req,
14194                                                 I915_WAIT_INTERRUPTIBLE,
14195                                                 NULL, NULL);
14196                         if (ret) {
14197                                 /* Any hang should be swallowed by the wait */
14198                                 WARN_ON(ret == -EIO);
14199                                 mutex_lock(&dev->struct_mutex);
14200                                 drm_atomic_helper_cleanup_planes(dev, state);
14201                                 mutex_unlock(&dev->struct_mutex);
14202                                 break;
14203                         }
14204                 }
14205         }
14206
14207         return ret;
14208 }
14209
14210 u32 intel_crtc_get_vblank_counter(struct intel_crtc *crtc)
14211 {
14212         struct drm_device *dev = crtc->base.dev;
14213
14214         if (!dev->max_vblank_count)
14215                 return drm_accurate_vblank_count(&crtc->base);
14216
14217         return dev->driver->get_vblank_counter(dev, crtc->pipe);
14218 }
14219
14220 static void intel_atomic_wait_for_vblanks(struct drm_device *dev,
14221                                           struct drm_i915_private *dev_priv,
14222                                           unsigned crtc_mask)
14223 {
14224         unsigned last_vblank_count[I915_MAX_PIPES];
14225         enum pipe pipe;
14226         int ret;
14227
14228         if (!crtc_mask)
14229                 return;
14230
14231         for_each_pipe(dev_priv, pipe) {
14232                 struct drm_crtc *crtc = dev_priv->pipe_to_crtc_mapping[pipe];
14233
14234                 if (!((1 << pipe) & crtc_mask))
14235                         continue;
14236
14237                 ret = drm_crtc_vblank_get(crtc);
14238                 if (WARN_ON(ret != 0)) {
14239                         crtc_mask &= ~(1 << pipe);
14240                         continue;
14241                 }
14242
14243                 last_vblank_count[pipe] = drm_crtc_vblank_count(crtc);
14244         }
14245
14246         for_each_pipe(dev_priv, pipe) {
14247                 struct drm_crtc *crtc = dev_priv->pipe_to_crtc_mapping[pipe];
14248                 long lret;
14249
14250                 if (!((1 << pipe) & crtc_mask))
14251                         continue;
14252
14253                 lret = wait_event_timeout(dev->vblank[pipe].queue,
14254                                 last_vblank_count[pipe] !=
14255                                         drm_crtc_vblank_count(crtc),
14256                                 msecs_to_jiffies(50));
14257
14258                 WARN(!lret, "pipe %c vblank wait timed out\n", pipe_name(pipe));
14259
14260                 drm_crtc_vblank_put(crtc);
14261         }
14262 }
14263
14264 static bool needs_vblank_wait(struct intel_crtc_state *crtc_state)
14265 {
14266         /* fb updated, need to unpin old fb */
14267         if (crtc_state->fb_changed)
14268                 return true;
14269
14270         /* wm changes, need vblank before final wm's */
14271         if (crtc_state->update_wm_post)
14272                 return true;
14273
14274         /*
14275          * cxsr is re-enabled after vblank.
14276          * This is already handled by crtc_state->update_wm_post,
14277          * but added for clarity.
14278          */
14279         if (crtc_state->disable_cxsr)
14280                 return true;
14281
14282         return false;
14283 }
14284
14285 static void intel_update_crtc(struct drm_crtc *crtc,
14286                               struct drm_atomic_state *state,
14287                               struct drm_crtc_state *old_crtc_state,
14288                               unsigned int *crtc_vblank_mask)
14289 {
14290         struct drm_device *dev = crtc->dev;
14291         struct drm_i915_private *dev_priv = to_i915(dev);
14292         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
14293         struct intel_crtc_state *pipe_config = to_intel_crtc_state(crtc->state);
14294         bool modeset = needs_modeset(crtc->state);
14295
14296         if (modeset) {
14297                 update_scanline_offset(intel_crtc);
14298                 dev_priv->display.crtc_enable(pipe_config, state);
14299         } else {
14300                 intel_pre_plane_update(to_intel_crtc_state(old_crtc_state));
14301         }
14302
14303         if (drm_atomic_get_existing_plane_state(state, crtc->primary)) {
14304                 intel_fbc_enable(
14305                     intel_crtc, pipe_config,
14306                     to_intel_plane_state(crtc->primary->state));
14307         }
14308
14309         drm_atomic_helper_commit_planes_on_crtc(old_crtc_state);
14310
14311         if (needs_vblank_wait(pipe_config))
14312                 *crtc_vblank_mask |= drm_crtc_mask(crtc);
14313 }
14314
14315 static void intel_update_crtcs(struct drm_atomic_state *state,
14316                                unsigned int *crtc_vblank_mask)
14317 {
14318         struct drm_crtc *crtc;
14319         struct drm_crtc_state *old_crtc_state;
14320         int i;
14321
14322         for_each_crtc_in_state(state, crtc, old_crtc_state, i) {
14323                 if (!crtc->state->active)
14324                         continue;
14325
14326                 intel_update_crtc(crtc, state, old_crtc_state,
14327                                   crtc_vblank_mask);
14328         }
14329 }
14330
14331 static void skl_update_crtcs(struct drm_atomic_state *state,
14332                              unsigned int *crtc_vblank_mask)
14333 {
14334         struct drm_device *dev = state->dev;
14335         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
14336         struct drm_crtc *crtc;
14337         struct intel_crtc *intel_crtc;
14338         struct drm_crtc_state *old_crtc_state;
14339         struct intel_crtc_state *cstate;
14340         unsigned int updated = 0;
14341         bool progress;
14342         enum pipe pipe;
14343
14344         /*
14345          * Whenever the number of active pipes changes, we need to make sure we
14346          * update the pipes in the right order so that their ddb allocations
14347          * never overlap with eachother inbetween CRTC updates. Otherwise we'll
14348          * cause pipe underruns and other bad stuff.
14349          */
14350         do {
14351                 int i;
14352                 progress = false;
14353
14354                 for_each_crtc_in_state(state, crtc, old_crtc_state, i) {
14355                         bool vbl_wait = false;
14356                         unsigned int cmask = drm_crtc_mask(crtc);
14357
14358                         intel_crtc = to_intel_crtc(crtc);
14359                         cstate = to_intel_crtc_state(crtc->state);
14360                         pipe = intel_crtc->pipe;
14361
14362                         if (updated & cmask || !crtc->state->active)
14363                                 continue;
14364                         if (skl_ddb_allocation_overlaps(state, intel_crtc))
14365                                 continue;
14366
14367                         updated |= cmask;
14368
14369                         /*
14370                          * If this is an already active pipe, it's DDB changed,
14371                          * and this isn't the last pipe that needs updating
14372                          * then we need to wait for a vblank to pass for the
14373                          * new ddb allocation to take effect.
14374                          */
14375                         if (!skl_ddb_entry_equal(&cstate->wm.skl.ddb,
14376                                                  &intel_crtc->hw_ddb) &&
14377                             !crtc->state->active_changed &&
14378                             intel_state->wm_results.dirty_pipes != updated)
14379                                 vbl_wait = true;
14380
14381                         intel_update_crtc(crtc, state, old_crtc_state,
14382                                           crtc_vblank_mask);
14383
14384                         if (vbl_wait)
14385                                 intel_wait_for_vblank(dev, pipe);
14386
14387                         progress = true;
14388                 }
14389         } while (progress);
14390 }
14391
14392 static void intel_atomic_commit_tail(struct drm_atomic_state *state)
14393 {
14394         struct drm_device *dev = state->dev;
14395         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
14396         struct drm_i915_private *dev_priv = to_i915(dev);
14397         struct drm_crtc_state *old_crtc_state;
14398         struct drm_crtc *crtc;
14399         struct intel_crtc_state *intel_cstate;
14400         struct drm_plane *plane;
14401         struct drm_plane_state *plane_state;
14402         bool hw_check = intel_state->modeset;
14403         unsigned long put_domains[I915_MAX_PIPES] = {};
14404         unsigned crtc_vblank_mask = 0;
14405         int i, ret;
14406
14407         for_each_plane_in_state(state, plane, plane_state, i) {
14408                 struct intel_plane_state *intel_plane_state =
14409                         to_intel_plane_state(plane_state);
14410
14411                 if (!intel_plane_state->wait_req)
14412                         continue;
14413
14414                 ret = i915_wait_request(intel_plane_state->wait_req,
14415                                         0, NULL, NULL);
14416                 /* EIO should be eaten, and we can't get interrupted in the
14417                  * worker, and blocking commits have waited already. */
14418                 WARN_ON(ret);
14419         }
14420
14421         drm_atomic_helper_wait_for_dependencies(state);
14422
14423         if (intel_state->modeset) {
14424                 memcpy(dev_priv->min_pixclk, intel_state->min_pixclk,
14425                        sizeof(intel_state->min_pixclk));
14426                 dev_priv->active_crtcs = intel_state->active_crtcs;
14427                 dev_priv->atomic_cdclk_freq = intel_state->cdclk;
14428
14429                 intel_display_power_get(dev_priv, POWER_DOMAIN_MODESET);
14430         }
14431
14432         for_each_crtc_in_state(state, crtc, old_crtc_state, i) {
14433                 struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
14434
14435                 if (needs_modeset(crtc->state) ||
14436                     to_intel_crtc_state(crtc->state)->update_pipe) {
14437                         hw_check = true;
14438
14439                         put_domains[to_intel_crtc(crtc)->pipe] =
14440                                 modeset_get_crtc_power_domains(crtc,
14441                                         to_intel_crtc_state(crtc->state));
14442                 }
14443
14444                 if (!needs_modeset(crtc->state))
14445                         continue;
14446
14447                 intel_pre_plane_update(to_intel_crtc_state(old_crtc_state));
14448
14449                 if (old_crtc_state->active) {
14450                         intel_crtc_disable_planes(crtc, old_crtc_state->plane_mask);
14451                         dev_priv->display.crtc_disable(to_intel_crtc_state(old_crtc_state), state);
14452                         intel_crtc->active = false;
14453                         intel_fbc_disable(intel_crtc);
14454                         intel_disable_shared_dpll(intel_crtc);
14455
14456                         /*
14457                          * Underruns don't always raise
14458                          * interrupts, so check manually.
14459                          */
14460                         intel_check_cpu_fifo_underruns(dev_priv);
14461                         intel_check_pch_fifo_underruns(dev_priv);
14462
14463                         if (!crtc->state->active)
14464                                 intel_update_watermarks(crtc);
14465                 }
14466         }
14467
14468         /* Only after disabling all output pipelines that will be changed can we
14469          * update the the output configuration. */
14470         intel_modeset_update_crtc_state(state);
14471
14472         if (intel_state->modeset) {
14473                 drm_atomic_helper_update_legacy_modeset_state(state->dev, state);
14474
14475                 if (dev_priv->display.modeset_commit_cdclk &&
14476                     (intel_state->dev_cdclk != dev_priv->cdclk_freq ||
14477                      intel_state->cdclk_pll_vco != dev_priv->cdclk_pll.vco))
14478                         dev_priv->display.modeset_commit_cdclk(state);
14479
14480                 /*
14481                  * SKL workaround: bspec recommends we disable the SAGV when we
14482                  * have more then one pipe enabled
14483                  */
14484                 if (!intel_can_enable_sagv(state))
14485                         intel_disable_sagv(dev_priv);
14486
14487                 intel_modeset_verify_disabled(dev);
14488         }
14489
14490         /* Complete the events for pipes that have now been disabled */
14491         for_each_crtc_in_state(state, crtc, old_crtc_state, i) {
14492                 bool modeset = needs_modeset(crtc->state);
14493
14494                 /* Complete events for now disable pipes here. */
14495                 if (modeset && !crtc->state->active && crtc->state->event) {
14496                         spin_lock_irq(&dev->event_lock);
14497                         drm_crtc_send_vblank_event(crtc, crtc->state->event);
14498                         spin_unlock_irq(&dev->event_lock);
14499
14500                         crtc->state->event = NULL;
14501                 }
14502         }
14503
14504         /* Now enable the clocks, plane, pipe, and connectors that we set up. */
14505         dev_priv->display.update_crtcs(state, &crtc_vblank_mask);
14506
14507         /* FIXME: We should call drm_atomic_helper_commit_hw_done() here
14508          * already, but still need the state for the delayed optimization. To
14509          * fix this:
14510          * - wrap the optimization/post_plane_update stuff into a per-crtc work.
14511          * - schedule that vblank worker _before_ calling hw_done
14512          * - at the start of commit_tail, cancel it _synchrously
14513          * - switch over to the vblank wait helper in the core after that since
14514          *   we don't need out special handling any more.
14515          */
14516         if (!state->legacy_cursor_update)
14517                 intel_atomic_wait_for_vblanks(dev, dev_priv, crtc_vblank_mask);
14518
14519         /*
14520          * Now that the vblank has passed, we can go ahead and program the
14521          * optimal watermarks on platforms that need two-step watermark
14522          * programming.
14523          *
14524          * TODO: Move this (and other cleanup) to an async worker eventually.
14525          */
14526         for_each_crtc_in_state(state, crtc, old_crtc_state, i) {
14527                 intel_cstate = to_intel_crtc_state(crtc->state);
14528
14529                 if (dev_priv->display.optimize_watermarks)
14530                         dev_priv->display.optimize_watermarks(intel_cstate);
14531         }
14532
14533         for_each_crtc_in_state(state, crtc, old_crtc_state, i) {
14534                 intel_post_plane_update(to_intel_crtc_state(old_crtc_state));
14535
14536                 if (put_domains[i])
14537                         modeset_put_power_domains(dev_priv, put_domains[i]);
14538
14539                 intel_modeset_verify_crtc(crtc, old_crtc_state, crtc->state);
14540         }
14541
14542         if (intel_state->modeset && intel_can_enable_sagv(state))
14543                 intel_enable_sagv(dev_priv);
14544
14545         drm_atomic_helper_commit_hw_done(state);
14546
14547         if (intel_state->modeset)
14548                 intel_display_power_put(dev_priv, POWER_DOMAIN_MODESET);
14549
14550         mutex_lock(&dev->struct_mutex);
14551         drm_atomic_helper_cleanup_planes(dev, state);
14552         mutex_unlock(&dev->struct_mutex);
14553
14554         drm_atomic_helper_commit_cleanup_done(state);
14555
14556         drm_atomic_state_put(state);
14557
14558         /* As one of the primary mmio accessors, KMS has a high likelihood
14559          * of triggering bugs in unclaimed access. After we finish
14560          * modesetting, see if an error has been flagged, and if so
14561          * enable debugging for the next modeset - and hope we catch
14562          * the culprit.
14563          *
14564          * XXX note that we assume display power is on at this point.
14565          * This might hold true now but we need to add pm helper to check
14566          * unclaimed only when the hardware is on, as atomic commits
14567          * can happen also when the device is completely off.
14568          */
14569         intel_uncore_arm_unclaimed_mmio_detection(dev_priv);
14570 }
14571
14572 static void intel_atomic_commit_work(struct work_struct *work)
14573 {
14574         struct drm_atomic_state *state = container_of(work,
14575                                                       struct drm_atomic_state,
14576                                                       commit_work);
14577         intel_atomic_commit_tail(state);
14578 }
14579
14580 static void intel_atomic_track_fbs(struct drm_atomic_state *state)
14581 {
14582         struct drm_plane_state *old_plane_state;
14583         struct drm_plane *plane;
14584         int i;
14585
14586         for_each_plane_in_state(state, plane, old_plane_state, i)
14587                 i915_gem_track_fb(intel_fb_obj(old_plane_state->fb),
14588                                   intel_fb_obj(plane->state->fb),
14589                                   to_intel_plane(plane)->frontbuffer_bit);
14590 }
14591
14592 /**
14593  * intel_atomic_commit - commit validated state object
14594  * @dev: DRM device
14595  * @state: the top-level driver state object
14596  * @nonblock: nonblocking commit
14597  *
14598  * This function commits a top-level state object that has been validated
14599  * with drm_atomic_helper_check().
14600  *
14601  * FIXME:  Atomic modeset support for i915 is not yet complete.  At the moment
14602  * nonblocking commits are only safe for pure plane updates. Everything else
14603  * should work though.
14604  *
14605  * RETURNS
14606  * Zero for success or -errno.
14607  */
14608 static int intel_atomic_commit(struct drm_device *dev,
14609                                struct drm_atomic_state *state,
14610                                bool nonblock)
14611 {
14612         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
14613         struct drm_i915_private *dev_priv = to_i915(dev);
14614         int ret = 0;
14615
14616         if (intel_state->modeset && nonblock) {
14617                 DRM_DEBUG_KMS("nonblocking commit for modeset not yet implemented.\n");
14618                 return -EINVAL;
14619         }
14620
14621         ret = drm_atomic_helper_setup_commit(state, nonblock);
14622         if (ret)
14623                 return ret;
14624
14625         INIT_WORK(&state->commit_work, intel_atomic_commit_work);
14626
14627         ret = intel_atomic_prepare_commit(dev, state, nonblock);
14628         if (ret) {
14629                 DRM_DEBUG_ATOMIC("Preparing state failed with %i\n", ret);
14630                 return ret;
14631         }
14632
14633         drm_atomic_helper_swap_state(state, true);
14634         dev_priv->wm.distrust_bios_wm = false;
14635         dev_priv->wm.skl_results = intel_state->wm_results;
14636         intel_shared_dpll_commit(state);
14637         intel_atomic_track_fbs(state);
14638
14639         drm_atomic_state_get(state);
14640         if (nonblock)
14641                 queue_work(system_unbound_wq, &state->commit_work);
14642         else
14643                 intel_atomic_commit_tail(state);
14644
14645         return 0;
14646 }
14647
14648 void intel_crtc_restore_mode(struct drm_crtc *crtc)
14649 {
14650         struct drm_device *dev = crtc->dev;
14651         struct drm_atomic_state *state;
14652         struct drm_crtc_state *crtc_state;
14653         int ret;
14654
14655         state = drm_atomic_state_alloc(dev);
14656         if (!state) {
14657                 DRM_DEBUG_KMS("[CRTC:%d:%s] crtc restore failed, out of memory",
14658                               crtc->base.id, crtc->name);
14659                 return;
14660         }
14661
14662         state->acquire_ctx = drm_modeset_legacy_acquire_ctx(crtc);
14663
14664 retry:
14665         crtc_state = drm_atomic_get_crtc_state(state, crtc);
14666         ret = PTR_ERR_OR_ZERO(crtc_state);
14667         if (!ret) {
14668                 if (!crtc_state->active)
14669                         goto out;
14670
14671                 crtc_state->mode_changed = true;
14672                 ret = drm_atomic_commit(state);
14673         }
14674
14675         if (ret == -EDEADLK) {
14676                 drm_atomic_state_clear(state);
14677                 drm_modeset_backoff(state->acquire_ctx);
14678                 goto retry;
14679         }
14680
14681 out:
14682         drm_atomic_state_put(state);
14683 }
14684
14685 /*
14686  * FIXME: Remove this once i915 is fully DRIVER_ATOMIC by calling
14687  *        drm_atomic_helper_legacy_gamma_set() directly.
14688  */
14689 static int intel_atomic_legacy_gamma_set(struct drm_crtc *crtc,
14690                                          u16 *red, u16 *green, u16 *blue,
14691                                          uint32_t size)
14692 {
14693         struct drm_device *dev = crtc->dev;
14694         struct drm_mode_config *config = &dev->mode_config;
14695         struct drm_crtc_state *state;
14696         int ret;
14697
14698         ret = drm_atomic_helper_legacy_gamma_set(crtc, red, green, blue, size);
14699         if (ret)
14700                 return ret;
14701
14702         /*
14703          * Make sure we update the legacy properties so this works when
14704          * atomic is not enabled.
14705          */
14706
14707         state = crtc->state;
14708
14709         drm_object_property_set_value(&crtc->base,
14710                                       config->degamma_lut_property,
14711                                       (state->degamma_lut) ?
14712                                       state->degamma_lut->base.id : 0);
14713
14714         drm_object_property_set_value(&crtc->base,
14715                                       config->ctm_property,
14716                                       (state->ctm) ?
14717                                       state->ctm->base.id : 0);
14718
14719         drm_object_property_set_value(&crtc->base,
14720                                       config->gamma_lut_property,
14721                                       (state->gamma_lut) ?
14722                                       state->gamma_lut->base.id : 0);
14723
14724         return 0;
14725 }
14726
14727 static const struct drm_crtc_funcs intel_crtc_funcs = {
14728         .gamma_set = intel_atomic_legacy_gamma_set,
14729         .set_config = drm_atomic_helper_set_config,
14730         .set_property = drm_atomic_helper_crtc_set_property,
14731         .destroy = intel_crtc_destroy,
14732         .page_flip = intel_crtc_page_flip,
14733         .atomic_duplicate_state = intel_crtc_duplicate_state,
14734         .atomic_destroy_state = intel_crtc_destroy_state,
14735 };
14736
14737 /**
14738  * intel_prepare_plane_fb - Prepare fb for usage on plane
14739  * @plane: drm plane to prepare for
14740  * @fb: framebuffer to prepare for presentation
14741  *
14742  * Prepares a framebuffer for usage on a display plane.  Generally this
14743  * involves pinning the underlying object and updating the frontbuffer tracking
14744  * bits.  Some older platforms need special physical address handling for
14745  * cursor planes.
14746  *
14747  * Must be called with struct_mutex held.
14748  *
14749  * Returns 0 on success, negative error code on failure.
14750  */
14751 int
14752 intel_prepare_plane_fb(struct drm_plane *plane,
14753                        struct drm_plane_state *new_state)
14754 {
14755         struct drm_device *dev = plane->dev;
14756         struct drm_i915_private *dev_priv = to_i915(dev);
14757         struct drm_framebuffer *fb = new_state->fb;
14758         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
14759         struct drm_i915_gem_object *old_obj = intel_fb_obj(plane->state->fb);
14760         struct reservation_object *resv;
14761         int ret = 0;
14762
14763         if (!obj && !old_obj)
14764                 return 0;
14765
14766         if (old_obj) {
14767                 struct drm_crtc_state *crtc_state =
14768                         drm_atomic_get_existing_crtc_state(new_state->state, plane->state->crtc);
14769
14770                 /* Big Hammer, we also need to ensure that any pending
14771                  * MI_WAIT_FOR_EVENT inside a user batch buffer on the
14772                  * current scanout is retired before unpinning the old
14773                  * framebuffer. Note that we rely on userspace rendering
14774                  * into the buffer attached to the pipe they are waiting
14775                  * on. If not, userspace generates a GPU hang with IPEHR
14776                  * point to the MI_WAIT_FOR_EVENT.
14777                  *
14778                  * This should only fail upon a hung GPU, in which case we
14779                  * can safely continue.
14780                  */
14781                 if (needs_modeset(crtc_state))
14782                         ret = i915_gem_object_wait_rendering(old_obj, true);
14783                 if (ret) {
14784                         /* GPU hangs should have been swallowed by the wait */
14785                         WARN_ON(ret == -EIO);
14786                         return ret;
14787                 }
14788         }
14789
14790         if (!obj)
14791                 return 0;
14792
14793         /* For framebuffer backed by dmabuf, wait for fence */
14794         resv = i915_gem_object_get_dmabuf_resv(obj);
14795         if (resv) {
14796                 long lret;
14797
14798                 lret = reservation_object_wait_timeout_rcu(resv, false, true,
14799                                                            MAX_SCHEDULE_TIMEOUT);
14800                 if (lret == -ERESTARTSYS)
14801                         return lret;
14802
14803                 WARN(lret < 0, "waiting returns %li\n", lret);
14804         }
14805
14806         if (plane->type == DRM_PLANE_TYPE_CURSOR &&
14807             INTEL_INFO(dev)->cursor_needs_physical) {
14808                 int align = IS_I830(dev_priv) ? 16 * 1024 : 256;
14809                 ret = i915_gem_object_attach_phys(obj, align);
14810                 if (ret)
14811                         DRM_DEBUG_KMS("failed to attach phys object\n");
14812         } else {
14813                 struct i915_vma *vma;
14814
14815                 vma = intel_pin_and_fence_fb_obj(fb, new_state->rotation);
14816                 if (IS_ERR(vma))
14817                         ret = PTR_ERR(vma);
14818         }
14819
14820         if (ret == 0) {
14821                 to_intel_plane_state(new_state)->wait_req =
14822                         i915_gem_active_get(&obj->last_write,
14823                                             &obj->base.dev->struct_mutex);
14824         }
14825
14826         return ret;
14827 }
14828
14829 /**
14830  * intel_cleanup_plane_fb - Cleans up an fb after plane use
14831  * @plane: drm plane to clean up for
14832  * @fb: old framebuffer that was on plane
14833  *
14834  * Cleans up a framebuffer that has just been removed from a plane.
14835  *
14836  * Must be called with struct_mutex held.
14837  */
14838 void
14839 intel_cleanup_plane_fb(struct drm_plane *plane,
14840                        struct drm_plane_state *old_state)
14841 {
14842         struct drm_device *dev = plane->dev;
14843         struct intel_plane_state *old_intel_state;
14844         struct intel_plane_state *intel_state = to_intel_plane_state(plane->state);
14845         struct drm_i915_gem_object *old_obj = intel_fb_obj(old_state->fb);
14846         struct drm_i915_gem_object *obj = intel_fb_obj(plane->state->fb);
14847
14848         old_intel_state = to_intel_plane_state(old_state);
14849
14850         if (!obj && !old_obj)
14851                 return;
14852
14853         if (old_obj && (plane->type != DRM_PLANE_TYPE_CURSOR ||
14854             !INTEL_INFO(dev)->cursor_needs_physical))
14855                 intel_unpin_fb_obj(old_state->fb, old_state->rotation);
14856
14857         i915_gem_request_assign(&intel_state->wait_req, NULL);
14858         i915_gem_request_assign(&old_intel_state->wait_req, NULL);
14859 }
14860
14861 int
14862 skl_max_scale(struct intel_crtc *intel_crtc, struct intel_crtc_state *crtc_state)
14863 {
14864         int max_scale;
14865         int crtc_clock, cdclk;
14866
14867         if (!intel_crtc || !crtc_state->base.enable)
14868                 return DRM_PLANE_HELPER_NO_SCALING;
14869
14870         crtc_clock = crtc_state->base.adjusted_mode.crtc_clock;
14871         cdclk = to_intel_atomic_state(crtc_state->base.state)->cdclk;
14872
14873         if (WARN_ON_ONCE(!crtc_clock || cdclk < crtc_clock))
14874                 return DRM_PLANE_HELPER_NO_SCALING;
14875
14876         /*
14877          * skl max scale is lower of:
14878          *    close to 3 but not 3, -1 is for that purpose
14879          *            or
14880          *    cdclk/crtc_clock
14881          */
14882         max_scale = min((1 << 16) * 3 - 1, (1 << 8) * ((cdclk << 8) / crtc_clock));
14883
14884         return max_scale;
14885 }
14886
14887 static int
14888 intel_check_primary_plane(struct drm_plane *plane,
14889                           struct intel_crtc_state *crtc_state,
14890                           struct intel_plane_state *state)
14891 {
14892         struct drm_i915_private *dev_priv = to_i915(plane->dev);
14893         struct drm_crtc *crtc = state->base.crtc;
14894         int min_scale = DRM_PLANE_HELPER_NO_SCALING;
14895         int max_scale = DRM_PLANE_HELPER_NO_SCALING;
14896         bool can_position = false;
14897         int ret;
14898
14899         if (INTEL_GEN(dev_priv) >= 9) {
14900                 /* use scaler when colorkey is not required */
14901                 if (state->ckey.flags == I915_SET_COLORKEY_NONE) {
14902                         min_scale = 1;
14903                         max_scale = skl_max_scale(to_intel_crtc(crtc), crtc_state);
14904                 }
14905                 can_position = true;
14906         }
14907
14908         ret = drm_plane_helper_check_state(&state->base,
14909                                            &state->clip,
14910                                            min_scale, max_scale,
14911                                            can_position, true);
14912         if (ret)
14913                 return ret;
14914
14915         if (!state->base.fb)
14916                 return 0;
14917
14918         if (INTEL_GEN(dev_priv) >= 9) {
14919                 ret = skl_check_plane_surface(state);
14920                 if (ret)
14921                         return ret;
14922         }
14923
14924         return 0;
14925 }
14926
14927 static void intel_begin_crtc_commit(struct drm_crtc *crtc,
14928                                     struct drm_crtc_state *old_crtc_state)
14929 {
14930         struct drm_device *dev = crtc->dev;
14931         struct drm_i915_private *dev_priv = to_i915(dev);
14932         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
14933         struct intel_crtc_state *intel_cstate =
14934                 to_intel_crtc_state(crtc->state);
14935         struct intel_crtc_state *old_intel_state =
14936                 to_intel_crtc_state(old_crtc_state);
14937         bool modeset = needs_modeset(crtc->state);
14938         enum pipe pipe = intel_crtc->pipe;
14939
14940         /* Perform vblank evasion around commit operation */
14941         intel_pipe_update_start(intel_crtc);
14942
14943         if (modeset)
14944                 return;
14945
14946         if (crtc->state->color_mgmt_changed || to_intel_crtc_state(crtc->state)->update_pipe) {
14947                 intel_color_set_csc(crtc->state);
14948                 intel_color_load_luts(crtc->state);
14949         }
14950
14951         if (intel_cstate->update_pipe) {
14952                 intel_update_pipe_config(intel_crtc, old_intel_state);
14953         } else if (INTEL_GEN(dev_priv) >= 9) {
14954                 skl_detach_scalers(intel_crtc);
14955
14956                 I915_WRITE(PIPE_WM_LINETIME(pipe),
14957                            intel_cstate->wm.skl.optimal.linetime);
14958         }
14959 }
14960
14961 static void intel_finish_crtc_commit(struct drm_crtc *crtc,
14962                                      struct drm_crtc_state *old_crtc_state)
14963 {
14964         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
14965
14966         intel_pipe_update_end(intel_crtc, NULL);
14967 }
14968
14969 /**
14970  * intel_plane_destroy - destroy a plane
14971  * @plane: plane to destroy
14972  *
14973  * Common destruction function for all types of planes (primary, cursor,
14974  * sprite).
14975  */
14976 void intel_plane_destroy(struct drm_plane *plane)
14977 {
14978         if (!plane)
14979                 return;
14980
14981         drm_plane_cleanup(plane);
14982         kfree(to_intel_plane(plane));
14983 }
14984
14985 const struct drm_plane_funcs intel_plane_funcs = {
14986         .update_plane = drm_atomic_helper_update_plane,
14987         .disable_plane = drm_atomic_helper_disable_plane,
14988         .destroy = intel_plane_destroy,
14989         .set_property = drm_atomic_helper_plane_set_property,
14990         .atomic_get_property = intel_plane_atomic_get_property,
14991         .atomic_set_property = intel_plane_atomic_set_property,
14992         .atomic_duplicate_state = intel_plane_duplicate_state,
14993         .atomic_destroy_state = intel_plane_destroy_state,
14994
14995 };
14996
14997 static struct drm_plane *intel_primary_plane_create(struct drm_device *dev,
14998                                                     int pipe)
14999 {
15000         struct drm_i915_private *dev_priv = to_i915(dev);
15001         struct intel_plane *primary = NULL;
15002         struct intel_plane_state *state = NULL;
15003         const uint32_t *intel_primary_formats;
15004         unsigned int supported_rotations;
15005         unsigned int num_formats;
15006         int ret;
15007
15008         primary = kzalloc(sizeof(*primary), GFP_KERNEL);
15009         if (!primary)
15010                 goto fail;
15011
15012         state = intel_create_plane_state(&primary->base);
15013         if (!state)
15014                 goto fail;
15015         primary->base.state = &state->base;
15016
15017         primary->can_scale = false;
15018         primary->max_downscale = 1;
15019         if (INTEL_INFO(dev)->gen >= 9) {
15020                 primary->can_scale = true;
15021                 state->scaler_id = -1;
15022         }
15023         primary->pipe = pipe;
15024         primary->plane = pipe;
15025         primary->frontbuffer_bit = INTEL_FRONTBUFFER_PRIMARY(pipe);
15026         primary->check_plane = intel_check_primary_plane;
15027         if (HAS_FBC(dev) && INTEL_INFO(dev)->gen < 4)
15028                 primary->plane = !pipe;
15029
15030         if (INTEL_INFO(dev)->gen >= 9) {
15031                 intel_primary_formats = skl_primary_formats;
15032                 num_formats = ARRAY_SIZE(skl_primary_formats);
15033
15034                 primary->update_plane = skylake_update_primary_plane;
15035                 primary->disable_plane = skylake_disable_primary_plane;
15036         } else if (HAS_PCH_SPLIT(dev_priv)) {
15037                 intel_primary_formats = i965_primary_formats;
15038                 num_formats = ARRAY_SIZE(i965_primary_formats);
15039
15040                 primary->update_plane = ironlake_update_primary_plane;
15041                 primary->disable_plane = i9xx_disable_primary_plane;
15042         } else if (INTEL_INFO(dev)->gen >= 4) {
15043                 intel_primary_formats = i965_primary_formats;
15044                 num_formats = ARRAY_SIZE(i965_primary_formats);
15045
15046                 primary->update_plane = i9xx_update_primary_plane;
15047                 primary->disable_plane = i9xx_disable_primary_plane;
15048         } else {
15049                 intel_primary_formats = i8xx_primary_formats;
15050                 num_formats = ARRAY_SIZE(i8xx_primary_formats);
15051
15052                 primary->update_plane = i9xx_update_primary_plane;
15053                 primary->disable_plane = i9xx_disable_primary_plane;
15054         }
15055
15056         if (INTEL_INFO(dev)->gen >= 9)
15057                 ret = drm_universal_plane_init(dev, &primary->base, 0,
15058                                                &intel_plane_funcs,
15059                                                intel_primary_formats, num_formats,
15060                                                DRM_PLANE_TYPE_PRIMARY,
15061                                                "plane 1%c", pipe_name(pipe));
15062         else if (INTEL_GEN(dev_priv) >= 5 || IS_G4X(dev_priv))
15063                 ret = drm_universal_plane_init(dev, &primary->base, 0,
15064                                                &intel_plane_funcs,
15065                                                intel_primary_formats, num_formats,
15066                                                DRM_PLANE_TYPE_PRIMARY,
15067                                                "primary %c", pipe_name(pipe));
15068         else
15069                 ret = drm_universal_plane_init(dev, &primary->base, 0,
15070                                                &intel_plane_funcs,
15071                                                intel_primary_formats, num_formats,
15072                                                DRM_PLANE_TYPE_PRIMARY,
15073                                                "plane %c", plane_name(primary->plane));
15074         if (ret)
15075                 goto fail;
15076
15077         if (INTEL_GEN(dev_priv) >= 9) {
15078                 supported_rotations =
15079                         DRM_ROTATE_0 | DRM_ROTATE_90 |
15080                         DRM_ROTATE_180 | DRM_ROTATE_270;
15081         } else if (INTEL_GEN(dev_priv) >= 4) {
15082                 supported_rotations =
15083                         DRM_ROTATE_0 | DRM_ROTATE_180;
15084         } else {
15085                 supported_rotations = DRM_ROTATE_0;
15086         }
15087
15088         if (INTEL_GEN(dev_priv) >= 4)
15089                 drm_plane_create_rotation_property(&primary->base,
15090                                                    DRM_ROTATE_0,
15091                                                    supported_rotations);
15092
15093         drm_plane_helper_add(&primary->base, &intel_plane_helper_funcs);
15094
15095         return &primary->base;
15096
15097 fail:
15098         kfree(state);
15099         kfree(primary);
15100
15101         return NULL;
15102 }
15103
15104 static int
15105 intel_check_cursor_plane(struct drm_plane *plane,
15106                          struct intel_crtc_state *crtc_state,
15107                          struct intel_plane_state *state)
15108 {
15109         struct drm_framebuffer *fb = state->base.fb;
15110         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
15111         enum pipe pipe = to_intel_plane(plane)->pipe;
15112         unsigned stride;
15113         int ret;
15114
15115         ret = drm_plane_helper_check_state(&state->base,
15116                                            &state->clip,
15117                                            DRM_PLANE_HELPER_NO_SCALING,
15118                                            DRM_PLANE_HELPER_NO_SCALING,
15119                                            true, true);
15120         if (ret)
15121                 return ret;
15122
15123         /* if we want to turn off the cursor ignore width and height */
15124         if (!obj)
15125                 return 0;
15126
15127         /* Check for which cursor types we support */
15128         if (!cursor_size_ok(to_i915(plane->dev), state->base.crtc_w,
15129                             state->base.crtc_h)) {
15130                 DRM_DEBUG("Cursor dimension %dx%d not supported\n",
15131                           state->base.crtc_w, state->base.crtc_h);
15132                 return -EINVAL;
15133         }
15134
15135         stride = roundup_pow_of_two(state->base.crtc_w) * 4;
15136         if (obj->base.size < stride * state->base.crtc_h) {
15137                 DRM_DEBUG_KMS("buffer is too small\n");
15138                 return -ENOMEM;
15139         }
15140
15141         if (fb->modifier[0] != DRM_FORMAT_MOD_NONE) {
15142                 DRM_DEBUG_KMS("cursor cannot be tiled\n");
15143                 return -EINVAL;
15144         }
15145
15146         /*
15147          * There's something wrong with the cursor on CHV pipe C.
15148          * If it straddles the left edge of the screen then
15149          * moving it away from the edge or disabling it often
15150          * results in a pipe underrun, and often that can lead to
15151          * dead pipe (constant underrun reported, and it scans
15152          * out just a solid color). To recover from that, the
15153          * display power well must be turned off and on again.
15154          * Refuse the put the cursor into that compromised position.
15155          */
15156         if (IS_CHERRYVIEW(to_i915(plane->dev)) && pipe == PIPE_C &&
15157             state->base.visible && state->base.crtc_x < 0) {
15158                 DRM_DEBUG_KMS("CHV cursor C not allowed to straddle the left screen edge\n");
15159                 return -EINVAL;
15160         }
15161
15162         return 0;
15163 }
15164
15165 static void
15166 intel_disable_cursor_plane(struct drm_plane *plane,
15167                            struct drm_crtc *crtc)
15168 {
15169         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
15170
15171         intel_crtc->cursor_addr = 0;
15172         intel_crtc_update_cursor(crtc, NULL);
15173 }
15174
15175 static void
15176 intel_update_cursor_plane(struct drm_plane *plane,
15177                           const struct intel_crtc_state *crtc_state,
15178                           const struct intel_plane_state *state)
15179 {
15180         struct drm_crtc *crtc = crtc_state->base.crtc;
15181         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
15182         struct drm_device *dev = plane->dev;
15183         struct drm_i915_gem_object *obj = intel_fb_obj(state->base.fb);
15184         uint32_t addr;
15185
15186         if (!obj)
15187                 addr = 0;
15188         else if (!INTEL_INFO(dev)->cursor_needs_physical)
15189                 addr = i915_gem_object_ggtt_offset(obj, NULL);
15190         else
15191                 addr = obj->phys_handle->busaddr;
15192
15193         intel_crtc->cursor_addr = addr;
15194         intel_crtc_update_cursor(crtc, state);
15195 }
15196
15197 static struct drm_plane *intel_cursor_plane_create(struct drm_device *dev,
15198                                                    int pipe)
15199 {
15200         struct drm_i915_private *dev_priv = to_i915(dev);
15201         struct intel_plane *cursor = NULL;
15202         struct intel_plane_state *state = NULL;
15203         int ret;
15204
15205         cursor = kzalloc(sizeof(*cursor), GFP_KERNEL);
15206         if (!cursor)
15207                 goto fail;
15208
15209         state = intel_create_plane_state(&cursor->base);
15210         if (!state)
15211                 goto fail;
15212         cursor->base.state = &state->base;
15213
15214         cursor->can_scale = false;
15215         cursor->max_downscale = 1;
15216         cursor->pipe = pipe;
15217         cursor->plane = pipe;
15218         cursor->frontbuffer_bit = INTEL_FRONTBUFFER_CURSOR(pipe);
15219         cursor->check_plane = intel_check_cursor_plane;
15220         cursor->update_plane = intel_update_cursor_plane;
15221         cursor->disable_plane = intel_disable_cursor_plane;
15222
15223         ret = drm_universal_plane_init(dev, &cursor->base, 0,
15224                                        &intel_plane_funcs,
15225                                        intel_cursor_formats,
15226                                        ARRAY_SIZE(intel_cursor_formats),
15227                                        DRM_PLANE_TYPE_CURSOR,
15228                                        "cursor %c", pipe_name(pipe));
15229         if (ret)
15230                 goto fail;
15231
15232         if (INTEL_GEN(dev_priv) >= 4)
15233                 drm_plane_create_rotation_property(&cursor->base,
15234                                                    DRM_ROTATE_0,
15235                                                    DRM_ROTATE_0 |
15236                                                    DRM_ROTATE_180);
15237
15238         if (INTEL_INFO(dev)->gen >=9)
15239                 state->scaler_id = -1;
15240
15241         drm_plane_helper_add(&cursor->base, &intel_plane_helper_funcs);
15242
15243         return &cursor->base;
15244
15245 fail:
15246         kfree(state);
15247         kfree(cursor);
15248
15249         return NULL;
15250 }
15251
15252 static void skl_init_scalers(struct drm_device *dev, struct intel_crtc *intel_crtc,
15253         struct intel_crtc_state *crtc_state)
15254 {
15255         int i;
15256         struct intel_scaler *intel_scaler;
15257         struct intel_crtc_scaler_state *scaler_state = &crtc_state->scaler_state;
15258
15259         for (i = 0; i < intel_crtc->num_scalers; i++) {
15260                 intel_scaler = &scaler_state->scalers[i];
15261                 intel_scaler->in_use = 0;
15262                 intel_scaler->mode = PS_SCALER_MODE_DYN;
15263         }
15264
15265         scaler_state->scaler_id = -1;
15266 }
15267
15268 static void intel_crtc_init(struct drm_device *dev, int pipe)
15269 {
15270         struct drm_i915_private *dev_priv = to_i915(dev);
15271         struct intel_crtc *intel_crtc;
15272         struct intel_crtc_state *crtc_state = NULL;
15273         struct drm_plane *primary = NULL;
15274         struct drm_plane *cursor = NULL;
15275         int ret;
15276
15277         intel_crtc = kzalloc(sizeof(*intel_crtc), GFP_KERNEL);
15278         if (intel_crtc == NULL)
15279                 return;
15280
15281         crtc_state = kzalloc(sizeof(*crtc_state), GFP_KERNEL);
15282         if (!crtc_state)
15283                 goto fail;
15284         intel_crtc->config = crtc_state;
15285         intel_crtc->base.state = &crtc_state->base;
15286         crtc_state->base.crtc = &intel_crtc->base;
15287
15288         /* initialize shared scalers */
15289         if (INTEL_INFO(dev)->gen >= 9) {
15290                 if (pipe == PIPE_C)
15291                         intel_crtc->num_scalers = 1;
15292                 else
15293                         intel_crtc->num_scalers = SKL_NUM_SCALERS;
15294
15295                 skl_init_scalers(dev, intel_crtc, crtc_state);
15296         }
15297
15298         primary = intel_primary_plane_create(dev, pipe);
15299         if (!primary)
15300                 goto fail;
15301
15302         cursor = intel_cursor_plane_create(dev, pipe);
15303         if (!cursor)
15304                 goto fail;
15305
15306         ret = drm_crtc_init_with_planes(dev, &intel_crtc->base, primary,
15307                                         cursor, &intel_crtc_funcs,
15308                                         "pipe %c", pipe_name(pipe));
15309         if (ret)
15310                 goto fail;
15311
15312         /*
15313          * On gen2/3 only plane A can do fbc, but the panel fitter and lvds port
15314          * is hooked to pipe B. Hence we want plane A feeding pipe B.
15315          */
15316         intel_crtc->pipe = pipe;
15317         intel_crtc->plane = pipe;
15318         if (HAS_FBC(dev) && INTEL_INFO(dev)->gen < 4) {
15319                 DRM_DEBUG_KMS("swapping pipes & planes for FBC\n");
15320                 intel_crtc->plane = !pipe;
15321         }
15322
15323         intel_crtc->cursor_base = ~0;
15324         intel_crtc->cursor_cntl = ~0;
15325         intel_crtc->cursor_size = ~0;
15326
15327         intel_crtc->wm.cxsr_allowed = true;
15328
15329         BUG_ON(pipe >= ARRAY_SIZE(dev_priv->plane_to_crtc_mapping) ||
15330                dev_priv->plane_to_crtc_mapping[intel_crtc->plane] != NULL);
15331         dev_priv->plane_to_crtc_mapping[intel_crtc->plane] = &intel_crtc->base;
15332         dev_priv->pipe_to_crtc_mapping[intel_crtc->pipe] = &intel_crtc->base;
15333
15334         drm_crtc_helper_add(&intel_crtc->base, &intel_helper_funcs);
15335
15336         intel_color_init(&intel_crtc->base);
15337
15338         WARN_ON(drm_crtc_index(&intel_crtc->base) != intel_crtc->pipe);
15339         return;
15340
15341 fail:
15342         intel_plane_destroy(primary);
15343         intel_plane_destroy(cursor);
15344         kfree(crtc_state);
15345         kfree(intel_crtc);
15346 }
15347
15348 enum pipe intel_get_pipe_from_connector(struct intel_connector *connector)
15349 {
15350         struct drm_encoder *encoder = connector->base.encoder;
15351         struct drm_device *dev = connector->base.dev;
15352
15353         WARN_ON(!drm_modeset_is_locked(&dev->mode_config.connection_mutex));
15354
15355         if (!encoder || WARN_ON(!encoder->crtc))
15356                 return INVALID_PIPE;
15357
15358         return to_intel_crtc(encoder->crtc)->pipe;
15359 }
15360
15361 int intel_get_pipe_from_crtc_id(struct drm_device *dev, void *data,
15362                                 struct drm_file *file)
15363 {
15364         struct drm_i915_get_pipe_from_crtc_id *pipe_from_crtc_id = data;
15365         struct drm_crtc *drmmode_crtc;
15366         struct intel_crtc *crtc;
15367
15368         drmmode_crtc = drm_crtc_find(dev, pipe_from_crtc_id->crtc_id);
15369         if (!drmmode_crtc)
15370                 return -ENOENT;
15371
15372         crtc = to_intel_crtc(drmmode_crtc);
15373         pipe_from_crtc_id->pipe = crtc->pipe;
15374
15375         return 0;
15376 }
15377
15378 static int intel_encoder_clones(struct intel_encoder *encoder)
15379 {
15380         struct drm_device *dev = encoder->base.dev;
15381         struct intel_encoder *source_encoder;
15382         int index_mask = 0;
15383         int entry = 0;
15384
15385         for_each_intel_encoder(dev, source_encoder) {
15386                 if (encoders_cloneable(encoder, source_encoder))
15387                         index_mask |= (1 << entry);
15388
15389                 entry++;
15390         }
15391
15392         return index_mask;
15393 }
15394
15395 static bool has_edp_a(struct drm_device *dev)
15396 {
15397         struct drm_i915_private *dev_priv = to_i915(dev);
15398
15399         if (!IS_MOBILE(dev))
15400                 return false;
15401
15402         if ((I915_READ(DP_A) & DP_DETECTED) == 0)
15403                 return false;
15404
15405         if (IS_GEN5(dev_priv) && (I915_READ(FUSE_STRAP) & ILK_eDP_A_DISABLE))
15406                 return false;
15407
15408         return true;
15409 }
15410
15411 static bool intel_crt_present(struct drm_device *dev)
15412 {
15413         struct drm_i915_private *dev_priv = to_i915(dev);
15414
15415         if (INTEL_INFO(dev)->gen >= 9)
15416                 return false;
15417
15418         if (IS_HSW_ULT(dev_priv) || IS_BDW_ULT(dev_priv))
15419                 return false;
15420
15421         if (IS_CHERRYVIEW(dev_priv))
15422                 return false;
15423
15424         if (HAS_PCH_LPT_H(dev_priv) &&
15425             I915_READ(SFUSE_STRAP) & SFUSE_STRAP_CRT_DISABLED)
15426                 return false;
15427
15428         /* DDI E can't be used if DDI A requires 4 lanes */
15429         if (HAS_DDI(dev_priv) && I915_READ(DDI_BUF_CTL(PORT_A)) & DDI_A_4_LANES)
15430                 return false;
15431
15432         if (!dev_priv->vbt.int_crt_support)
15433                 return false;
15434
15435         return true;
15436 }
15437
15438 void intel_pps_unlock_regs_wa(struct drm_i915_private *dev_priv)
15439 {
15440         int pps_num;
15441         int pps_idx;
15442
15443         if (HAS_DDI(dev_priv))
15444                 return;
15445         /*
15446          * This w/a is needed at least on CPT/PPT, but to be sure apply it
15447          * everywhere where registers can be write protected.
15448          */
15449         if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
15450                 pps_num = 2;
15451         else
15452                 pps_num = 1;
15453
15454         for (pps_idx = 0; pps_idx < pps_num; pps_idx++) {
15455                 u32 val = I915_READ(PP_CONTROL(pps_idx));
15456
15457                 val = (val & ~PANEL_UNLOCK_MASK) | PANEL_UNLOCK_REGS;
15458                 I915_WRITE(PP_CONTROL(pps_idx), val);
15459         }
15460 }
15461
15462 static void intel_pps_init(struct drm_i915_private *dev_priv)
15463 {
15464         if (HAS_PCH_SPLIT(dev_priv) || IS_BROXTON(dev_priv))
15465                 dev_priv->pps_mmio_base = PCH_PPS_BASE;
15466         else if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
15467                 dev_priv->pps_mmio_base = VLV_PPS_BASE;
15468         else
15469                 dev_priv->pps_mmio_base = PPS_BASE;
15470
15471         intel_pps_unlock_regs_wa(dev_priv);
15472 }
15473
15474 static void intel_setup_outputs(struct drm_device *dev)
15475 {
15476         struct drm_i915_private *dev_priv = to_i915(dev);
15477         struct intel_encoder *encoder;
15478         bool dpd_is_edp = false;
15479
15480         intel_pps_init(dev_priv);
15481
15482         /*
15483          * intel_edp_init_connector() depends on this completing first, to
15484          * prevent the registeration of both eDP and LVDS and the incorrect
15485          * sharing of the PPS.
15486          */
15487         intel_lvds_init(dev);
15488
15489         if (intel_crt_present(dev))
15490                 intel_crt_init(dev);
15491
15492         if (IS_BROXTON(dev_priv)) {
15493                 /*
15494                  * FIXME: Broxton doesn't support port detection via the
15495                  * DDI_BUF_CTL_A or SFUSE_STRAP registers, find another way to
15496                  * detect the ports.
15497                  */
15498                 intel_ddi_init(dev, PORT_A);
15499                 intel_ddi_init(dev, PORT_B);
15500                 intel_ddi_init(dev, PORT_C);
15501
15502                 intel_dsi_init(dev);
15503         } else if (HAS_DDI(dev_priv)) {
15504                 int found;
15505
15506                 /*
15507                  * Haswell uses DDI functions to detect digital outputs.
15508                  * On SKL pre-D0 the strap isn't connected, so we assume
15509                  * it's there.
15510                  */
15511                 found = I915_READ(DDI_BUF_CTL(PORT_A)) & DDI_INIT_DISPLAY_DETECTED;
15512                 /* WaIgnoreDDIAStrap: skl */
15513                 if (found || IS_SKYLAKE(dev_priv) || IS_KABYLAKE(dev_priv))
15514                         intel_ddi_init(dev, PORT_A);
15515
15516                 /* DDI B, C and D detection is indicated by the SFUSE_STRAP
15517                  * register */
15518                 found = I915_READ(SFUSE_STRAP);
15519
15520                 if (found & SFUSE_STRAP_DDIB_DETECTED)
15521                         intel_ddi_init(dev, PORT_B);
15522                 if (found & SFUSE_STRAP_DDIC_DETECTED)
15523                         intel_ddi_init(dev, PORT_C);
15524                 if (found & SFUSE_STRAP_DDID_DETECTED)
15525                         intel_ddi_init(dev, PORT_D);
15526                 /*
15527                  * On SKL we don't have a way to detect DDI-E so we rely on VBT.
15528                  */
15529                 if ((IS_SKYLAKE(dev_priv) || IS_KABYLAKE(dev_priv)) &&
15530                     (dev_priv->vbt.ddi_port_info[PORT_E].supports_dp ||
15531                      dev_priv->vbt.ddi_port_info[PORT_E].supports_dvi ||
15532                      dev_priv->vbt.ddi_port_info[PORT_E].supports_hdmi))
15533                         intel_ddi_init(dev, PORT_E);
15534
15535         } else if (HAS_PCH_SPLIT(dev_priv)) {
15536                 int found;
15537                 dpd_is_edp = intel_dp_is_edp(dev, PORT_D);
15538
15539                 if (has_edp_a(dev))
15540                         intel_dp_init(dev, DP_A, PORT_A);
15541
15542                 if (I915_READ(PCH_HDMIB) & SDVO_DETECTED) {
15543                         /* PCH SDVOB multiplex with HDMIB */
15544                         found = intel_sdvo_init(dev, PCH_SDVOB, PORT_B);
15545                         if (!found)
15546                                 intel_hdmi_init(dev, PCH_HDMIB, PORT_B);
15547                         if (!found && (I915_READ(PCH_DP_B) & DP_DETECTED))
15548                                 intel_dp_init(dev, PCH_DP_B, PORT_B);
15549                 }
15550
15551                 if (I915_READ(PCH_HDMIC) & SDVO_DETECTED)
15552                         intel_hdmi_init(dev, PCH_HDMIC, PORT_C);
15553
15554                 if (!dpd_is_edp && I915_READ(PCH_HDMID) & SDVO_DETECTED)
15555                         intel_hdmi_init(dev, PCH_HDMID, PORT_D);
15556
15557                 if (I915_READ(PCH_DP_C) & DP_DETECTED)
15558                         intel_dp_init(dev, PCH_DP_C, PORT_C);
15559
15560                 if (I915_READ(PCH_DP_D) & DP_DETECTED)
15561                         intel_dp_init(dev, PCH_DP_D, PORT_D);
15562         } else if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv)) {
15563                 bool has_edp, has_port;
15564
15565                 /*
15566                  * The DP_DETECTED bit is the latched state of the DDC
15567                  * SDA pin at boot. However since eDP doesn't require DDC
15568                  * (no way to plug in a DP->HDMI dongle) the DDC pins for
15569                  * eDP ports may have been muxed to an alternate function.
15570                  * Thus we can't rely on the DP_DETECTED bit alone to detect
15571                  * eDP ports. Consult the VBT as well as DP_DETECTED to
15572                  * detect eDP ports.
15573                  *
15574                  * Sadly the straps seem to be missing sometimes even for HDMI
15575                  * ports (eg. on Voyo V3 - CHT x7-Z8700), so check both strap
15576                  * and VBT for the presence of the port. Additionally we can't
15577                  * trust the port type the VBT declares as we've seen at least
15578                  * HDMI ports that the VBT claim are DP or eDP.
15579                  */
15580                 has_edp = intel_dp_is_edp(dev, PORT_B);
15581                 has_port = intel_bios_is_port_present(dev_priv, PORT_B);
15582                 if (I915_READ(VLV_DP_B) & DP_DETECTED || has_port)
15583                         has_edp &= intel_dp_init(dev, VLV_DP_B, PORT_B);
15584                 if ((I915_READ(VLV_HDMIB) & SDVO_DETECTED || has_port) && !has_edp)
15585                         intel_hdmi_init(dev, VLV_HDMIB, PORT_B);
15586
15587                 has_edp = intel_dp_is_edp(dev, PORT_C);
15588                 has_port = intel_bios_is_port_present(dev_priv, PORT_C);
15589                 if (I915_READ(VLV_DP_C) & DP_DETECTED || has_port)
15590                         has_edp &= intel_dp_init(dev, VLV_DP_C, PORT_C);
15591                 if ((I915_READ(VLV_HDMIC) & SDVO_DETECTED || has_port) && !has_edp)
15592                         intel_hdmi_init(dev, VLV_HDMIC, PORT_C);
15593
15594                 if (IS_CHERRYVIEW(dev_priv)) {
15595                         /*
15596                          * eDP not supported on port D,
15597                          * so no need to worry about it
15598                          */
15599                         has_port = intel_bios_is_port_present(dev_priv, PORT_D);
15600                         if (I915_READ(CHV_DP_D) & DP_DETECTED || has_port)
15601                                 intel_dp_init(dev, CHV_DP_D, PORT_D);
15602                         if (I915_READ(CHV_HDMID) & SDVO_DETECTED || has_port)
15603                                 intel_hdmi_init(dev, CHV_HDMID, PORT_D);
15604                 }
15605
15606                 intel_dsi_init(dev);
15607         } else if (!IS_GEN2(dev_priv) && !IS_PINEVIEW(dev_priv)) {
15608                 bool found = false;
15609
15610                 if (I915_READ(GEN3_SDVOB) & SDVO_DETECTED) {
15611                         DRM_DEBUG_KMS("probing SDVOB\n");
15612                         found = intel_sdvo_init(dev, GEN3_SDVOB, PORT_B);
15613                         if (!found && IS_G4X(dev_priv)) {
15614                                 DRM_DEBUG_KMS("probing HDMI on SDVOB\n");
15615                                 intel_hdmi_init(dev, GEN4_HDMIB, PORT_B);
15616                         }
15617
15618                         if (!found && IS_G4X(dev_priv))
15619                                 intel_dp_init(dev, DP_B, PORT_B);
15620                 }
15621
15622                 /* Before G4X SDVOC doesn't have its own detect register */
15623
15624                 if (I915_READ(GEN3_SDVOB) & SDVO_DETECTED) {
15625                         DRM_DEBUG_KMS("probing SDVOC\n");
15626                         found = intel_sdvo_init(dev, GEN3_SDVOC, PORT_C);
15627                 }
15628
15629                 if (!found && (I915_READ(GEN3_SDVOC) & SDVO_DETECTED)) {
15630
15631                         if (IS_G4X(dev_priv)) {
15632                                 DRM_DEBUG_KMS("probing HDMI on SDVOC\n");
15633                                 intel_hdmi_init(dev, GEN4_HDMIC, PORT_C);
15634                         }
15635                         if (IS_G4X(dev_priv))
15636                                 intel_dp_init(dev, DP_C, PORT_C);
15637                 }
15638
15639                 if (IS_G4X(dev_priv) && (I915_READ(DP_D) & DP_DETECTED))
15640                         intel_dp_init(dev, DP_D, PORT_D);
15641         } else if (IS_GEN2(dev_priv))
15642                 intel_dvo_init(dev);
15643
15644         if (SUPPORTS_TV(dev))
15645                 intel_tv_init(dev);
15646
15647         intel_psr_init(dev);
15648
15649         for_each_intel_encoder(dev, encoder) {
15650                 encoder->base.possible_crtcs = encoder->crtc_mask;
15651                 encoder->base.possible_clones =
15652                         intel_encoder_clones(encoder);
15653         }
15654
15655         intel_init_pch_refclk(dev);
15656
15657         drm_helper_move_panel_connectors_to_head(dev);
15658 }
15659
15660 static void intel_user_framebuffer_destroy(struct drm_framebuffer *fb)
15661 {
15662         struct drm_device *dev = fb->dev;
15663         struct intel_framebuffer *intel_fb = to_intel_framebuffer(fb);
15664
15665         drm_framebuffer_cleanup(fb);
15666         mutex_lock(&dev->struct_mutex);
15667         WARN_ON(!intel_fb->obj->framebuffer_references--);
15668         i915_gem_object_put(intel_fb->obj);
15669         mutex_unlock(&dev->struct_mutex);
15670         kfree(intel_fb);
15671 }
15672
15673 static int intel_user_framebuffer_create_handle(struct drm_framebuffer *fb,
15674                                                 struct drm_file *file,
15675                                                 unsigned int *handle)
15676 {
15677         struct intel_framebuffer *intel_fb = to_intel_framebuffer(fb);
15678         struct drm_i915_gem_object *obj = intel_fb->obj;
15679
15680         if (obj->userptr.mm) {
15681                 DRM_DEBUG("attempting to use a userptr for a framebuffer, denied\n");
15682                 return -EINVAL;
15683         }
15684
15685         return drm_gem_handle_create(file, &obj->base, handle);
15686 }
15687
15688 static int intel_user_framebuffer_dirty(struct drm_framebuffer *fb,
15689                                         struct drm_file *file,
15690                                         unsigned flags, unsigned color,
15691                                         struct drm_clip_rect *clips,
15692                                         unsigned num_clips)
15693 {
15694         struct drm_device *dev = fb->dev;
15695         struct intel_framebuffer *intel_fb = to_intel_framebuffer(fb);
15696         struct drm_i915_gem_object *obj = intel_fb->obj;
15697
15698         mutex_lock(&dev->struct_mutex);
15699         intel_fb_obj_flush(obj, false, ORIGIN_DIRTYFB);
15700         mutex_unlock(&dev->struct_mutex);
15701
15702         return 0;
15703 }
15704
15705 static const struct drm_framebuffer_funcs intel_fb_funcs = {
15706         .destroy = intel_user_framebuffer_destroy,
15707         .create_handle = intel_user_framebuffer_create_handle,
15708         .dirty = intel_user_framebuffer_dirty,
15709 };
15710
15711 static
15712 u32 intel_fb_pitch_limit(struct drm_i915_private *dev_priv,
15713                          uint64_t fb_modifier, uint32_t pixel_format)
15714 {
15715         u32 gen = INTEL_INFO(dev_priv)->gen;
15716
15717         if (gen >= 9) {
15718                 int cpp = drm_format_plane_cpp(pixel_format, 0);
15719
15720                 /* "The stride in bytes must not exceed the of the size of 8K
15721                  *  pixels and 32K bytes."
15722                  */
15723                 return min(8192 * cpp, 32768);
15724         } else if (gen >= 5 && !IS_VALLEYVIEW(dev_priv) &&
15725                    !IS_CHERRYVIEW(dev_priv)) {
15726                 return 32*1024;
15727         } else if (gen >= 4) {
15728                 if (fb_modifier == I915_FORMAT_MOD_X_TILED)
15729                         return 16*1024;
15730                 else
15731                         return 32*1024;
15732         } else if (gen >= 3) {
15733                 if (fb_modifier == I915_FORMAT_MOD_X_TILED)
15734                         return 8*1024;
15735                 else
15736                         return 16*1024;
15737         } else {
15738                 /* XXX DSPC is limited to 4k tiled */
15739                 return 8*1024;
15740         }
15741 }
15742
15743 static int intel_framebuffer_init(struct drm_device *dev,
15744                                   struct intel_framebuffer *intel_fb,
15745                                   struct drm_mode_fb_cmd2 *mode_cmd,
15746                                   struct drm_i915_gem_object *obj)
15747 {
15748         struct drm_i915_private *dev_priv = to_i915(dev);
15749         unsigned int tiling = i915_gem_object_get_tiling(obj);
15750         int ret;
15751         u32 pitch_limit, stride_alignment;
15752         char *format_name;
15753
15754         WARN_ON(!mutex_is_locked(&dev->struct_mutex));
15755
15756         if (mode_cmd->flags & DRM_MODE_FB_MODIFIERS) {
15757                 /*
15758                  * If there's a fence, enforce that
15759                  * the fb modifier and tiling mode match.
15760                  */
15761                 if (tiling != I915_TILING_NONE &&
15762                     tiling != intel_fb_modifier_to_tiling(mode_cmd->modifier[0])) {
15763                         DRM_DEBUG("tiling_mode doesn't match fb modifier\n");
15764                         return -EINVAL;
15765                 }
15766         } else {
15767                 if (tiling == I915_TILING_X) {
15768                         mode_cmd->modifier[0] = I915_FORMAT_MOD_X_TILED;
15769                 } else if (tiling == I915_TILING_Y) {
15770                         DRM_DEBUG("No Y tiling for legacy addfb\n");
15771                         return -EINVAL;
15772                 }
15773         }
15774
15775         /* Passed in modifier sanity checking. */
15776         switch (mode_cmd->modifier[0]) {
15777         case I915_FORMAT_MOD_Y_TILED:
15778         case I915_FORMAT_MOD_Yf_TILED:
15779                 if (INTEL_INFO(dev)->gen < 9) {
15780                         DRM_DEBUG("Unsupported tiling 0x%llx!\n",
15781                                   mode_cmd->modifier[0]);
15782                         return -EINVAL;
15783                 }
15784         case DRM_FORMAT_MOD_NONE:
15785         case I915_FORMAT_MOD_X_TILED:
15786                 break;
15787         default:
15788                 DRM_DEBUG("Unsupported fb modifier 0x%llx!\n",
15789                           mode_cmd->modifier[0]);
15790                 return -EINVAL;
15791         }
15792
15793         /*
15794          * gen2/3 display engine uses the fence if present,
15795          * so the tiling mode must match the fb modifier exactly.
15796          */
15797         if (INTEL_INFO(dev_priv)->gen < 4 &&
15798             tiling != intel_fb_modifier_to_tiling(mode_cmd->modifier[0])) {
15799                 DRM_DEBUG("tiling_mode must match fb modifier exactly on gen2/3\n");
15800                 return -EINVAL;
15801         }
15802
15803         stride_alignment = intel_fb_stride_alignment(dev_priv,
15804                                                      mode_cmd->modifier[0],
15805                                                      mode_cmd->pixel_format);
15806         if (mode_cmd->pitches[0] & (stride_alignment - 1)) {
15807                 DRM_DEBUG("pitch (%d) must be at least %u byte aligned\n",
15808                           mode_cmd->pitches[0], stride_alignment);
15809                 return -EINVAL;
15810         }
15811
15812         pitch_limit = intel_fb_pitch_limit(dev_priv, mode_cmd->modifier[0],
15813                                            mode_cmd->pixel_format);
15814         if (mode_cmd->pitches[0] > pitch_limit) {
15815                 DRM_DEBUG("%s pitch (%u) must be at less than %d\n",
15816                           mode_cmd->modifier[0] != DRM_FORMAT_MOD_NONE ?
15817                           "tiled" : "linear",
15818                           mode_cmd->pitches[0], pitch_limit);
15819                 return -EINVAL;
15820         }
15821
15822         /*
15823          * If there's a fence, enforce that
15824          * the fb pitch and fence stride match.
15825          */
15826         if (tiling != I915_TILING_NONE &&
15827             mode_cmd->pitches[0] != i915_gem_object_get_stride(obj)) {
15828                 DRM_DEBUG("pitch (%d) must match tiling stride (%d)\n",
15829                           mode_cmd->pitches[0],
15830                           i915_gem_object_get_stride(obj));
15831                 return -EINVAL;
15832         }
15833
15834         /* Reject formats not supported by any plane early. */
15835         switch (mode_cmd->pixel_format) {
15836         case DRM_FORMAT_C8:
15837         case DRM_FORMAT_RGB565:
15838         case DRM_FORMAT_XRGB8888:
15839         case DRM_FORMAT_ARGB8888:
15840                 break;
15841         case DRM_FORMAT_XRGB1555:
15842                 if (INTEL_INFO(dev)->gen > 3) {
15843                         format_name = drm_get_format_name(mode_cmd->pixel_format);
15844                         DRM_DEBUG("unsupported pixel format: %s\n", format_name);
15845                         kfree(format_name);
15846                         return -EINVAL;
15847                 }
15848                 break;
15849         case DRM_FORMAT_ABGR8888:
15850                 if (!IS_VALLEYVIEW(dev_priv) && !IS_CHERRYVIEW(dev_priv) &&
15851                     INTEL_INFO(dev)->gen < 9) {
15852                         format_name = drm_get_format_name(mode_cmd->pixel_format);
15853                         DRM_DEBUG("unsupported pixel format: %s\n", format_name);
15854                         kfree(format_name);
15855                         return -EINVAL;
15856                 }
15857                 break;
15858         case DRM_FORMAT_XBGR8888:
15859         case DRM_FORMAT_XRGB2101010:
15860         case DRM_FORMAT_XBGR2101010:
15861                 if (INTEL_INFO(dev)->gen < 4) {
15862                         format_name = drm_get_format_name(mode_cmd->pixel_format);
15863                         DRM_DEBUG("unsupported pixel format: %s\n", format_name);
15864                         kfree(format_name);
15865                         return -EINVAL;
15866                 }
15867                 break;
15868         case DRM_FORMAT_ABGR2101010:
15869                 if (!IS_VALLEYVIEW(dev_priv) && !IS_CHERRYVIEW(dev_priv)) {
15870                         format_name = drm_get_format_name(mode_cmd->pixel_format);
15871                         DRM_DEBUG("unsupported pixel format: %s\n", format_name);
15872                         kfree(format_name);
15873                         return -EINVAL;
15874                 }
15875                 break;
15876         case DRM_FORMAT_YUYV:
15877         case DRM_FORMAT_UYVY:
15878         case DRM_FORMAT_YVYU:
15879         case DRM_FORMAT_VYUY:
15880                 if (INTEL_INFO(dev)->gen < 5) {
15881                         format_name = drm_get_format_name(mode_cmd->pixel_format);
15882                         DRM_DEBUG("unsupported pixel format: %s\n", format_name);
15883                         kfree(format_name);
15884                         return -EINVAL;
15885                 }
15886                 break;
15887         default:
15888                 format_name = drm_get_format_name(mode_cmd->pixel_format);
15889                 DRM_DEBUG("unsupported pixel format: %s\n", format_name);
15890                 kfree(format_name);
15891                 return -EINVAL;
15892         }
15893
15894         /* FIXME need to adjust LINOFF/TILEOFF accordingly. */
15895         if (mode_cmd->offsets[0] != 0)
15896                 return -EINVAL;
15897
15898         drm_helper_mode_fill_fb_struct(&intel_fb->base, mode_cmd);
15899         intel_fb->obj = obj;
15900
15901         ret = intel_fill_fb_info(dev_priv, &intel_fb->base);
15902         if (ret)
15903                 return ret;
15904
15905         ret = drm_framebuffer_init(dev, &intel_fb->base, &intel_fb_funcs);
15906         if (ret) {
15907                 DRM_ERROR("framebuffer init failed %d\n", ret);
15908                 return ret;
15909         }
15910
15911         intel_fb->obj->framebuffer_references++;
15912
15913         return 0;
15914 }
15915
15916 static struct drm_framebuffer *
15917 intel_user_framebuffer_create(struct drm_device *dev,
15918                               struct drm_file *filp,
15919                               const struct drm_mode_fb_cmd2 *user_mode_cmd)
15920 {
15921         struct drm_framebuffer *fb;
15922         struct drm_i915_gem_object *obj;
15923         struct drm_mode_fb_cmd2 mode_cmd = *user_mode_cmd;
15924
15925         obj = i915_gem_object_lookup(filp, mode_cmd.handles[0]);
15926         if (!obj)
15927                 return ERR_PTR(-ENOENT);
15928
15929         fb = intel_framebuffer_create(dev, &mode_cmd, obj);
15930         if (IS_ERR(fb))
15931                 i915_gem_object_put_unlocked(obj);
15932
15933         return fb;
15934 }
15935
15936 static const struct drm_mode_config_funcs intel_mode_funcs = {
15937         .fb_create = intel_user_framebuffer_create,
15938         .output_poll_changed = intel_fbdev_output_poll_changed,
15939         .atomic_check = intel_atomic_check,
15940         .atomic_commit = intel_atomic_commit,
15941         .atomic_state_alloc = intel_atomic_state_alloc,
15942         .atomic_state_clear = intel_atomic_state_clear,
15943 };
15944
15945 /**
15946  * intel_init_display_hooks - initialize the display modesetting hooks
15947  * @dev_priv: device private
15948  */
15949 void intel_init_display_hooks(struct drm_i915_private *dev_priv)
15950 {
15951         if (INTEL_INFO(dev_priv)->gen >= 9) {
15952                 dev_priv->display.get_pipe_config = haswell_get_pipe_config;
15953                 dev_priv->display.get_initial_plane_config =
15954                         skylake_get_initial_plane_config;
15955                 dev_priv->display.crtc_compute_clock =
15956                         haswell_crtc_compute_clock;
15957                 dev_priv->display.crtc_enable = haswell_crtc_enable;
15958                 dev_priv->display.crtc_disable = haswell_crtc_disable;
15959         } else if (HAS_DDI(dev_priv)) {
15960                 dev_priv->display.get_pipe_config = haswell_get_pipe_config;
15961                 dev_priv->display.get_initial_plane_config =
15962                         ironlake_get_initial_plane_config;
15963                 dev_priv->display.crtc_compute_clock =
15964                         haswell_crtc_compute_clock;
15965                 dev_priv->display.crtc_enable = haswell_crtc_enable;
15966                 dev_priv->display.crtc_disable = haswell_crtc_disable;
15967         } else if (HAS_PCH_SPLIT(dev_priv)) {
15968                 dev_priv->display.get_pipe_config = ironlake_get_pipe_config;
15969                 dev_priv->display.get_initial_plane_config =
15970                         ironlake_get_initial_plane_config;
15971                 dev_priv->display.crtc_compute_clock =
15972                         ironlake_crtc_compute_clock;
15973                 dev_priv->display.crtc_enable = ironlake_crtc_enable;
15974                 dev_priv->display.crtc_disable = ironlake_crtc_disable;
15975         } else if (IS_CHERRYVIEW(dev_priv)) {
15976                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
15977                 dev_priv->display.get_initial_plane_config =
15978                         i9xx_get_initial_plane_config;
15979                 dev_priv->display.crtc_compute_clock = chv_crtc_compute_clock;
15980                 dev_priv->display.crtc_enable = valleyview_crtc_enable;
15981                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
15982         } else if (IS_VALLEYVIEW(dev_priv)) {
15983                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
15984                 dev_priv->display.get_initial_plane_config =
15985                         i9xx_get_initial_plane_config;
15986                 dev_priv->display.crtc_compute_clock = vlv_crtc_compute_clock;
15987                 dev_priv->display.crtc_enable = valleyview_crtc_enable;
15988                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
15989         } else if (IS_G4X(dev_priv)) {
15990                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
15991                 dev_priv->display.get_initial_plane_config =
15992                         i9xx_get_initial_plane_config;
15993                 dev_priv->display.crtc_compute_clock = g4x_crtc_compute_clock;
15994                 dev_priv->display.crtc_enable = i9xx_crtc_enable;
15995                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
15996         } else if (IS_PINEVIEW(dev_priv)) {
15997                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
15998                 dev_priv->display.get_initial_plane_config =
15999                         i9xx_get_initial_plane_config;
16000                 dev_priv->display.crtc_compute_clock = pnv_crtc_compute_clock;
16001                 dev_priv->display.crtc_enable = i9xx_crtc_enable;
16002                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
16003         } else if (!IS_GEN2(dev_priv)) {
16004                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
16005                 dev_priv->display.get_initial_plane_config =
16006                         i9xx_get_initial_plane_config;
16007                 dev_priv->display.crtc_compute_clock = i9xx_crtc_compute_clock;
16008                 dev_priv->display.crtc_enable = i9xx_crtc_enable;
16009                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
16010         } else {
16011                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
16012                 dev_priv->display.get_initial_plane_config =
16013                         i9xx_get_initial_plane_config;
16014                 dev_priv->display.crtc_compute_clock = i8xx_crtc_compute_clock;
16015                 dev_priv->display.crtc_enable = i9xx_crtc_enable;
16016                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
16017         }
16018
16019         /* Returns the core display clock speed */
16020         if (IS_SKYLAKE(dev_priv) || IS_KABYLAKE(dev_priv))
16021                 dev_priv->display.get_display_clock_speed =
16022                         skylake_get_display_clock_speed;
16023         else if (IS_BROXTON(dev_priv))
16024                 dev_priv->display.get_display_clock_speed =
16025                         broxton_get_display_clock_speed;
16026         else if (IS_BROADWELL(dev_priv))
16027                 dev_priv->display.get_display_clock_speed =
16028                         broadwell_get_display_clock_speed;
16029         else if (IS_HASWELL(dev_priv))
16030                 dev_priv->display.get_display_clock_speed =
16031                         haswell_get_display_clock_speed;
16032         else if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
16033                 dev_priv->display.get_display_clock_speed =
16034                         valleyview_get_display_clock_speed;
16035         else if (IS_GEN5(dev_priv))
16036                 dev_priv->display.get_display_clock_speed =
16037                         ilk_get_display_clock_speed;
16038         else if (IS_I945G(dev_priv) || IS_BROADWATER(dev_priv) ||
16039                  IS_GEN6(dev_priv) || IS_IVYBRIDGE(dev_priv))
16040                 dev_priv->display.get_display_clock_speed =
16041                         i945_get_display_clock_speed;
16042         else if (IS_GM45(dev_priv))
16043                 dev_priv->display.get_display_clock_speed =
16044                         gm45_get_display_clock_speed;
16045         else if (IS_CRESTLINE(dev_priv))
16046                 dev_priv->display.get_display_clock_speed =
16047                         i965gm_get_display_clock_speed;
16048         else if (IS_PINEVIEW(dev_priv))
16049                 dev_priv->display.get_display_clock_speed =
16050                         pnv_get_display_clock_speed;
16051         else if (IS_G33(dev_priv) || IS_G4X(dev_priv))
16052                 dev_priv->display.get_display_clock_speed =
16053                         g33_get_display_clock_speed;
16054         else if (IS_I915G(dev_priv))
16055                 dev_priv->display.get_display_clock_speed =
16056                         i915_get_display_clock_speed;
16057         else if (IS_I945GM(dev_priv) || IS_845G(dev_priv))
16058                 dev_priv->display.get_display_clock_speed =
16059                         i9xx_misc_get_display_clock_speed;
16060         else if (IS_I915GM(dev_priv))
16061                 dev_priv->display.get_display_clock_speed =
16062                         i915gm_get_display_clock_speed;
16063         else if (IS_I865G(dev_priv))
16064                 dev_priv->display.get_display_clock_speed =
16065                         i865_get_display_clock_speed;
16066         else if (IS_I85X(dev_priv))
16067                 dev_priv->display.get_display_clock_speed =
16068                         i85x_get_display_clock_speed;
16069         else { /* 830 */
16070                 WARN(!IS_I830(dev_priv), "Unknown platform. Assuming 133 MHz CDCLK\n");
16071                 dev_priv->display.get_display_clock_speed =
16072                         i830_get_display_clock_speed;
16073         }
16074
16075         if (IS_GEN5(dev_priv)) {
16076                 dev_priv->display.fdi_link_train = ironlake_fdi_link_train;
16077         } else if (IS_GEN6(dev_priv)) {
16078                 dev_priv->display.fdi_link_train = gen6_fdi_link_train;
16079         } else if (IS_IVYBRIDGE(dev_priv)) {
16080                 /* FIXME: detect B0+ stepping and use auto training */
16081                 dev_priv->display.fdi_link_train = ivb_manual_fdi_link_train;
16082         } else if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv)) {
16083                 dev_priv->display.fdi_link_train = hsw_fdi_link_train;
16084         }
16085
16086         if (IS_BROADWELL(dev_priv)) {
16087                 dev_priv->display.modeset_commit_cdclk =
16088                         broadwell_modeset_commit_cdclk;
16089                 dev_priv->display.modeset_calc_cdclk =
16090                         broadwell_modeset_calc_cdclk;
16091         } else if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv)) {
16092                 dev_priv->display.modeset_commit_cdclk =
16093                         valleyview_modeset_commit_cdclk;
16094                 dev_priv->display.modeset_calc_cdclk =
16095                         valleyview_modeset_calc_cdclk;
16096         } else if (IS_BROXTON(dev_priv)) {
16097                 dev_priv->display.modeset_commit_cdclk =
16098                         bxt_modeset_commit_cdclk;
16099                 dev_priv->display.modeset_calc_cdclk =
16100                         bxt_modeset_calc_cdclk;
16101         } else if (IS_SKYLAKE(dev_priv) || IS_KABYLAKE(dev_priv)) {
16102                 dev_priv->display.modeset_commit_cdclk =
16103                         skl_modeset_commit_cdclk;
16104                 dev_priv->display.modeset_calc_cdclk =
16105                         skl_modeset_calc_cdclk;
16106         }
16107
16108         if (dev_priv->info.gen >= 9)
16109                 dev_priv->display.update_crtcs = skl_update_crtcs;
16110         else
16111                 dev_priv->display.update_crtcs = intel_update_crtcs;
16112
16113         switch (INTEL_INFO(dev_priv)->gen) {
16114         case 2:
16115                 dev_priv->display.queue_flip = intel_gen2_queue_flip;
16116                 break;
16117
16118         case 3:
16119                 dev_priv->display.queue_flip = intel_gen3_queue_flip;
16120                 break;
16121
16122         case 4:
16123         case 5:
16124                 dev_priv->display.queue_flip = intel_gen4_queue_flip;
16125                 break;
16126
16127         case 6:
16128                 dev_priv->display.queue_flip = intel_gen6_queue_flip;
16129                 break;
16130         case 7:
16131         case 8: /* FIXME(BDW): Check that the gen8 RCS flip works. */
16132                 dev_priv->display.queue_flip = intel_gen7_queue_flip;
16133                 break;
16134         case 9:
16135                 /* Drop through - unsupported since execlist only. */
16136         default:
16137                 /* Default just returns -ENODEV to indicate unsupported */
16138                 dev_priv->display.queue_flip = intel_default_queue_flip;
16139         }
16140 }
16141
16142 /*
16143  * Some BIOSes insist on assuming the GPU's pipe A is enabled at suspend,
16144  * resume, or other times.  This quirk makes sure that's the case for
16145  * affected systems.
16146  */
16147 static void quirk_pipea_force(struct drm_device *dev)
16148 {
16149         struct drm_i915_private *dev_priv = to_i915(dev);
16150
16151         dev_priv->quirks |= QUIRK_PIPEA_FORCE;
16152         DRM_INFO("applying pipe a force quirk\n");
16153 }
16154
16155 static void quirk_pipeb_force(struct drm_device *dev)
16156 {
16157         struct drm_i915_private *dev_priv = to_i915(dev);
16158
16159         dev_priv->quirks |= QUIRK_PIPEB_FORCE;
16160         DRM_INFO("applying pipe b force quirk\n");
16161 }
16162
16163 /*
16164  * Some machines (Lenovo U160) do not work with SSC on LVDS for some reason
16165  */
16166 static void quirk_ssc_force_disable(struct drm_device *dev)
16167 {
16168         struct drm_i915_private *dev_priv = to_i915(dev);
16169         dev_priv->quirks |= QUIRK_LVDS_SSC_DISABLE;
16170         DRM_INFO("applying lvds SSC disable quirk\n");
16171 }
16172
16173 /*
16174  * A machine (e.g. Acer Aspire 5734Z) may need to invert the panel backlight
16175  * brightness value
16176  */
16177 static void quirk_invert_brightness(struct drm_device *dev)
16178 {
16179         struct drm_i915_private *dev_priv = to_i915(dev);
16180         dev_priv->quirks |= QUIRK_INVERT_BRIGHTNESS;
16181         DRM_INFO("applying inverted panel brightness quirk\n");
16182 }
16183
16184 /* Some VBT's incorrectly indicate no backlight is present */
16185 static void quirk_backlight_present(struct drm_device *dev)
16186 {
16187         struct drm_i915_private *dev_priv = to_i915(dev);
16188         dev_priv->quirks |= QUIRK_BACKLIGHT_PRESENT;
16189         DRM_INFO("applying backlight present quirk\n");
16190 }
16191
16192 struct intel_quirk {
16193         int device;
16194         int subsystem_vendor;
16195         int subsystem_device;
16196         void (*hook)(struct drm_device *dev);
16197 };
16198
16199 /* For systems that don't have a meaningful PCI subdevice/subvendor ID */
16200 struct intel_dmi_quirk {
16201         void (*hook)(struct drm_device *dev);
16202         const struct dmi_system_id (*dmi_id_list)[];
16203 };
16204
16205 static int intel_dmi_reverse_brightness(const struct dmi_system_id *id)
16206 {
16207         DRM_INFO("Backlight polarity reversed on %s\n", id->ident);
16208         return 1;
16209 }
16210
16211 static const struct intel_dmi_quirk intel_dmi_quirks[] = {
16212         {
16213                 .dmi_id_list = &(const struct dmi_system_id[]) {
16214                         {
16215                                 .callback = intel_dmi_reverse_brightness,
16216                                 .ident = "NCR Corporation",
16217                                 .matches = {DMI_MATCH(DMI_SYS_VENDOR, "NCR Corporation"),
16218                                             DMI_MATCH(DMI_PRODUCT_NAME, ""),
16219                                 },
16220                         },
16221                         { }  /* terminating entry */
16222                 },
16223                 .hook = quirk_invert_brightness,
16224         },
16225 };
16226
16227 static struct intel_quirk intel_quirks[] = {
16228         /* Toshiba Protege R-205, S-209 needs pipe A force quirk */
16229         { 0x2592, 0x1179, 0x0001, quirk_pipea_force },
16230
16231         /* ThinkPad T60 needs pipe A force quirk (bug #16494) */
16232         { 0x2782, 0x17aa, 0x201a, quirk_pipea_force },
16233
16234         /* 830 needs to leave pipe A & dpll A up */
16235         { 0x3577, PCI_ANY_ID, PCI_ANY_ID, quirk_pipea_force },
16236
16237         /* 830 needs to leave pipe B & dpll B up */
16238         { 0x3577, PCI_ANY_ID, PCI_ANY_ID, quirk_pipeb_force },
16239
16240         /* Lenovo U160 cannot use SSC on LVDS */
16241         { 0x0046, 0x17aa, 0x3920, quirk_ssc_force_disable },
16242
16243         /* Sony Vaio Y cannot use SSC on LVDS */
16244         { 0x0046, 0x104d, 0x9076, quirk_ssc_force_disable },
16245
16246         /* Acer Aspire 5734Z must invert backlight brightness */
16247         { 0x2a42, 0x1025, 0x0459, quirk_invert_brightness },
16248
16249         /* Acer/eMachines G725 */
16250         { 0x2a42, 0x1025, 0x0210, quirk_invert_brightness },
16251
16252         /* Acer/eMachines e725 */
16253         { 0x2a42, 0x1025, 0x0212, quirk_invert_brightness },
16254
16255         /* Acer/Packard Bell NCL20 */
16256         { 0x2a42, 0x1025, 0x034b, quirk_invert_brightness },
16257
16258         /* Acer Aspire 4736Z */
16259         { 0x2a42, 0x1025, 0x0260, quirk_invert_brightness },
16260
16261         /* Acer Aspire 5336 */
16262         { 0x2a42, 0x1025, 0x048a, quirk_invert_brightness },
16263
16264         /* Acer C720 and C720P Chromebooks (Celeron 2955U) have backlights */
16265         { 0x0a06, 0x1025, 0x0a11, quirk_backlight_present },
16266
16267         /* Acer C720 Chromebook (Core i3 4005U) */
16268         { 0x0a16, 0x1025, 0x0a11, quirk_backlight_present },
16269
16270         /* Apple Macbook 2,1 (Core 2 T7400) */
16271         { 0x27a2, 0x8086, 0x7270, quirk_backlight_present },
16272
16273         /* Apple Macbook 4,1 */
16274         { 0x2a02, 0x106b, 0x00a1, quirk_backlight_present },
16275
16276         /* Toshiba CB35 Chromebook (Celeron 2955U) */
16277         { 0x0a06, 0x1179, 0x0a88, quirk_backlight_present },
16278
16279         /* HP Chromebook 14 (Celeron 2955U) */
16280         { 0x0a06, 0x103c, 0x21ed, quirk_backlight_present },
16281
16282         /* Dell Chromebook 11 */
16283         { 0x0a06, 0x1028, 0x0a35, quirk_backlight_present },
16284
16285         /* Dell Chromebook 11 (2015 version) */
16286         { 0x0a16, 0x1028, 0x0a35, quirk_backlight_present },
16287 };
16288
16289 static void intel_init_quirks(struct drm_device *dev)
16290 {
16291         struct pci_dev *d = dev->pdev;
16292         int i;
16293
16294         for (i = 0; i < ARRAY_SIZE(intel_quirks); i++) {
16295                 struct intel_quirk *q = &intel_quirks[i];
16296
16297                 if (d->device == q->device &&
16298                     (d->subsystem_vendor == q->subsystem_vendor ||
16299                      q->subsystem_vendor == PCI_ANY_ID) &&
16300                     (d->subsystem_device == q->subsystem_device ||
16301                      q->subsystem_device == PCI_ANY_ID))
16302                         q->hook(dev);
16303         }
16304         for (i = 0; i < ARRAY_SIZE(intel_dmi_quirks); i++) {
16305                 if (dmi_check_system(*intel_dmi_quirks[i].dmi_id_list) != 0)
16306                         intel_dmi_quirks[i].hook(dev);
16307         }
16308 }
16309
16310 /* Disable the VGA plane that we never use */
16311 static void i915_disable_vga(struct drm_device *dev)
16312 {
16313         struct drm_i915_private *dev_priv = to_i915(dev);
16314         struct pci_dev *pdev = dev_priv->drm.pdev;
16315         u8 sr1;
16316         i915_reg_t vga_reg = i915_vgacntrl_reg(dev_priv);
16317
16318         /* WaEnableVGAAccessThroughIOPort:ctg,elk,ilk,snb,ivb,vlv,hsw */
16319         vga_get_uninterruptible(pdev, VGA_RSRC_LEGACY_IO);
16320         outb(SR01, VGA_SR_INDEX);
16321         sr1 = inb(VGA_SR_DATA);
16322         outb(sr1 | 1<<5, VGA_SR_DATA);
16323         vga_put(pdev, VGA_RSRC_LEGACY_IO);
16324         udelay(300);
16325
16326         I915_WRITE(vga_reg, VGA_DISP_DISABLE);
16327         POSTING_READ(vga_reg);
16328 }
16329
16330 void intel_modeset_init_hw(struct drm_device *dev)
16331 {
16332         struct drm_i915_private *dev_priv = to_i915(dev);
16333
16334         intel_update_cdclk(dev);
16335
16336         dev_priv->atomic_cdclk_freq = dev_priv->cdclk_freq;
16337
16338         intel_init_clock_gating(dev);
16339 }
16340
16341 /*
16342  * Calculate what we think the watermarks should be for the state we've read
16343  * out of the hardware and then immediately program those watermarks so that
16344  * we ensure the hardware settings match our internal state.
16345  *
16346  * We can calculate what we think WM's should be by creating a duplicate of the
16347  * current state (which was constructed during hardware readout) and running it
16348  * through the atomic check code to calculate new watermark values in the
16349  * state object.
16350  */
16351 static void sanitize_watermarks(struct drm_device *dev)
16352 {
16353         struct drm_i915_private *dev_priv = to_i915(dev);
16354         struct drm_atomic_state *state;
16355         struct drm_crtc *crtc;
16356         struct drm_crtc_state *cstate;
16357         struct drm_modeset_acquire_ctx ctx;
16358         int ret;
16359         int i;
16360
16361         /* Only supported on platforms that use atomic watermark design */
16362         if (!dev_priv->display.optimize_watermarks)
16363                 return;
16364
16365         /*
16366          * We need to hold connection_mutex before calling duplicate_state so
16367          * that the connector loop is protected.
16368          */
16369         drm_modeset_acquire_init(&ctx, 0);
16370 retry:
16371         ret = drm_modeset_lock_all_ctx(dev, &ctx);
16372         if (ret == -EDEADLK) {
16373                 drm_modeset_backoff(&ctx);
16374                 goto retry;
16375         } else if (WARN_ON(ret)) {
16376                 goto fail;
16377         }
16378
16379         state = drm_atomic_helper_duplicate_state(dev, &ctx);
16380         if (WARN_ON(IS_ERR(state)))
16381                 goto fail;
16382
16383         /*
16384          * Hardware readout is the only time we don't want to calculate
16385          * intermediate watermarks (since we don't trust the current
16386          * watermarks).
16387          */
16388         to_intel_atomic_state(state)->skip_intermediate_wm = true;
16389
16390         ret = intel_atomic_check(dev, state);
16391         if (ret) {
16392                 /*
16393                  * If we fail here, it means that the hardware appears to be
16394                  * programmed in a way that shouldn't be possible, given our
16395                  * understanding of watermark requirements.  This might mean a
16396                  * mistake in the hardware readout code or a mistake in the
16397                  * watermark calculations for a given platform.  Raise a WARN
16398                  * so that this is noticeable.
16399                  *
16400                  * If this actually happens, we'll have to just leave the
16401                  * BIOS-programmed watermarks untouched and hope for the best.
16402                  */
16403                 WARN(true, "Could not determine valid watermarks for inherited state\n");
16404                 goto put_state;
16405         }
16406
16407         /* Write calculated watermark values back */
16408         for_each_crtc_in_state(state, crtc, cstate, i) {
16409                 struct intel_crtc_state *cs = to_intel_crtc_state(cstate);
16410
16411                 cs->wm.need_postvbl_update = true;
16412                 dev_priv->display.optimize_watermarks(cs);
16413         }
16414
16415 put_state:
16416         drm_atomic_state_put(state);
16417 fail:
16418         drm_modeset_drop_locks(&ctx);
16419         drm_modeset_acquire_fini(&ctx);
16420 }
16421
16422 void intel_modeset_init(struct drm_device *dev)
16423 {
16424         struct drm_i915_private *dev_priv = to_i915(dev);
16425         struct i915_ggtt *ggtt = &dev_priv->ggtt;
16426         int sprite, ret;
16427         enum pipe pipe;
16428         struct intel_crtc *crtc;
16429
16430         drm_mode_config_init(dev);
16431
16432         dev->mode_config.min_width = 0;
16433         dev->mode_config.min_height = 0;
16434
16435         dev->mode_config.preferred_depth = 24;
16436         dev->mode_config.prefer_shadow = 1;
16437
16438         dev->mode_config.allow_fb_modifiers = true;
16439
16440         dev->mode_config.funcs = &intel_mode_funcs;
16441
16442         intel_init_quirks(dev);
16443
16444         intel_init_pm(dev);
16445
16446         if (INTEL_INFO(dev)->num_pipes == 0)
16447                 return;
16448
16449         /*
16450          * There may be no VBT; and if the BIOS enabled SSC we can
16451          * just keep using it to avoid unnecessary flicker.  Whereas if the
16452          * BIOS isn't using it, don't assume it will work even if the VBT
16453          * indicates as much.
16454          */
16455         if (HAS_PCH_IBX(dev_priv) || HAS_PCH_CPT(dev_priv)) {
16456                 bool bios_lvds_use_ssc = !!(I915_READ(PCH_DREF_CONTROL) &
16457                                             DREF_SSC1_ENABLE);
16458
16459                 if (dev_priv->vbt.lvds_use_ssc != bios_lvds_use_ssc) {
16460                         DRM_DEBUG_KMS("SSC %sabled by BIOS, overriding VBT which says %sabled\n",
16461                                      bios_lvds_use_ssc ? "en" : "dis",
16462                                      dev_priv->vbt.lvds_use_ssc ? "en" : "dis");
16463                         dev_priv->vbt.lvds_use_ssc = bios_lvds_use_ssc;
16464                 }
16465         }
16466
16467         if (IS_GEN2(dev_priv)) {
16468                 dev->mode_config.max_width = 2048;
16469                 dev->mode_config.max_height = 2048;
16470         } else if (IS_GEN3(dev_priv)) {
16471                 dev->mode_config.max_width = 4096;
16472                 dev->mode_config.max_height = 4096;
16473         } else {
16474                 dev->mode_config.max_width = 8192;
16475                 dev->mode_config.max_height = 8192;
16476         }
16477
16478         if (IS_845G(dev_priv) || IS_I865G(dev_priv)) {
16479                 dev->mode_config.cursor_width = IS_845G(dev_priv) ? 64 : 512;
16480                 dev->mode_config.cursor_height = 1023;
16481         } else if (IS_GEN2(dev_priv)) {
16482                 dev->mode_config.cursor_width = GEN2_CURSOR_WIDTH;
16483                 dev->mode_config.cursor_height = GEN2_CURSOR_HEIGHT;
16484         } else {
16485                 dev->mode_config.cursor_width = MAX_CURSOR_WIDTH;
16486                 dev->mode_config.cursor_height = MAX_CURSOR_HEIGHT;
16487         }
16488
16489         dev->mode_config.fb_base = ggtt->mappable_base;
16490
16491         DRM_DEBUG_KMS("%d display pipe%s available.\n",
16492                       INTEL_INFO(dev)->num_pipes,
16493                       INTEL_INFO(dev)->num_pipes > 1 ? "s" : "");
16494
16495         for_each_pipe(dev_priv, pipe) {
16496                 intel_crtc_init(dev, pipe);
16497                 for_each_sprite(dev_priv, pipe, sprite) {
16498                         ret = intel_plane_init(dev, pipe, sprite);
16499                         if (ret)
16500                                 DRM_DEBUG_KMS("pipe %c sprite %c init failed: %d\n",
16501                                               pipe_name(pipe), sprite_name(pipe, sprite), ret);
16502                 }
16503         }
16504
16505         intel_update_czclk(dev_priv);
16506         intel_update_cdclk(dev);
16507
16508         intel_shared_dpll_init(dev);
16509
16510         if (dev_priv->max_cdclk_freq == 0)
16511                 intel_update_max_cdclk(dev);
16512
16513         /* Just disable it once at startup */
16514         i915_disable_vga(dev);
16515         intel_setup_outputs(dev);
16516
16517         drm_modeset_lock_all(dev);
16518         intel_modeset_setup_hw_state(dev);
16519         drm_modeset_unlock_all(dev);
16520
16521         for_each_intel_crtc(dev, crtc) {
16522                 struct intel_initial_plane_config plane_config = {};
16523
16524                 if (!crtc->active)
16525                         continue;
16526
16527                 /*
16528                  * Note that reserving the BIOS fb up front prevents us
16529                  * from stuffing other stolen allocations like the ring
16530                  * on top.  This prevents some ugliness at boot time, and
16531                  * can even allow for smooth boot transitions if the BIOS
16532                  * fb is large enough for the active pipe configuration.
16533                  */
16534                 dev_priv->display.get_initial_plane_config(crtc,
16535                                                            &plane_config);
16536
16537                 /*
16538                  * If the fb is shared between multiple heads, we'll
16539                  * just get the first one.
16540                  */
16541                 intel_find_initial_plane_obj(crtc, &plane_config);
16542         }
16543
16544         /*
16545          * Make sure hardware watermarks really match the state we read out.
16546          * Note that we need to do this after reconstructing the BIOS fb's
16547          * since the watermark calculation done here will use pstate->fb.
16548          */
16549         sanitize_watermarks(dev);
16550 }
16551
16552 static void intel_enable_pipe_a(struct drm_device *dev)
16553 {
16554         struct intel_connector *connector;
16555         struct drm_connector *crt = NULL;
16556         struct intel_load_detect_pipe load_detect_temp;
16557         struct drm_modeset_acquire_ctx *ctx = dev->mode_config.acquire_ctx;
16558
16559         /* We can't just switch on the pipe A, we need to set things up with a
16560          * proper mode and output configuration. As a gross hack, enable pipe A
16561          * by enabling the load detect pipe once. */
16562         for_each_intel_connector(dev, connector) {
16563                 if (connector->encoder->type == INTEL_OUTPUT_ANALOG) {
16564                         crt = &connector->base;
16565                         break;
16566                 }
16567         }
16568
16569         if (!crt)
16570                 return;
16571
16572         if (intel_get_load_detect_pipe(crt, NULL, &load_detect_temp, ctx))
16573                 intel_release_load_detect_pipe(crt, &load_detect_temp, ctx);
16574 }
16575
16576 static bool
16577 intel_check_plane_mapping(struct intel_crtc *crtc)
16578 {
16579         struct drm_device *dev = crtc->base.dev;
16580         struct drm_i915_private *dev_priv = to_i915(dev);
16581         u32 val;
16582
16583         if (INTEL_INFO(dev)->num_pipes == 1)
16584                 return true;
16585
16586         val = I915_READ(DSPCNTR(!crtc->plane));
16587
16588         if ((val & DISPLAY_PLANE_ENABLE) &&
16589             (!!(val & DISPPLANE_SEL_PIPE_MASK) == crtc->pipe))
16590                 return false;
16591
16592         return true;
16593 }
16594
16595 static bool intel_crtc_has_encoders(struct intel_crtc *crtc)
16596 {
16597         struct drm_device *dev = crtc->base.dev;
16598         struct intel_encoder *encoder;
16599
16600         for_each_encoder_on_crtc(dev, &crtc->base, encoder)
16601                 return true;
16602
16603         return false;
16604 }
16605
16606 static struct intel_connector *intel_encoder_find_connector(struct intel_encoder *encoder)
16607 {
16608         struct drm_device *dev = encoder->base.dev;
16609         struct intel_connector *connector;
16610
16611         for_each_connector_on_encoder(dev, &encoder->base, connector)
16612                 return connector;
16613
16614         return NULL;
16615 }
16616
16617 static bool has_pch_trancoder(struct drm_i915_private *dev_priv,
16618                               enum transcoder pch_transcoder)
16619 {
16620         return HAS_PCH_IBX(dev_priv) || HAS_PCH_CPT(dev_priv) ||
16621                 (HAS_PCH_LPT_H(dev_priv) && pch_transcoder == TRANSCODER_A);
16622 }
16623
16624 static void intel_sanitize_crtc(struct intel_crtc *crtc)
16625 {
16626         struct drm_device *dev = crtc->base.dev;
16627         struct drm_i915_private *dev_priv = to_i915(dev);
16628         enum transcoder cpu_transcoder = crtc->config->cpu_transcoder;
16629
16630         /* Clear any frame start delays used for debugging left by the BIOS */
16631         if (!transcoder_is_dsi(cpu_transcoder)) {
16632                 i915_reg_t reg = PIPECONF(cpu_transcoder);
16633
16634                 I915_WRITE(reg,
16635                            I915_READ(reg) & ~PIPECONF_FRAME_START_DELAY_MASK);
16636         }
16637
16638         /* restore vblank interrupts to correct state */
16639         drm_crtc_vblank_reset(&crtc->base);
16640         if (crtc->active) {
16641                 struct intel_plane *plane;
16642
16643                 drm_crtc_vblank_on(&crtc->base);
16644
16645                 /* Disable everything but the primary plane */
16646                 for_each_intel_plane_on_crtc(dev, crtc, plane) {
16647                         if (plane->base.type == DRM_PLANE_TYPE_PRIMARY)
16648                                 continue;
16649
16650                         plane->disable_plane(&plane->base, &crtc->base);
16651                 }
16652         }
16653
16654         /* We need to sanitize the plane -> pipe mapping first because this will
16655          * disable the crtc (and hence change the state) if it is wrong. Note
16656          * that gen4+ has a fixed plane -> pipe mapping.  */
16657         if (INTEL_INFO(dev)->gen < 4 && !intel_check_plane_mapping(crtc)) {
16658                 bool plane;
16659
16660                 DRM_DEBUG_KMS("[CRTC:%d:%s] wrong plane connection detected!\n",
16661                               crtc->base.base.id, crtc->base.name);
16662
16663                 /* Pipe has the wrong plane attached and the plane is active.
16664                  * Temporarily change the plane mapping and disable everything
16665                  * ...  */
16666                 plane = crtc->plane;
16667                 to_intel_plane_state(crtc->base.primary->state)->base.visible = true;
16668                 crtc->plane = !plane;
16669                 intel_crtc_disable_noatomic(&crtc->base);
16670                 crtc->plane = plane;
16671         }
16672
16673         if (dev_priv->quirks & QUIRK_PIPEA_FORCE &&
16674             crtc->pipe == PIPE_A && !crtc->active) {
16675                 /* BIOS forgot to enable pipe A, this mostly happens after
16676                  * resume. Force-enable the pipe to fix this, the update_dpms
16677                  * call below we restore the pipe to the right state, but leave
16678                  * the required bits on. */
16679                 intel_enable_pipe_a(dev);
16680         }
16681
16682         /* Adjust the state of the output pipe according to whether we
16683          * have active connectors/encoders. */
16684         if (crtc->active && !intel_crtc_has_encoders(crtc))
16685                 intel_crtc_disable_noatomic(&crtc->base);
16686
16687         if (crtc->active || HAS_GMCH_DISPLAY(dev_priv)) {
16688                 /*
16689                  * We start out with underrun reporting disabled to avoid races.
16690                  * For correct bookkeeping mark this on active crtcs.
16691                  *
16692                  * Also on gmch platforms we dont have any hardware bits to
16693                  * disable the underrun reporting. Which means we need to start
16694                  * out with underrun reporting disabled also on inactive pipes,
16695                  * since otherwise we'll complain about the garbage we read when
16696                  * e.g. coming up after runtime pm.
16697                  *
16698                  * No protection against concurrent access is required - at
16699                  * worst a fifo underrun happens which also sets this to false.
16700                  */
16701                 crtc->cpu_fifo_underrun_disabled = true;
16702                 /*
16703                  * We track the PCH trancoder underrun reporting state
16704                  * within the crtc. With crtc for pipe A housing the underrun
16705                  * reporting state for PCH transcoder A, crtc for pipe B housing
16706                  * it for PCH transcoder B, etc. LPT-H has only PCH transcoder A,
16707                  * and marking underrun reporting as disabled for the non-existing
16708                  * PCH transcoders B and C would prevent enabling the south
16709                  * error interrupt (see cpt_can_enable_serr_int()).
16710                  */
16711                 if (has_pch_trancoder(dev_priv, (enum transcoder)crtc->pipe))
16712                         crtc->pch_fifo_underrun_disabled = true;
16713         }
16714 }
16715
16716 static void intel_sanitize_encoder(struct intel_encoder *encoder)
16717 {
16718         struct intel_connector *connector;
16719
16720         /* We need to check both for a crtc link (meaning that the
16721          * encoder is active and trying to read from a pipe) and the
16722          * pipe itself being active. */
16723         bool has_active_crtc = encoder->base.crtc &&
16724                 to_intel_crtc(encoder->base.crtc)->active;
16725
16726         connector = intel_encoder_find_connector(encoder);
16727         if (connector && !has_active_crtc) {
16728                 DRM_DEBUG_KMS("[ENCODER:%d:%s] has active connectors but no active pipe!\n",
16729                               encoder->base.base.id,
16730                               encoder->base.name);
16731
16732                 /* Connector is active, but has no active pipe. This is
16733                  * fallout from our resume register restoring. Disable
16734                  * the encoder manually again. */
16735                 if (encoder->base.crtc) {
16736                         struct drm_crtc_state *crtc_state = encoder->base.crtc->state;
16737
16738                         DRM_DEBUG_KMS("[ENCODER:%d:%s] manually disabled\n",
16739                                       encoder->base.base.id,
16740                                       encoder->base.name);
16741                         encoder->disable(encoder, to_intel_crtc_state(crtc_state), connector->base.state);
16742                         if (encoder->post_disable)
16743                                 encoder->post_disable(encoder, to_intel_crtc_state(crtc_state), connector->base.state);
16744                 }
16745                 encoder->base.crtc = NULL;
16746
16747                 /* Inconsistent output/port/pipe state happens presumably due to
16748                  * a bug in one of the get_hw_state functions. Or someplace else
16749                  * in our code, like the register restore mess on resume. Clamp
16750                  * things to off as a safer default. */
16751
16752                 connector->base.dpms = DRM_MODE_DPMS_OFF;
16753                 connector->base.encoder = NULL;
16754         }
16755         /* Enabled encoders without active connectors will be fixed in
16756          * the crtc fixup. */
16757 }
16758
16759 void i915_redisable_vga_power_on(struct drm_device *dev)
16760 {
16761         struct drm_i915_private *dev_priv = to_i915(dev);
16762         i915_reg_t vga_reg = i915_vgacntrl_reg(dev_priv);
16763
16764         if (!(I915_READ(vga_reg) & VGA_DISP_DISABLE)) {
16765                 DRM_DEBUG_KMS("Something enabled VGA plane, disabling it\n");
16766                 i915_disable_vga(dev);
16767         }
16768 }
16769
16770 void i915_redisable_vga(struct drm_device *dev)
16771 {
16772         struct drm_i915_private *dev_priv = to_i915(dev);
16773
16774         /* This function can be called both from intel_modeset_setup_hw_state or
16775          * at a very early point in our resume sequence, where the power well
16776          * structures are not yet restored. Since this function is at a very
16777          * paranoid "someone might have enabled VGA while we were not looking"
16778          * level, just check if the power well is enabled instead of trying to
16779          * follow the "don't touch the power well if we don't need it" policy
16780          * the rest of the driver uses. */
16781         if (!intel_display_power_get_if_enabled(dev_priv, POWER_DOMAIN_VGA))
16782                 return;
16783
16784         i915_redisable_vga_power_on(dev);
16785
16786         intel_display_power_put(dev_priv, POWER_DOMAIN_VGA);
16787 }
16788
16789 static bool primary_get_hw_state(struct intel_plane *plane)
16790 {
16791         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
16792
16793         return I915_READ(DSPCNTR(plane->plane)) & DISPLAY_PLANE_ENABLE;
16794 }
16795
16796 /* FIXME read out full plane state for all planes */
16797 static void readout_plane_state(struct intel_crtc *crtc)
16798 {
16799         struct drm_plane *primary = crtc->base.primary;
16800         struct intel_plane_state *plane_state =
16801                 to_intel_plane_state(primary->state);
16802
16803         plane_state->base.visible = crtc->active &&
16804                 primary_get_hw_state(to_intel_plane(primary));
16805
16806         if (plane_state->base.visible)
16807                 crtc->base.state->plane_mask |= 1 << drm_plane_index(primary);
16808 }
16809
16810 static void intel_modeset_readout_hw_state(struct drm_device *dev)
16811 {
16812         struct drm_i915_private *dev_priv = to_i915(dev);
16813         enum pipe pipe;
16814         struct intel_crtc *crtc;
16815         struct intel_encoder *encoder;
16816         struct intel_connector *connector;
16817         int i;
16818
16819         dev_priv->active_crtcs = 0;
16820
16821         for_each_intel_crtc(dev, crtc) {
16822                 struct intel_crtc_state *crtc_state = crtc->config;
16823                 int pixclk = 0;
16824
16825                 __drm_atomic_helper_crtc_destroy_state(&crtc_state->base);
16826                 memset(crtc_state, 0, sizeof(*crtc_state));
16827                 crtc_state->base.crtc = &crtc->base;
16828
16829                 crtc_state->base.active = crtc_state->base.enable =
16830                         dev_priv->display.get_pipe_config(crtc, crtc_state);
16831
16832                 crtc->base.enabled = crtc_state->base.enable;
16833                 crtc->active = crtc_state->base.active;
16834
16835                 if (crtc_state->base.active) {
16836                         dev_priv->active_crtcs |= 1 << crtc->pipe;
16837
16838                         if (INTEL_GEN(dev_priv) >= 9 || IS_BROADWELL(dev_priv))
16839                                 pixclk = ilk_pipe_pixel_rate(crtc_state);
16840                         else if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
16841                                 pixclk = crtc_state->base.adjusted_mode.crtc_clock;
16842                         else
16843                                 WARN_ON(dev_priv->display.modeset_calc_cdclk);
16844
16845                         /* pixel rate mustn't exceed 95% of cdclk with IPS on BDW */
16846                         if (IS_BROADWELL(dev_priv) && crtc_state->ips_enabled)
16847                                 pixclk = DIV_ROUND_UP(pixclk * 100, 95);
16848                 }
16849
16850                 dev_priv->min_pixclk[crtc->pipe] = pixclk;
16851
16852                 readout_plane_state(crtc);
16853
16854                 DRM_DEBUG_KMS("[CRTC:%d:%s] hw state readout: %s\n",
16855                               crtc->base.base.id, crtc->base.name,
16856                               crtc->active ? "enabled" : "disabled");
16857         }
16858
16859         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
16860                 struct intel_shared_dpll *pll = &dev_priv->shared_dplls[i];
16861
16862                 pll->on = pll->funcs.get_hw_state(dev_priv, pll,
16863                                                   &pll->config.hw_state);
16864                 pll->config.crtc_mask = 0;
16865                 for_each_intel_crtc(dev, crtc) {
16866                         if (crtc->active && crtc->config->shared_dpll == pll)
16867                                 pll->config.crtc_mask |= 1 << crtc->pipe;
16868                 }
16869                 pll->active_mask = pll->config.crtc_mask;
16870
16871                 DRM_DEBUG_KMS("%s hw state readout: crtc_mask 0x%08x, on %i\n",
16872                               pll->name, pll->config.crtc_mask, pll->on);
16873         }
16874
16875         for_each_intel_encoder(dev, encoder) {
16876                 pipe = 0;
16877
16878                 if (encoder->get_hw_state(encoder, &pipe)) {
16879                         crtc = to_intel_crtc(dev_priv->pipe_to_crtc_mapping[pipe]);
16880                         encoder->base.crtc = &crtc->base;
16881                         crtc->config->output_types |= 1 << encoder->type;
16882                         encoder->get_config(encoder, crtc->config);
16883                 } else {
16884                         encoder->base.crtc = NULL;
16885                 }
16886
16887                 DRM_DEBUG_KMS("[ENCODER:%d:%s] hw state readout: %s, pipe %c\n",
16888                               encoder->base.base.id,
16889                               encoder->base.name,
16890                               encoder->base.crtc ? "enabled" : "disabled",
16891                               pipe_name(pipe));
16892         }
16893
16894         for_each_intel_connector(dev, connector) {
16895                 if (connector->get_hw_state(connector)) {
16896                         connector->base.dpms = DRM_MODE_DPMS_ON;
16897
16898                         encoder = connector->encoder;
16899                         connector->base.encoder = &encoder->base;
16900
16901                         if (encoder->base.crtc &&
16902                             encoder->base.crtc->state->active) {
16903                                 /*
16904                                  * This has to be done during hardware readout
16905                                  * because anything calling .crtc_disable may
16906                                  * rely on the connector_mask being accurate.
16907                                  */
16908                                 encoder->base.crtc->state->connector_mask |=
16909                                         1 << drm_connector_index(&connector->base);
16910                                 encoder->base.crtc->state->encoder_mask |=
16911                                         1 << drm_encoder_index(&encoder->base);
16912                         }
16913
16914                 } else {
16915                         connector->base.dpms = DRM_MODE_DPMS_OFF;
16916                         connector->base.encoder = NULL;
16917                 }
16918                 DRM_DEBUG_KMS("[CONNECTOR:%d:%s] hw state readout: %s\n",
16919                               connector->base.base.id,
16920                               connector->base.name,
16921                               connector->base.encoder ? "enabled" : "disabled");
16922         }
16923
16924         for_each_intel_crtc(dev, crtc) {
16925                 crtc->base.hwmode = crtc->config->base.adjusted_mode;
16926
16927                 memset(&crtc->base.mode, 0, sizeof(crtc->base.mode));
16928                 if (crtc->base.state->active) {
16929                         intel_mode_from_pipe_config(&crtc->base.mode, crtc->config);
16930                         intel_mode_from_pipe_config(&crtc->base.state->adjusted_mode, crtc->config);
16931                         WARN_ON(drm_atomic_set_mode_for_crtc(crtc->base.state, &crtc->base.mode));
16932
16933                         /*
16934                          * The initial mode needs to be set in order to keep
16935                          * the atomic core happy. It wants a valid mode if the
16936                          * crtc's enabled, so we do the above call.
16937                          *
16938                          * At this point some state updated by the connectors
16939                          * in their ->detect() callback has not run yet, so
16940                          * no recalculation can be done yet.
16941                          *
16942                          * Even if we could do a recalculation and modeset
16943                          * right now it would cause a double modeset if
16944                          * fbdev or userspace chooses a different initial mode.
16945                          *
16946                          * If that happens, someone indicated they wanted a
16947                          * mode change, which means it's safe to do a full
16948                          * recalculation.
16949                          */
16950                         crtc->base.state->mode.private_flags = I915_MODE_FLAG_INHERITED;
16951
16952                         drm_calc_timestamping_constants(&crtc->base, &crtc->base.hwmode);
16953                         update_scanline_offset(crtc);
16954                 }
16955
16956                 intel_pipe_config_sanity_check(dev_priv, crtc->config);
16957         }
16958 }
16959
16960 /* Scan out the current hw modeset state,
16961  * and sanitizes it to the current state
16962  */
16963 static void
16964 intel_modeset_setup_hw_state(struct drm_device *dev)
16965 {
16966         struct drm_i915_private *dev_priv = to_i915(dev);
16967         enum pipe pipe;
16968         struct intel_crtc *crtc;
16969         struct intel_encoder *encoder;
16970         int i;
16971
16972         intel_modeset_readout_hw_state(dev);
16973
16974         /* HW state is read out, now we need to sanitize this mess. */
16975         for_each_intel_encoder(dev, encoder) {
16976                 intel_sanitize_encoder(encoder);
16977         }
16978
16979         for_each_pipe(dev_priv, pipe) {
16980                 crtc = to_intel_crtc(dev_priv->pipe_to_crtc_mapping[pipe]);
16981                 intel_sanitize_crtc(crtc);
16982                 intel_dump_pipe_config(crtc, crtc->config,
16983                                        "[setup_hw_state]");
16984         }
16985
16986         intel_modeset_update_connector_atomic_state(dev);
16987
16988         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
16989                 struct intel_shared_dpll *pll = &dev_priv->shared_dplls[i];
16990
16991                 if (!pll->on || pll->active_mask)
16992                         continue;
16993
16994                 DRM_DEBUG_KMS("%s enabled but not in use, disabling\n", pll->name);
16995
16996                 pll->funcs.disable(dev_priv, pll);
16997                 pll->on = false;
16998         }
16999
17000         if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
17001                 vlv_wm_get_hw_state(dev);
17002         else if (IS_GEN9(dev_priv))
17003                 skl_wm_get_hw_state(dev);
17004         else if (HAS_PCH_SPLIT(dev_priv))
17005                 ilk_wm_get_hw_state(dev);
17006
17007         for_each_intel_crtc(dev, crtc) {
17008                 unsigned long put_domains;
17009
17010                 put_domains = modeset_get_crtc_power_domains(&crtc->base, crtc->config);
17011                 if (WARN_ON(put_domains))
17012                         modeset_put_power_domains(dev_priv, put_domains);
17013         }
17014         intel_display_set_init_power(dev_priv, false);
17015
17016         intel_fbc_init_pipe_state(dev_priv);
17017 }
17018
17019 void intel_display_resume(struct drm_device *dev)
17020 {
17021         struct drm_i915_private *dev_priv = to_i915(dev);
17022         struct drm_atomic_state *state = dev_priv->modeset_restore_state;
17023         struct drm_modeset_acquire_ctx ctx;
17024         int ret;
17025
17026         dev_priv->modeset_restore_state = NULL;
17027         if (state)
17028                 state->acquire_ctx = &ctx;
17029
17030         /*
17031          * This is a cludge because with real atomic modeset mode_config.mutex
17032          * won't be taken. Unfortunately some probed state like
17033          * audio_codec_enable is still protected by mode_config.mutex, so lock
17034          * it here for now.
17035          */
17036         mutex_lock(&dev->mode_config.mutex);
17037         drm_modeset_acquire_init(&ctx, 0);
17038
17039         while (1) {
17040                 ret = drm_modeset_lock_all_ctx(dev, &ctx);
17041                 if (ret != -EDEADLK)
17042                         break;
17043
17044                 drm_modeset_backoff(&ctx);
17045         }
17046
17047         if (!ret)
17048                 ret = __intel_display_resume(dev, state);
17049
17050         drm_modeset_drop_locks(&ctx);
17051         drm_modeset_acquire_fini(&ctx);
17052         mutex_unlock(&dev->mode_config.mutex);
17053
17054         if (ret)
17055                 DRM_ERROR("Restoring old state failed with %i\n", ret);
17056         drm_atomic_state_put(state);
17057 }
17058
17059 void intel_modeset_gem_init(struct drm_device *dev)
17060 {
17061         struct drm_i915_private *dev_priv = to_i915(dev);
17062         struct drm_crtc *c;
17063         struct drm_i915_gem_object *obj;
17064
17065         intel_init_gt_powersave(dev_priv);
17066
17067         intel_modeset_init_hw(dev);
17068
17069         intel_setup_overlay(dev_priv);
17070
17071         /*
17072          * Make sure any fbs we allocated at startup are properly
17073          * pinned & fenced.  When we do the allocation it's too early
17074          * for this.
17075          */
17076         for_each_crtc(dev, c) {
17077                 struct i915_vma *vma;
17078
17079                 obj = intel_fb_obj(c->primary->fb);
17080                 if (obj == NULL)
17081                         continue;
17082
17083                 mutex_lock(&dev->struct_mutex);
17084                 vma = intel_pin_and_fence_fb_obj(c->primary->fb,
17085                                                  c->primary->state->rotation);
17086                 mutex_unlock(&dev->struct_mutex);
17087                 if (IS_ERR(vma)) {
17088                         DRM_ERROR("failed to pin boot fb on pipe %d\n",
17089                                   to_intel_crtc(c)->pipe);
17090                         drm_framebuffer_unreference(c->primary->fb);
17091                         c->primary->fb = NULL;
17092                         c->primary->crtc = c->primary->state->crtc = NULL;
17093                         update_state_fb(c->primary);
17094                         c->state->plane_mask &= ~(1 << drm_plane_index(c->primary));
17095                 }
17096         }
17097 }
17098
17099 int intel_connector_register(struct drm_connector *connector)
17100 {
17101         struct intel_connector *intel_connector = to_intel_connector(connector);
17102         int ret;
17103
17104         ret = intel_backlight_device_register(intel_connector);
17105         if (ret)
17106                 goto err;
17107
17108         return 0;
17109
17110 err:
17111         return ret;
17112 }
17113
17114 void intel_connector_unregister(struct drm_connector *connector)
17115 {
17116         struct intel_connector *intel_connector = to_intel_connector(connector);
17117
17118         intel_backlight_device_unregister(intel_connector);
17119         intel_panel_destroy_backlight(connector);
17120 }
17121
17122 void intel_modeset_cleanup(struct drm_device *dev)
17123 {
17124         struct drm_i915_private *dev_priv = to_i915(dev);
17125
17126         intel_disable_gt_powersave(dev_priv);
17127
17128         /*
17129          * Interrupts and polling as the first thing to avoid creating havoc.
17130          * Too much stuff here (turning of connectors, ...) would
17131          * experience fancy races otherwise.
17132          */
17133         intel_irq_uninstall(dev_priv);
17134
17135         /*
17136          * Due to the hpd irq storm handling the hotplug work can re-arm the
17137          * poll handlers. Hence disable polling after hpd handling is shut down.
17138          */
17139         drm_kms_helper_poll_fini(dev);
17140
17141         intel_unregister_dsm_handler();
17142
17143         intel_fbc_global_disable(dev_priv);
17144
17145         /* flush any delayed tasks or pending work */
17146         flush_scheduled_work();
17147
17148         drm_mode_config_cleanup(dev);
17149
17150         intel_cleanup_overlay(dev_priv);
17151
17152         intel_cleanup_gt_powersave(dev_priv);
17153
17154         intel_teardown_gmbus(dev);
17155 }
17156
17157 void intel_connector_attach_encoder(struct intel_connector *connector,
17158                                     struct intel_encoder *encoder)
17159 {
17160         connector->encoder = encoder;
17161         drm_mode_connector_attach_encoder(&connector->base,
17162                                           &encoder->base);
17163 }
17164
17165 /*
17166  * set vga decode state - true == enable VGA decode
17167  */
17168 int intel_modeset_vga_set_state(struct drm_device *dev, bool state)
17169 {
17170         struct drm_i915_private *dev_priv = to_i915(dev);
17171         unsigned reg = INTEL_INFO(dev)->gen >= 6 ? SNB_GMCH_CTRL : INTEL_GMCH_CTRL;
17172         u16 gmch_ctrl;
17173
17174         if (pci_read_config_word(dev_priv->bridge_dev, reg, &gmch_ctrl)) {
17175                 DRM_ERROR("failed to read control word\n");
17176                 return -EIO;
17177         }
17178
17179         if (!!(gmch_ctrl & INTEL_GMCH_VGA_DISABLE) == !state)
17180                 return 0;
17181
17182         if (state)
17183                 gmch_ctrl &= ~INTEL_GMCH_VGA_DISABLE;
17184         else
17185                 gmch_ctrl |= INTEL_GMCH_VGA_DISABLE;
17186
17187         if (pci_write_config_word(dev_priv->bridge_dev, reg, gmch_ctrl)) {
17188                 DRM_ERROR("failed to write control word\n");
17189                 return -EIO;
17190         }
17191
17192         return 0;
17193 }
17194
17195 #if IS_ENABLED(CONFIG_DRM_I915_CAPTURE_ERROR)
17196
17197 struct intel_display_error_state {
17198
17199         u32 power_well_driver;
17200
17201         int num_transcoders;
17202
17203         struct intel_cursor_error_state {
17204                 u32 control;
17205                 u32 position;
17206                 u32 base;
17207                 u32 size;
17208         } cursor[I915_MAX_PIPES];
17209
17210         struct intel_pipe_error_state {
17211                 bool power_domain_on;
17212                 u32 source;
17213                 u32 stat;
17214         } pipe[I915_MAX_PIPES];
17215
17216         struct intel_plane_error_state {
17217                 u32 control;
17218                 u32 stride;
17219                 u32 size;
17220                 u32 pos;
17221                 u32 addr;
17222                 u32 surface;
17223                 u32 tile_offset;
17224         } plane[I915_MAX_PIPES];
17225
17226         struct intel_transcoder_error_state {
17227                 bool power_domain_on;
17228                 enum transcoder cpu_transcoder;
17229
17230                 u32 conf;
17231
17232                 u32 htotal;
17233                 u32 hblank;
17234                 u32 hsync;
17235                 u32 vtotal;
17236                 u32 vblank;
17237                 u32 vsync;
17238         } transcoder[4];
17239 };
17240
17241 struct intel_display_error_state *
17242 intel_display_capture_error_state(struct drm_i915_private *dev_priv)
17243 {
17244         struct intel_display_error_state *error;
17245         int transcoders[] = {
17246                 TRANSCODER_A,
17247                 TRANSCODER_B,
17248                 TRANSCODER_C,
17249                 TRANSCODER_EDP,
17250         };
17251         int i;
17252
17253         if (INTEL_INFO(dev_priv)->num_pipes == 0)
17254                 return NULL;
17255
17256         error = kzalloc(sizeof(*error), GFP_ATOMIC);
17257         if (error == NULL)
17258                 return NULL;
17259
17260         if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv))
17261                 error->power_well_driver = I915_READ(HSW_PWR_WELL_DRIVER);
17262
17263         for_each_pipe(dev_priv, i) {
17264                 error->pipe[i].power_domain_on =
17265                         __intel_display_power_is_enabled(dev_priv,
17266                                                          POWER_DOMAIN_PIPE(i));
17267                 if (!error->pipe[i].power_domain_on)
17268                         continue;
17269
17270                 error->cursor[i].control = I915_READ(CURCNTR(i));
17271                 error->cursor[i].position = I915_READ(CURPOS(i));
17272                 error->cursor[i].base = I915_READ(CURBASE(i));
17273
17274                 error->plane[i].control = I915_READ(DSPCNTR(i));
17275                 error->plane[i].stride = I915_READ(DSPSTRIDE(i));
17276                 if (INTEL_GEN(dev_priv) <= 3) {
17277                         error->plane[i].size = I915_READ(DSPSIZE(i));
17278                         error->plane[i].pos = I915_READ(DSPPOS(i));
17279                 }
17280                 if (INTEL_GEN(dev_priv) <= 7 && !IS_HASWELL(dev_priv))
17281                         error->plane[i].addr = I915_READ(DSPADDR(i));
17282                 if (INTEL_GEN(dev_priv) >= 4) {
17283                         error->plane[i].surface = I915_READ(DSPSURF(i));
17284                         error->plane[i].tile_offset = I915_READ(DSPTILEOFF(i));
17285                 }
17286
17287                 error->pipe[i].source = I915_READ(PIPESRC(i));
17288
17289                 if (HAS_GMCH_DISPLAY(dev_priv))
17290                         error->pipe[i].stat = I915_READ(PIPESTAT(i));
17291         }
17292
17293         /* Note: this does not include DSI transcoders. */
17294         error->num_transcoders = INTEL_INFO(dev_priv)->num_pipes;
17295         if (HAS_DDI(dev_priv))
17296                 error->num_transcoders++; /* Account for eDP. */
17297
17298         for (i = 0; i < error->num_transcoders; i++) {
17299                 enum transcoder cpu_transcoder = transcoders[i];
17300
17301                 error->transcoder[i].power_domain_on =
17302                         __intel_display_power_is_enabled(dev_priv,
17303                                 POWER_DOMAIN_TRANSCODER(cpu_transcoder));
17304                 if (!error->transcoder[i].power_domain_on)
17305                         continue;
17306
17307                 error->transcoder[i].cpu_transcoder = cpu_transcoder;
17308
17309                 error->transcoder[i].conf = I915_READ(PIPECONF(cpu_transcoder));
17310                 error->transcoder[i].htotal = I915_READ(HTOTAL(cpu_transcoder));
17311                 error->transcoder[i].hblank = I915_READ(HBLANK(cpu_transcoder));
17312                 error->transcoder[i].hsync = I915_READ(HSYNC(cpu_transcoder));
17313                 error->transcoder[i].vtotal = I915_READ(VTOTAL(cpu_transcoder));
17314                 error->transcoder[i].vblank = I915_READ(VBLANK(cpu_transcoder));
17315                 error->transcoder[i].vsync = I915_READ(VSYNC(cpu_transcoder));
17316         }
17317
17318         return error;
17319 }
17320
17321 #define err_printf(e, ...) i915_error_printf(e, __VA_ARGS__)
17322
17323 void
17324 intel_display_print_error_state(struct drm_i915_error_state_buf *m,
17325                                 struct drm_device *dev,
17326                                 struct intel_display_error_state *error)
17327 {
17328         struct drm_i915_private *dev_priv = to_i915(dev);
17329         int i;
17330
17331         if (!error)
17332                 return;
17333
17334         err_printf(m, "Num Pipes: %d\n", INTEL_INFO(dev)->num_pipes);
17335         if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv))
17336                 err_printf(m, "PWR_WELL_CTL2: %08x\n",
17337                            error->power_well_driver);
17338         for_each_pipe(dev_priv, i) {
17339                 err_printf(m, "Pipe [%d]:\n", i);
17340                 err_printf(m, "  Power: %s\n",
17341                            onoff(error->pipe[i].power_domain_on));
17342                 err_printf(m, "  SRC: %08x\n", error->pipe[i].source);
17343                 err_printf(m, "  STAT: %08x\n", error->pipe[i].stat);
17344
17345                 err_printf(m, "Plane [%d]:\n", i);
17346                 err_printf(m, "  CNTR: %08x\n", error->plane[i].control);
17347                 err_printf(m, "  STRIDE: %08x\n", error->plane[i].stride);
17348                 if (INTEL_INFO(dev)->gen <= 3) {
17349                         err_printf(m, "  SIZE: %08x\n", error->plane[i].size);
17350                         err_printf(m, "  POS: %08x\n", error->plane[i].pos);
17351                 }
17352                 if (INTEL_GEN(dev_priv) <= 7 && !IS_HASWELL(dev_priv))
17353                         err_printf(m, "  ADDR: %08x\n", error->plane[i].addr);
17354                 if (INTEL_INFO(dev)->gen >= 4) {
17355                         err_printf(m, "  SURF: %08x\n", error->plane[i].surface);
17356                         err_printf(m, "  TILEOFF: %08x\n", error->plane[i].tile_offset);
17357                 }
17358
17359                 err_printf(m, "Cursor [%d]:\n", i);
17360                 err_printf(m, "  CNTR: %08x\n", error->cursor[i].control);
17361                 err_printf(m, "  POS: %08x\n", error->cursor[i].position);
17362                 err_printf(m, "  BASE: %08x\n", error->cursor[i].base);
17363         }
17364
17365         for (i = 0; i < error->num_transcoders; i++) {
17366                 err_printf(m, "CPU transcoder: %s\n",
17367                            transcoder_name(error->transcoder[i].cpu_transcoder));
17368                 err_printf(m, "  Power: %s\n",
17369                            onoff(error->transcoder[i].power_domain_on));
17370                 err_printf(m, "  CONF: %08x\n", error->transcoder[i].conf);
17371                 err_printf(m, "  HTOTAL: %08x\n", error->transcoder[i].htotal);
17372                 err_printf(m, "  HBLANK: %08x\n", error->transcoder[i].hblank);
17373                 err_printf(m, "  HSYNC: %08x\n", error->transcoder[i].hsync);
17374                 err_printf(m, "  VTOTAL: %08x\n", error->transcoder[i].vtotal);
17375                 err_printf(m, "  VBLANK: %08x\n", error->transcoder[i].vblank);
17376                 err_printf(m, "  VSYNC: %08x\n", error->transcoder[i].vsync);
17377         }
17378 }
17379
17380 #endif