]> asedeno.scripts.mit.edu Git - linux.git/blob - drivers/gpu/drm/i915/display/intel_display.c
06cf2171474d86316e2830e33e2eb306cf5201b3
[linux.git] / drivers / gpu / drm / i915 / display / 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/i2c.h>
28 #include <linux/input.h>
29 #include <linux/intel-iommu.h>
30 #include <linux/kernel.h>
31 #include <linux/module.h>
32 #include <linux/dma-resv.h>
33 #include <linux/slab.h>
34 #include <linux/vgaarb.h>
35
36 #include <drm/drm_atomic.h>
37 #include <drm/drm_atomic_helper.h>
38 #include <drm/drm_atomic_uapi.h>
39 #include <drm/drm_dp_helper.h>
40 #include <drm/drm_edid.h>
41 #include <drm/drm_fourcc.h>
42 #include <drm/drm_plane_helper.h>
43 #include <drm/drm_probe_helper.h>
44 #include <drm/drm_rect.h>
45 #include <drm/i915_drm.h>
46
47 #include "display/intel_crt.h"
48 #include "display/intel_ddi.h"
49 #include "display/intel_dp.h"
50 #include "display/intel_dsi.h"
51 #include "display/intel_dvo.h"
52 #include "display/intel_gmbus.h"
53 #include "display/intel_hdmi.h"
54 #include "display/intel_lvds.h"
55 #include "display/intel_sdvo.h"
56 #include "display/intel_tv.h"
57 #include "display/intel_vdsc.h"
58
59 #include "i915_drv.h"
60 #include "i915_trace.h"
61 #include "intel_acpi.h"
62 #include "intel_atomic.h"
63 #include "intel_atomic_plane.h"
64 #include "intel_bw.h"
65 #include "intel_cdclk.h"
66 #include "intel_color.h"
67 #include "intel_display_types.h"
68 #include "intel_fbc.h"
69 #include "intel_fbdev.h"
70 #include "intel_fifo_underrun.h"
71 #include "intel_frontbuffer.h"
72 #include "intel_hdcp.h"
73 #include "intel_hotplug.h"
74 #include "intel_overlay.h"
75 #include "intel_pipe_crc.h"
76 #include "intel_pm.h"
77 #include "intel_psr.h"
78 #include "intel_quirks.h"
79 #include "intel_sideband.h"
80 #include "intel_sprite.h"
81 #include "intel_tc.h"
82
83 /* Primary plane formats for gen <= 3 */
84 static const u32 i8xx_primary_formats[] = {
85         DRM_FORMAT_C8,
86         DRM_FORMAT_RGB565,
87         DRM_FORMAT_XRGB1555,
88         DRM_FORMAT_XRGB8888,
89 };
90
91 /* Primary plane formats for gen >= 4 */
92 static const u32 i965_primary_formats[] = {
93         DRM_FORMAT_C8,
94         DRM_FORMAT_RGB565,
95         DRM_FORMAT_XRGB8888,
96         DRM_FORMAT_XBGR8888,
97         DRM_FORMAT_XRGB2101010,
98         DRM_FORMAT_XBGR2101010,
99 };
100
101 static const u64 i9xx_format_modifiers[] = {
102         I915_FORMAT_MOD_X_TILED,
103         DRM_FORMAT_MOD_LINEAR,
104         DRM_FORMAT_MOD_INVALID
105 };
106
107 /* Cursor formats */
108 static const u32 intel_cursor_formats[] = {
109         DRM_FORMAT_ARGB8888,
110 };
111
112 static const u64 cursor_format_modifiers[] = {
113         DRM_FORMAT_MOD_LINEAR,
114         DRM_FORMAT_MOD_INVALID
115 };
116
117 static void i9xx_crtc_clock_get(struct intel_crtc *crtc,
118                                 struct intel_crtc_state *pipe_config);
119 static void ironlake_pch_clock_get(struct intel_crtc *crtc,
120                                    struct intel_crtc_state *pipe_config);
121
122 static int intel_framebuffer_init(struct intel_framebuffer *ifb,
123                                   struct drm_i915_gem_object *obj,
124                                   struct drm_mode_fb_cmd2 *mode_cmd);
125 static void intel_set_pipe_timings(const struct intel_crtc_state *crtc_state);
126 static void intel_set_pipe_src_size(const struct intel_crtc_state *crtc_state);
127 static void intel_cpu_transcoder_set_m_n(const struct intel_crtc_state *crtc_state,
128                                          const struct intel_link_m_n *m_n,
129                                          const struct intel_link_m_n *m2_n2);
130 static void i9xx_set_pipeconf(const struct intel_crtc_state *crtc_state);
131 static void ironlake_set_pipeconf(const struct intel_crtc_state *crtc_state);
132 static void haswell_set_pipeconf(const struct intel_crtc_state *crtc_state);
133 static void bdw_set_pipemisc(const struct intel_crtc_state *crtc_state);
134 static void vlv_prepare_pll(struct intel_crtc *crtc,
135                             const struct intel_crtc_state *pipe_config);
136 static void chv_prepare_pll(struct intel_crtc *crtc,
137                             const struct intel_crtc_state *pipe_config);
138 static void intel_begin_crtc_commit(struct intel_atomic_state *, struct intel_crtc *);
139 static void intel_finish_crtc_commit(struct intel_atomic_state *, struct intel_crtc *);
140 static void intel_crtc_init_scalers(struct intel_crtc *crtc,
141                                     struct intel_crtc_state *crtc_state);
142 static void skylake_pfit_enable(const struct intel_crtc_state *crtc_state);
143 static void ironlake_pfit_disable(const struct intel_crtc_state *old_crtc_state);
144 static void ironlake_pfit_enable(const struct intel_crtc_state *crtc_state);
145 static void intel_modeset_setup_hw_state(struct drm_device *dev,
146                                          struct drm_modeset_acquire_ctx *ctx);
147 static void intel_pre_disable_primary_noatomic(struct drm_crtc *crtc);
148
149 struct intel_limit {
150         struct {
151                 int min, max;
152         } dot, vco, n, m, m1, m2, p, p1;
153
154         struct {
155                 int dot_limit;
156                 int p2_slow, p2_fast;
157         } p2;
158 };
159
160 /* returns HPLL frequency in kHz */
161 int vlv_get_hpll_vco(struct drm_i915_private *dev_priv)
162 {
163         int hpll_freq, vco_freq[] = { 800, 1600, 2000, 2400 };
164
165         /* Obtain SKU information */
166         hpll_freq = vlv_cck_read(dev_priv, CCK_FUSE_REG) &
167                 CCK_FUSE_HPLL_FREQ_MASK;
168
169         return vco_freq[hpll_freq] * 1000;
170 }
171
172 int vlv_get_cck_clock(struct drm_i915_private *dev_priv,
173                       const char *name, u32 reg, int ref_freq)
174 {
175         u32 val;
176         int divider;
177
178         val = vlv_cck_read(dev_priv, reg);
179         divider = val & CCK_FREQUENCY_VALUES;
180
181         WARN((val & CCK_FREQUENCY_STATUS) !=
182              (divider << CCK_FREQUENCY_STATUS_SHIFT),
183              "%s change in progress\n", name);
184
185         return DIV_ROUND_CLOSEST(ref_freq << 1, divider + 1);
186 }
187
188 int vlv_get_cck_clock_hpll(struct drm_i915_private *dev_priv,
189                            const char *name, u32 reg)
190 {
191         int hpll;
192
193         vlv_cck_get(dev_priv);
194
195         if (dev_priv->hpll_freq == 0)
196                 dev_priv->hpll_freq = vlv_get_hpll_vco(dev_priv);
197
198         hpll = vlv_get_cck_clock(dev_priv, name, reg, dev_priv->hpll_freq);
199
200         vlv_cck_put(dev_priv);
201
202         return hpll;
203 }
204
205 static void intel_update_czclk(struct drm_i915_private *dev_priv)
206 {
207         if (!(IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv)))
208                 return;
209
210         dev_priv->czclk_freq = vlv_get_cck_clock_hpll(dev_priv, "czclk",
211                                                       CCK_CZ_CLOCK_CONTROL);
212
213         DRM_DEBUG_DRIVER("CZ clock rate: %d kHz\n", dev_priv->czclk_freq);
214 }
215
216 static inline u32 /* units of 100MHz */
217 intel_fdi_link_freq(struct drm_i915_private *dev_priv,
218                     const struct intel_crtc_state *pipe_config)
219 {
220         if (HAS_DDI(dev_priv))
221                 return pipe_config->port_clock; /* SPLL */
222         else
223                 return dev_priv->fdi_pll_freq;
224 }
225
226 static const struct intel_limit intel_limits_i8xx_dac = {
227         .dot = { .min = 25000, .max = 350000 },
228         .vco = { .min = 908000, .max = 1512000 },
229         .n = { .min = 2, .max = 16 },
230         .m = { .min = 96, .max = 140 },
231         .m1 = { .min = 18, .max = 26 },
232         .m2 = { .min = 6, .max = 16 },
233         .p = { .min = 4, .max = 128 },
234         .p1 = { .min = 2, .max = 33 },
235         .p2 = { .dot_limit = 165000,
236                 .p2_slow = 4, .p2_fast = 2 },
237 };
238
239 static const struct intel_limit intel_limits_i8xx_dvo = {
240         .dot = { .min = 25000, .max = 350000 },
241         .vco = { .min = 908000, .max = 1512000 },
242         .n = { .min = 2, .max = 16 },
243         .m = { .min = 96, .max = 140 },
244         .m1 = { .min = 18, .max = 26 },
245         .m2 = { .min = 6, .max = 16 },
246         .p = { .min = 4, .max = 128 },
247         .p1 = { .min = 2, .max = 33 },
248         .p2 = { .dot_limit = 165000,
249                 .p2_slow = 4, .p2_fast = 4 },
250 };
251
252 static const struct intel_limit intel_limits_i8xx_lvds = {
253         .dot = { .min = 25000, .max = 350000 },
254         .vco = { .min = 908000, .max = 1512000 },
255         .n = { .min = 2, .max = 16 },
256         .m = { .min = 96, .max = 140 },
257         .m1 = { .min = 18, .max = 26 },
258         .m2 = { .min = 6, .max = 16 },
259         .p = { .min = 4, .max = 128 },
260         .p1 = { .min = 1, .max = 6 },
261         .p2 = { .dot_limit = 165000,
262                 .p2_slow = 14, .p2_fast = 7 },
263 };
264
265 static const struct intel_limit intel_limits_i9xx_sdvo = {
266         .dot = { .min = 20000, .max = 400000 },
267         .vco = { .min = 1400000, .max = 2800000 },
268         .n = { .min = 1, .max = 6 },
269         .m = { .min = 70, .max = 120 },
270         .m1 = { .min = 8, .max = 18 },
271         .m2 = { .min = 3, .max = 7 },
272         .p = { .min = 5, .max = 80 },
273         .p1 = { .min = 1, .max = 8 },
274         .p2 = { .dot_limit = 200000,
275                 .p2_slow = 10, .p2_fast = 5 },
276 };
277
278 static const struct intel_limit intel_limits_i9xx_lvds = {
279         .dot = { .min = 20000, .max = 400000 },
280         .vco = { .min = 1400000, .max = 2800000 },
281         .n = { .min = 1, .max = 6 },
282         .m = { .min = 70, .max = 120 },
283         .m1 = { .min = 8, .max = 18 },
284         .m2 = { .min = 3, .max = 7 },
285         .p = { .min = 7, .max = 98 },
286         .p1 = { .min = 1, .max = 8 },
287         .p2 = { .dot_limit = 112000,
288                 .p2_slow = 14, .p2_fast = 7 },
289 };
290
291
292 static const struct intel_limit intel_limits_g4x_sdvo = {
293         .dot = { .min = 25000, .max = 270000 },
294         .vco = { .min = 1750000, .max = 3500000},
295         .n = { .min = 1, .max = 4 },
296         .m = { .min = 104, .max = 138 },
297         .m1 = { .min = 17, .max = 23 },
298         .m2 = { .min = 5, .max = 11 },
299         .p = { .min = 10, .max = 30 },
300         .p1 = { .min = 1, .max = 3},
301         .p2 = { .dot_limit = 270000,
302                 .p2_slow = 10,
303                 .p2_fast = 10
304         },
305 };
306
307 static const struct intel_limit intel_limits_g4x_hdmi = {
308         .dot = { .min = 22000, .max = 400000 },
309         .vco = { .min = 1750000, .max = 3500000},
310         .n = { .min = 1, .max = 4 },
311         .m = { .min = 104, .max = 138 },
312         .m1 = { .min = 16, .max = 23 },
313         .m2 = { .min = 5, .max = 11 },
314         .p = { .min = 5, .max = 80 },
315         .p1 = { .min = 1, .max = 8},
316         .p2 = { .dot_limit = 165000,
317                 .p2_slow = 10, .p2_fast = 5 },
318 };
319
320 static const struct intel_limit intel_limits_g4x_single_channel_lvds = {
321         .dot = { .min = 20000, .max = 115000 },
322         .vco = { .min = 1750000, .max = 3500000 },
323         .n = { .min = 1, .max = 3 },
324         .m = { .min = 104, .max = 138 },
325         .m1 = { .min = 17, .max = 23 },
326         .m2 = { .min = 5, .max = 11 },
327         .p = { .min = 28, .max = 112 },
328         .p1 = { .min = 2, .max = 8 },
329         .p2 = { .dot_limit = 0,
330                 .p2_slow = 14, .p2_fast = 14
331         },
332 };
333
334 static const struct intel_limit intel_limits_g4x_dual_channel_lvds = {
335         .dot = { .min = 80000, .max = 224000 },
336         .vco = { .min = 1750000, .max = 3500000 },
337         .n = { .min = 1, .max = 3 },
338         .m = { .min = 104, .max = 138 },
339         .m1 = { .min = 17, .max = 23 },
340         .m2 = { .min = 5, .max = 11 },
341         .p = { .min = 14, .max = 42 },
342         .p1 = { .min = 2, .max = 6 },
343         .p2 = { .dot_limit = 0,
344                 .p2_slow = 7, .p2_fast = 7
345         },
346 };
347
348 static const struct intel_limit intel_limits_pineview_sdvo = {
349         .dot = { .min = 20000, .max = 400000},
350         .vco = { .min = 1700000, .max = 3500000 },
351         /* Pineview's Ncounter is a ring counter */
352         .n = { .min = 3, .max = 6 },
353         .m = { .min = 2, .max = 256 },
354         /* Pineview only has one combined m divider, which we treat as m2. */
355         .m1 = { .min = 0, .max = 0 },
356         .m2 = { .min = 0, .max = 254 },
357         .p = { .min = 5, .max = 80 },
358         .p1 = { .min = 1, .max = 8 },
359         .p2 = { .dot_limit = 200000,
360                 .p2_slow = 10, .p2_fast = 5 },
361 };
362
363 static const struct intel_limit intel_limits_pineview_lvds = {
364         .dot = { .min = 20000, .max = 400000 },
365         .vco = { .min = 1700000, .max = 3500000 },
366         .n = { .min = 3, .max = 6 },
367         .m = { .min = 2, .max = 256 },
368         .m1 = { .min = 0, .max = 0 },
369         .m2 = { .min = 0, .max = 254 },
370         .p = { .min = 7, .max = 112 },
371         .p1 = { .min = 1, .max = 8 },
372         .p2 = { .dot_limit = 112000,
373                 .p2_slow = 14, .p2_fast = 14 },
374 };
375
376 /* Ironlake / Sandybridge
377  *
378  * We calculate clock using (register_value + 2) for N/M1/M2, so here
379  * the range value for them is (actual_value - 2).
380  */
381 static const struct intel_limit intel_limits_ironlake_dac = {
382         .dot = { .min = 25000, .max = 350000 },
383         .vco = { .min = 1760000, .max = 3510000 },
384         .n = { .min = 1, .max = 5 },
385         .m = { .min = 79, .max = 127 },
386         .m1 = { .min = 12, .max = 22 },
387         .m2 = { .min = 5, .max = 9 },
388         .p = { .min = 5, .max = 80 },
389         .p1 = { .min = 1, .max = 8 },
390         .p2 = { .dot_limit = 225000,
391                 .p2_slow = 10, .p2_fast = 5 },
392 };
393
394 static const struct intel_limit intel_limits_ironlake_single_lvds = {
395         .dot = { .min = 25000, .max = 350000 },
396         .vco = { .min = 1760000, .max = 3510000 },
397         .n = { .min = 1, .max = 3 },
398         .m = { .min = 79, .max = 118 },
399         .m1 = { .min = 12, .max = 22 },
400         .m2 = { .min = 5, .max = 9 },
401         .p = { .min = 28, .max = 112 },
402         .p1 = { .min = 2, .max = 8 },
403         .p2 = { .dot_limit = 225000,
404                 .p2_slow = 14, .p2_fast = 14 },
405 };
406
407 static const struct intel_limit intel_limits_ironlake_dual_lvds = {
408         .dot = { .min = 25000, .max = 350000 },
409         .vco = { .min = 1760000, .max = 3510000 },
410         .n = { .min = 1, .max = 3 },
411         .m = { .min = 79, .max = 127 },
412         .m1 = { .min = 12, .max = 22 },
413         .m2 = { .min = 5, .max = 9 },
414         .p = { .min = 14, .max = 56 },
415         .p1 = { .min = 2, .max = 8 },
416         .p2 = { .dot_limit = 225000,
417                 .p2_slow = 7, .p2_fast = 7 },
418 };
419
420 /* LVDS 100mhz refclk limits. */
421 static const struct intel_limit intel_limits_ironlake_single_lvds_100m = {
422         .dot = { .min = 25000, .max = 350000 },
423         .vco = { .min = 1760000, .max = 3510000 },
424         .n = { .min = 1, .max = 2 },
425         .m = { .min = 79, .max = 126 },
426         .m1 = { .min = 12, .max = 22 },
427         .m2 = { .min = 5, .max = 9 },
428         .p = { .min = 28, .max = 112 },
429         .p1 = { .min = 2, .max = 8 },
430         .p2 = { .dot_limit = 225000,
431                 .p2_slow = 14, .p2_fast = 14 },
432 };
433
434 static const struct intel_limit intel_limits_ironlake_dual_lvds_100m = {
435         .dot = { .min = 25000, .max = 350000 },
436         .vco = { .min = 1760000, .max = 3510000 },
437         .n = { .min = 1, .max = 3 },
438         .m = { .min = 79, .max = 126 },
439         .m1 = { .min = 12, .max = 22 },
440         .m2 = { .min = 5, .max = 9 },
441         .p = { .min = 14, .max = 42 },
442         .p1 = { .min = 2, .max = 6 },
443         .p2 = { .dot_limit = 225000,
444                 .p2_slow = 7, .p2_fast = 7 },
445 };
446
447 static const struct intel_limit intel_limits_vlv = {
448          /*
449           * These are the data rate limits (measured in fast clocks)
450           * since those are the strictest limits we have. The fast
451           * clock and actual rate limits are more relaxed, so checking
452           * them would make no difference.
453           */
454         .dot = { .min = 25000 * 5, .max = 270000 * 5 },
455         .vco = { .min = 4000000, .max = 6000000 },
456         .n = { .min = 1, .max = 7 },
457         .m1 = { .min = 2, .max = 3 },
458         .m2 = { .min = 11, .max = 156 },
459         .p1 = { .min = 2, .max = 3 },
460         .p2 = { .p2_slow = 2, .p2_fast = 20 }, /* slow=min, fast=max */
461 };
462
463 static const struct intel_limit intel_limits_chv = {
464         /*
465          * These are the data rate limits (measured in fast clocks)
466          * since those are the strictest limits we have.  The fast
467          * clock and actual rate limits are more relaxed, so checking
468          * them would make no difference.
469          */
470         .dot = { .min = 25000 * 5, .max = 540000 * 5},
471         .vco = { .min = 4800000, .max = 6480000 },
472         .n = { .min = 1, .max = 1 },
473         .m1 = { .min = 2, .max = 2 },
474         .m2 = { .min = 24 << 22, .max = 175 << 22 },
475         .p1 = { .min = 2, .max = 4 },
476         .p2 = { .p2_slow = 1, .p2_fast = 14 },
477 };
478
479 static const struct intel_limit intel_limits_bxt = {
480         /* FIXME: find real dot limits */
481         .dot = { .min = 0, .max = INT_MAX },
482         .vco = { .min = 4800000, .max = 6700000 },
483         .n = { .min = 1, .max = 1 },
484         .m1 = { .min = 2, .max = 2 },
485         /* FIXME: find real m2 limits */
486         .m2 = { .min = 2 << 22, .max = 255 << 22 },
487         .p1 = { .min = 2, .max = 4 },
488         .p2 = { .p2_slow = 1, .p2_fast = 20 },
489 };
490
491 /* WA Display #0827: Gen9:all */
492 static void
493 skl_wa_827(struct drm_i915_private *dev_priv, enum pipe pipe, bool enable)
494 {
495         if (enable)
496                 I915_WRITE(CLKGATE_DIS_PSL(pipe),
497                            I915_READ(CLKGATE_DIS_PSL(pipe)) |
498                            DUPS1_GATING_DIS | DUPS2_GATING_DIS);
499         else
500                 I915_WRITE(CLKGATE_DIS_PSL(pipe),
501                            I915_READ(CLKGATE_DIS_PSL(pipe)) &
502                            ~(DUPS1_GATING_DIS | DUPS2_GATING_DIS));
503 }
504
505 /* Wa_2006604312:icl */
506 static void
507 icl_wa_scalerclkgating(struct drm_i915_private *dev_priv, enum pipe pipe,
508                        bool enable)
509 {
510         if (enable)
511                 I915_WRITE(CLKGATE_DIS_PSL(pipe),
512                            I915_READ(CLKGATE_DIS_PSL(pipe)) | DPFR_GATING_DIS);
513         else
514                 I915_WRITE(CLKGATE_DIS_PSL(pipe),
515                            I915_READ(CLKGATE_DIS_PSL(pipe)) & ~DPFR_GATING_DIS);
516 }
517
518 static bool
519 needs_modeset(const struct intel_crtc_state *state)
520 {
521         return drm_atomic_crtc_needs_modeset(&state->base);
522 }
523
524 /*
525  * Platform specific helpers to calculate the port PLL loopback- (clock.m),
526  * and post-divider (clock.p) values, pre- (clock.vco) and post-divided fast
527  * (clock.dot) clock rates. This fast dot clock is fed to the port's IO logic.
528  * The helpers' return value is the rate of the clock that is fed to the
529  * display engine's pipe which can be the above fast dot clock rate or a
530  * divided-down version of it.
531  */
532 /* m1 is reserved as 0 in Pineview, n is a ring counter */
533 static int pnv_calc_dpll_params(int refclk, struct dpll *clock)
534 {
535         clock->m = clock->m2 + 2;
536         clock->p = clock->p1 * clock->p2;
537         if (WARN_ON(clock->n == 0 || clock->p == 0))
538                 return 0;
539         clock->vco = DIV_ROUND_CLOSEST(refclk * clock->m, clock->n);
540         clock->dot = DIV_ROUND_CLOSEST(clock->vco, clock->p);
541
542         return clock->dot;
543 }
544
545 static u32 i9xx_dpll_compute_m(struct dpll *dpll)
546 {
547         return 5 * (dpll->m1 + 2) + (dpll->m2 + 2);
548 }
549
550 static int i9xx_calc_dpll_params(int refclk, struct dpll *clock)
551 {
552         clock->m = i9xx_dpll_compute_m(clock);
553         clock->p = clock->p1 * clock->p2;
554         if (WARN_ON(clock->n + 2 == 0 || clock->p == 0))
555                 return 0;
556         clock->vco = DIV_ROUND_CLOSEST(refclk * clock->m, clock->n + 2);
557         clock->dot = DIV_ROUND_CLOSEST(clock->vco, clock->p);
558
559         return clock->dot;
560 }
561
562 static int vlv_calc_dpll_params(int refclk, struct dpll *clock)
563 {
564         clock->m = clock->m1 * clock->m2;
565         clock->p = clock->p1 * clock->p2;
566         if (WARN_ON(clock->n == 0 || clock->p == 0))
567                 return 0;
568         clock->vco = DIV_ROUND_CLOSEST(refclk * clock->m, clock->n);
569         clock->dot = DIV_ROUND_CLOSEST(clock->vco, clock->p);
570
571         return clock->dot / 5;
572 }
573
574 int chv_calc_dpll_params(int refclk, struct dpll *clock)
575 {
576         clock->m = clock->m1 * clock->m2;
577         clock->p = clock->p1 * clock->p2;
578         if (WARN_ON(clock->n == 0 || clock->p == 0))
579                 return 0;
580         clock->vco = DIV_ROUND_CLOSEST_ULL(mul_u32_u32(refclk, clock->m),
581                                            clock->n << 22);
582         clock->dot = DIV_ROUND_CLOSEST(clock->vco, clock->p);
583
584         return clock->dot / 5;
585 }
586
587 #define INTELPllInvalid(s)   do { /* DRM_DEBUG(s); */ return false; } while (0)
588
589 /*
590  * Returns whether the given set of divisors are valid for a given refclk with
591  * the given connectors.
592  */
593 static bool intel_PLL_is_valid(struct drm_i915_private *dev_priv,
594                                const struct intel_limit *limit,
595                                const struct dpll *clock)
596 {
597         if (clock->n   < limit->n.min   || limit->n.max   < clock->n)
598                 INTELPllInvalid("n out of range\n");
599         if (clock->p1  < limit->p1.min  || limit->p1.max  < clock->p1)
600                 INTELPllInvalid("p1 out of range\n");
601         if (clock->m2  < limit->m2.min  || limit->m2.max  < clock->m2)
602                 INTELPllInvalid("m2 out of range\n");
603         if (clock->m1  < limit->m1.min  || limit->m1.max  < clock->m1)
604                 INTELPllInvalid("m1 out of range\n");
605
606         if (!IS_PINEVIEW(dev_priv) && !IS_VALLEYVIEW(dev_priv) &&
607             !IS_CHERRYVIEW(dev_priv) && !IS_GEN9_LP(dev_priv))
608                 if (clock->m1 <= clock->m2)
609                         INTELPllInvalid("m1 <= m2\n");
610
611         if (!IS_VALLEYVIEW(dev_priv) && !IS_CHERRYVIEW(dev_priv) &&
612             !IS_GEN9_LP(dev_priv)) {
613                 if (clock->p < limit->p.min || limit->p.max < clock->p)
614                         INTELPllInvalid("p out of range\n");
615                 if (clock->m < limit->m.min || limit->m.max < clock->m)
616                         INTELPllInvalid("m out of range\n");
617         }
618
619         if (clock->vco < limit->vco.min || limit->vco.max < clock->vco)
620                 INTELPllInvalid("vco out of range\n");
621         /* XXX: We may need to be checking "Dot clock" depending on the multiplier,
622          * connector, etc., rather than just a single range.
623          */
624         if (clock->dot < limit->dot.min || limit->dot.max < clock->dot)
625                 INTELPllInvalid("dot out of range\n");
626
627         return true;
628 }
629
630 static int
631 i9xx_select_p2_div(const struct intel_limit *limit,
632                    const struct intel_crtc_state *crtc_state,
633                    int target)
634 {
635         struct drm_i915_private *dev_priv = to_i915(crtc_state->base.crtc->dev);
636
637         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
638                 /*
639                  * For LVDS just rely on its current settings for dual-channel.
640                  * We haven't figured out how to reliably set up different
641                  * single/dual channel state, if we even can.
642                  */
643                 if (intel_is_dual_link_lvds(dev_priv))
644                         return limit->p2.p2_fast;
645                 else
646                         return limit->p2.p2_slow;
647         } else {
648                 if (target < limit->p2.dot_limit)
649                         return limit->p2.p2_slow;
650                 else
651                         return limit->p2.p2_fast;
652         }
653 }
654
655 /*
656  * Returns a set of divisors for the desired target clock with the given
657  * refclk, or FALSE.  The returned values represent the clock equation:
658  * reflck * (5 * (m1 + 2) + (m2 + 2)) / (n + 2) / p1 / p2.
659  *
660  * Target and reference clocks are specified in kHz.
661  *
662  * If match_clock is provided, then best_clock P divider must match the P
663  * divider from @match_clock used for LVDS downclocking.
664  */
665 static bool
666 i9xx_find_best_dpll(const struct intel_limit *limit,
667                     struct intel_crtc_state *crtc_state,
668                     int target, int refclk, struct dpll *match_clock,
669                     struct dpll *best_clock)
670 {
671         struct drm_device *dev = crtc_state->base.crtc->dev;
672         struct dpll clock;
673         int err = target;
674
675         memset(best_clock, 0, sizeof(*best_clock));
676
677         clock.p2 = i9xx_select_p2_div(limit, crtc_state, target);
678
679         for (clock.m1 = limit->m1.min; clock.m1 <= limit->m1.max;
680              clock.m1++) {
681                 for (clock.m2 = limit->m2.min;
682                      clock.m2 <= limit->m2.max; clock.m2++) {
683                         if (clock.m2 >= clock.m1)
684                                 break;
685                         for (clock.n = limit->n.min;
686                              clock.n <= limit->n.max; clock.n++) {
687                                 for (clock.p1 = limit->p1.min;
688                                         clock.p1 <= limit->p1.max; clock.p1++) {
689                                         int this_err;
690
691                                         i9xx_calc_dpll_params(refclk, &clock);
692                                         if (!intel_PLL_is_valid(to_i915(dev),
693                                                                 limit,
694                                                                 &clock))
695                                                 continue;
696                                         if (match_clock &&
697                                             clock.p != match_clock->p)
698                                                 continue;
699
700                                         this_err = abs(clock.dot - target);
701                                         if (this_err < err) {
702                                                 *best_clock = clock;
703                                                 err = this_err;
704                                         }
705                                 }
706                         }
707                 }
708         }
709
710         return (err != target);
711 }
712
713 /*
714  * Returns a set of divisors for the desired target clock with the given
715  * refclk, or FALSE.  The returned values represent the clock equation:
716  * reflck * (5 * (m1 + 2) + (m2 + 2)) / (n + 2) / p1 / p2.
717  *
718  * Target and reference clocks are specified in kHz.
719  *
720  * If match_clock is provided, then best_clock P divider must match the P
721  * divider from @match_clock used for LVDS downclocking.
722  */
723 static bool
724 pnv_find_best_dpll(const struct intel_limit *limit,
725                    struct intel_crtc_state *crtc_state,
726                    int target, int refclk, struct dpll *match_clock,
727                    struct dpll *best_clock)
728 {
729         struct drm_device *dev = crtc_state->base.crtc->dev;
730         struct dpll clock;
731         int err = target;
732
733         memset(best_clock, 0, sizeof(*best_clock));
734
735         clock.p2 = i9xx_select_p2_div(limit, crtc_state, target);
736
737         for (clock.m1 = limit->m1.min; clock.m1 <= limit->m1.max;
738              clock.m1++) {
739                 for (clock.m2 = limit->m2.min;
740                      clock.m2 <= limit->m2.max; clock.m2++) {
741                         for (clock.n = limit->n.min;
742                              clock.n <= limit->n.max; clock.n++) {
743                                 for (clock.p1 = limit->p1.min;
744                                         clock.p1 <= limit->p1.max; clock.p1++) {
745                                         int this_err;
746
747                                         pnv_calc_dpll_params(refclk, &clock);
748                                         if (!intel_PLL_is_valid(to_i915(dev),
749                                                                 limit,
750                                                                 &clock))
751                                                 continue;
752                                         if (match_clock &&
753                                             clock.p != match_clock->p)
754                                                 continue;
755
756                                         this_err = abs(clock.dot - target);
757                                         if (this_err < err) {
758                                                 *best_clock = clock;
759                                                 err = this_err;
760                                         }
761                                 }
762                         }
763                 }
764         }
765
766         return (err != target);
767 }
768
769 /*
770  * Returns a set of divisors for the desired target clock with the given
771  * refclk, or FALSE.  The returned values represent the clock equation:
772  * reflck * (5 * (m1 + 2) + (m2 + 2)) / (n + 2) / p1 / p2.
773  *
774  * Target and reference clocks are specified in kHz.
775  *
776  * If match_clock is provided, then best_clock P divider must match the P
777  * divider from @match_clock used for LVDS downclocking.
778  */
779 static bool
780 g4x_find_best_dpll(const struct intel_limit *limit,
781                    struct intel_crtc_state *crtc_state,
782                    int target, int refclk, struct dpll *match_clock,
783                    struct dpll *best_clock)
784 {
785         struct drm_device *dev = crtc_state->base.crtc->dev;
786         struct dpll clock;
787         int max_n;
788         bool found = false;
789         /* approximately equals target * 0.00585 */
790         int err_most = (target >> 8) + (target >> 9);
791
792         memset(best_clock, 0, sizeof(*best_clock));
793
794         clock.p2 = i9xx_select_p2_div(limit, crtc_state, target);
795
796         max_n = limit->n.max;
797         /* based on hardware requirement, prefer smaller n to precision */
798         for (clock.n = limit->n.min; clock.n <= max_n; clock.n++) {
799                 /* based on hardware requirement, prefere larger m1,m2 */
800                 for (clock.m1 = limit->m1.max;
801                      clock.m1 >= limit->m1.min; clock.m1--) {
802                         for (clock.m2 = limit->m2.max;
803                              clock.m2 >= limit->m2.min; clock.m2--) {
804                                 for (clock.p1 = limit->p1.max;
805                                      clock.p1 >= limit->p1.min; clock.p1--) {
806                                         int this_err;
807
808                                         i9xx_calc_dpll_params(refclk, &clock);
809                                         if (!intel_PLL_is_valid(to_i915(dev),
810                                                                 limit,
811                                                                 &clock))
812                                                 continue;
813
814                                         this_err = abs(clock.dot - target);
815                                         if (this_err < err_most) {
816                                                 *best_clock = clock;
817                                                 err_most = this_err;
818                                                 max_n = clock.n;
819                                                 found = true;
820                                         }
821                                 }
822                         }
823                 }
824         }
825         return found;
826 }
827
828 /*
829  * Check if the calculated PLL configuration is more optimal compared to the
830  * best configuration and error found so far. Return the calculated error.
831  */
832 static bool vlv_PLL_is_optimal(struct drm_device *dev, int target_freq,
833                                const struct dpll *calculated_clock,
834                                const struct dpll *best_clock,
835                                unsigned int best_error_ppm,
836                                unsigned int *error_ppm)
837 {
838         /*
839          * For CHV ignore the error and consider only the P value.
840          * Prefer a bigger P value based on HW requirements.
841          */
842         if (IS_CHERRYVIEW(to_i915(dev))) {
843                 *error_ppm = 0;
844
845                 return calculated_clock->p > best_clock->p;
846         }
847
848         if (WARN_ON_ONCE(!target_freq))
849                 return false;
850
851         *error_ppm = div_u64(1000000ULL *
852                                 abs(target_freq - calculated_clock->dot),
853                              target_freq);
854         /*
855          * Prefer a better P value over a better (smaller) error if the error
856          * is small. Ensure this preference for future configurations too by
857          * setting the error to 0.
858          */
859         if (*error_ppm < 100 && calculated_clock->p > best_clock->p) {
860                 *error_ppm = 0;
861
862                 return true;
863         }
864
865         return *error_ppm + 10 < best_error_ppm;
866 }
867
868 /*
869  * Returns a set of divisors for the desired target clock with the given
870  * refclk, or FALSE.  The returned values represent the clock equation:
871  * reflck * (5 * (m1 + 2) + (m2 + 2)) / (n + 2) / p1 / p2.
872  */
873 static bool
874 vlv_find_best_dpll(const struct intel_limit *limit,
875                    struct intel_crtc_state *crtc_state,
876                    int target, int refclk, struct dpll *match_clock,
877                    struct dpll *best_clock)
878 {
879         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
880         struct drm_device *dev = crtc->base.dev;
881         struct dpll clock;
882         unsigned int bestppm = 1000000;
883         /* min update 19.2 MHz */
884         int max_n = min(limit->n.max, refclk / 19200);
885         bool found = false;
886
887         target *= 5; /* fast clock */
888
889         memset(best_clock, 0, sizeof(*best_clock));
890
891         /* based on hardware requirement, prefer smaller n to precision */
892         for (clock.n = limit->n.min; clock.n <= max_n; clock.n++) {
893                 for (clock.p1 = limit->p1.max; clock.p1 >= limit->p1.min; clock.p1--) {
894                         for (clock.p2 = limit->p2.p2_fast; clock.p2 >= limit->p2.p2_slow;
895                              clock.p2 -= clock.p2 > 10 ? 2 : 1) {
896                                 clock.p = clock.p1 * clock.p2;
897                                 /* based on hardware requirement, prefer bigger m1,m2 values */
898                                 for (clock.m1 = limit->m1.min; clock.m1 <= limit->m1.max; clock.m1++) {
899                                         unsigned int ppm;
900
901                                         clock.m2 = DIV_ROUND_CLOSEST(target * clock.p * clock.n,
902                                                                      refclk * clock.m1);
903
904                                         vlv_calc_dpll_params(refclk, &clock);
905
906                                         if (!intel_PLL_is_valid(to_i915(dev),
907                                                                 limit,
908                                                                 &clock))
909                                                 continue;
910
911                                         if (!vlv_PLL_is_optimal(dev, target,
912                                                                 &clock,
913                                                                 best_clock,
914                                                                 bestppm, &ppm))
915                                                 continue;
916
917                                         *best_clock = clock;
918                                         bestppm = ppm;
919                                         found = true;
920                                 }
921                         }
922                 }
923         }
924
925         return found;
926 }
927
928 /*
929  * Returns a set of divisors for the desired target clock with the given
930  * refclk, or FALSE.  The returned values represent the clock equation:
931  * reflck * (5 * (m1 + 2) + (m2 + 2)) / (n + 2) / p1 / p2.
932  */
933 static bool
934 chv_find_best_dpll(const struct intel_limit *limit,
935                    struct intel_crtc_state *crtc_state,
936                    int target, int refclk, struct dpll *match_clock,
937                    struct dpll *best_clock)
938 {
939         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
940         struct drm_device *dev = crtc->base.dev;
941         unsigned int best_error_ppm;
942         struct dpll clock;
943         u64 m2;
944         int found = false;
945
946         memset(best_clock, 0, sizeof(*best_clock));
947         best_error_ppm = 1000000;
948
949         /*
950          * Based on hardware doc, the n always set to 1, and m1 always
951          * set to 2.  If requires to support 200Mhz refclk, we need to
952          * revisit this because n may not 1 anymore.
953          */
954         clock.n = 1, clock.m1 = 2;
955         target *= 5;    /* fast clock */
956
957         for (clock.p1 = limit->p1.max; clock.p1 >= limit->p1.min; clock.p1--) {
958                 for (clock.p2 = limit->p2.p2_fast;
959                                 clock.p2 >= limit->p2.p2_slow;
960                                 clock.p2 -= clock.p2 > 10 ? 2 : 1) {
961                         unsigned int error_ppm;
962
963                         clock.p = clock.p1 * clock.p2;
964
965                         m2 = DIV_ROUND_CLOSEST_ULL(mul_u32_u32(target, clock.p * clock.n) << 22,
966                                                    refclk * clock.m1);
967
968                         if (m2 > INT_MAX/clock.m1)
969                                 continue;
970
971                         clock.m2 = m2;
972
973                         chv_calc_dpll_params(refclk, &clock);
974
975                         if (!intel_PLL_is_valid(to_i915(dev), limit, &clock))
976                                 continue;
977
978                         if (!vlv_PLL_is_optimal(dev, target, &clock, best_clock,
979                                                 best_error_ppm, &error_ppm))
980                                 continue;
981
982                         *best_clock = clock;
983                         best_error_ppm = error_ppm;
984                         found = true;
985                 }
986         }
987
988         return found;
989 }
990
991 bool bxt_find_best_dpll(struct intel_crtc_state *crtc_state,
992                         struct dpll *best_clock)
993 {
994         int refclk = 100000;
995         const struct intel_limit *limit = &intel_limits_bxt;
996
997         return chv_find_best_dpll(limit, crtc_state,
998                                   crtc_state->port_clock, refclk,
999                                   NULL, best_clock);
1000 }
1001
1002 bool intel_crtc_active(struct intel_crtc *crtc)
1003 {
1004         /* Be paranoid as we can arrive here with only partial
1005          * state retrieved from the hardware during setup.
1006          *
1007          * We can ditch the adjusted_mode.crtc_clock check as soon
1008          * as Haswell has gained clock readout/fastboot support.
1009          *
1010          * We can ditch the crtc->primary->state->fb check as soon as we can
1011          * properly reconstruct framebuffers.
1012          *
1013          * FIXME: The intel_crtc->active here should be switched to
1014          * crtc->state->active once we have proper CRTC states wired up
1015          * for atomic.
1016          */
1017         return crtc->active && crtc->base.primary->state->fb &&
1018                 crtc->config->base.adjusted_mode.crtc_clock;
1019 }
1020
1021 enum transcoder intel_pipe_to_cpu_transcoder(struct drm_i915_private *dev_priv,
1022                                              enum pipe pipe)
1023 {
1024         struct intel_crtc *crtc = intel_get_crtc_for_pipe(dev_priv, pipe);
1025
1026         return crtc->config->cpu_transcoder;
1027 }
1028
1029 static bool pipe_scanline_is_moving(struct drm_i915_private *dev_priv,
1030                                     enum pipe pipe)
1031 {
1032         i915_reg_t reg = PIPEDSL(pipe);
1033         u32 line1, line2;
1034         u32 line_mask;
1035
1036         if (IS_GEN(dev_priv, 2))
1037                 line_mask = DSL_LINEMASK_GEN2;
1038         else
1039                 line_mask = DSL_LINEMASK_GEN3;
1040
1041         line1 = I915_READ(reg) & line_mask;
1042         msleep(5);
1043         line2 = I915_READ(reg) & line_mask;
1044
1045         return line1 != line2;
1046 }
1047
1048 static void wait_for_pipe_scanline_moving(struct intel_crtc *crtc, bool state)
1049 {
1050         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1051         enum pipe pipe = crtc->pipe;
1052
1053         /* Wait for the display line to settle/start moving */
1054         if (wait_for(pipe_scanline_is_moving(dev_priv, pipe) == state, 100))
1055                 DRM_ERROR("pipe %c scanline %s wait timed out\n",
1056                           pipe_name(pipe), onoff(state));
1057 }
1058
1059 static void intel_wait_for_pipe_scanline_stopped(struct intel_crtc *crtc)
1060 {
1061         wait_for_pipe_scanline_moving(crtc, false);
1062 }
1063
1064 static void intel_wait_for_pipe_scanline_moving(struct intel_crtc *crtc)
1065 {
1066         wait_for_pipe_scanline_moving(crtc, true);
1067 }
1068
1069 static void
1070 intel_wait_for_pipe_off(const struct intel_crtc_state *old_crtc_state)
1071 {
1072         struct intel_crtc *crtc = to_intel_crtc(old_crtc_state->base.crtc);
1073         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1074
1075         if (INTEL_GEN(dev_priv) >= 4) {
1076                 enum transcoder cpu_transcoder = old_crtc_state->cpu_transcoder;
1077                 i915_reg_t reg = PIPECONF(cpu_transcoder);
1078
1079                 /* Wait for the Pipe State to go off */
1080                 if (intel_de_wait_for_clear(dev_priv, reg,
1081                                             I965_PIPECONF_ACTIVE, 100))
1082                         WARN(1, "pipe_off wait timed out\n");
1083         } else {
1084                 intel_wait_for_pipe_scanline_stopped(crtc);
1085         }
1086 }
1087
1088 /* Only for pre-ILK configs */
1089 void assert_pll(struct drm_i915_private *dev_priv,
1090                 enum pipe pipe, bool state)
1091 {
1092         u32 val;
1093         bool cur_state;
1094
1095         val = I915_READ(DPLL(pipe));
1096         cur_state = !!(val & DPLL_VCO_ENABLE);
1097         I915_STATE_WARN(cur_state != state,
1098              "PLL state assertion failure (expected %s, current %s)\n",
1099                         onoff(state), onoff(cur_state));
1100 }
1101
1102 /* XXX: the dsi pll is shared between MIPI DSI ports */
1103 void assert_dsi_pll(struct drm_i915_private *dev_priv, bool state)
1104 {
1105         u32 val;
1106         bool cur_state;
1107
1108         vlv_cck_get(dev_priv);
1109         val = vlv_cck_read(dev_priv, CCK_REG_DSI_PLL_CONTROL);
1110         vlv_cck_put(dev_priv);
1111
1112         cur_state = val & DSI_PLL_VCO_EN;
1113         I915_STATE_WARN(cur_state != state,
1114              "DSI PLL state assertion failure (expected %s, current %s)\n",
1115                         onoff(state), onoff(cur_state));
1116 }
1117
1118 static void assert_fdi_tx(struct drm_i915_private *dev_priv,
1119                           enum pipe pipe, bool state)
1120 {
1121         bool cur_state;
1122         enum transcoder cpu_transcoder = intel_pipe_to_cpu_transcoder(dev_priv,
1123                                                                       pipe);
1124
1125         if (HAS_DDI(dev_priv)) {
1126                 /* DDI does not have a specific FDI_TX register */
1127                 u32 val = I915_READ(TRANS_DDI_FUNC_CTL(cpu_transcoder));
1128                 cur_state = !!(val & TRANS_DDI_FUNC_ENABLE);
1129         } else {
1130                 u32 val = I915_READ(FDI_TX_CTL(pipe));
1131                 cur_state = !!(val & FDI_TX_ENABLE);
1132         }
1133         I915_STATE_WARN(cur_state != state,
1134              "FDI TX state assertion failure (expected %s, current %s)\n",
1135                         onoff(state), onoff(cur_state));
1136 }
1137 #define assert_fdi_tx_enabled(d, p) assert_fdi_tx(d, p, true)
1138 #define assert_fdi_tx_disabled(d, p) assert_fdi_tx(d, p, false)
1139
1140 static void assert_fdi_rx(struct drm_i915_private *dev_priv,
1141                           enum pipe pipe, bool state)
1142 {
1143         u32 val;
1144         bool cur_state;
1145
1146         val = I915_READ(FDI_RX_CTL(pipe));
1147         cur_state = !!(val & FDI_RX_ENABLE);
1148         I915_STATE_WARN(cur_state != state,
1149              "FDI RX state assertion failure (expected %s, current %s)\n",
1150                         onoff(state), onoff(cur_state));
1151 }
1152 #define assert_fdi_rx_enabled(d, p) assert_fdi_rx(d, p, true)
1153 #define assert_fdi_rx_disabled(d, p) assert_fdi_rx(d, p, false)
1154
1155 static void assert_fdi_tx_pll_enabled(struct drm_i915_private *dev_priv,
1156                                       enum pipe pipe)
1157 {
1158         u32 val;
1159
1160         /* ILK FDI PLL is always enabled */
1161         if (IS_GEN(dev_priv, 5))
1162                 return;
1163
1164         /* On Haswell, DDI ports are responsible for the FDI PLL setup */
1165         if (HAS_DDI(dev_priv))
1166                 return;
1167
1168         val = I915_READ(FDI_TX_CTL(pipe));
1169         I915_STATE_WARN(!(val & FDI_TX_PLL_ENABLE), "FDI TX PLL assertion failure, should be active but is disabled\n");
1170 }
1171
1172 void assert_fdi_rx_pll(struct drm_i915_private *dev_priv,
1173                        enum pipe pipe, bool state)
1174 {
1175         u32 val;
1176         bool cur_state;
1177
1178         val = I915_READ(FDI_RX_CTL(pipe));
1179         cur_state = !!(val & FDI_RX_PLL_ENABLE);
1180         I915_STATE_WARN(cur_state != state,
1181              "FDI RX PLL assertion failure (expected %s, current %s)\n",
1182                         onoff(state), onoff(cur_state));
1183 }
1184
1185 void assert_panel_unlocked(struct drm_i915_private *dev_priv, enum pipe pipe)
1186 {
1187         i915_reg_t pp_reg;
1188         u32 val;
1189         enum pipe panel_pipe = INVALID_PIPE;
1190         bool locked = true;
1191
1192         if (WARN_ON(HAS_DDI(dev_priv)))
1193                 return;
1194
1195         if (HAS_PCH_SPLIT(dev_priv)) {
1196                 u32 port_sel;
1197
1198                 pp_reg = PP_CONTROL(0);
1199                 port_sel = I915_READ(PP_ON_DELAYS(0)) & PANEL_PORT_SELECT_MASK;
1200
1201                 switch (port_sel) {
1202                 case PANEL_PORT_SELECT_LVDS:
1203                         intel_lvds_port_enabled(dev_priv, PCH_LVDS, &panel_pipe);
1204                         break;
1205                 case PANEL_PORT_SELECT_DPA:
1206                         intel_dp_port_enabled(dev_priv, DP_A, PORT_A, &panel_pipe);
1207                         break;
1208                 case PANEL_PORT_SELECT_DPC:
1209                         intel_dp_port_enabled(dev_priv, PCH_DP_C, PORT_C, &panel_pipe);
1210                         break;
1211                 case PANEL_PORT_SELECT_DPD:
1212                         intel_dp_port_enabled(dev_priv, PCH_DP_D, PORT_D, &panel_pipe);
1213                         break;
1214                 default:
1215                         MISSING_CASE(port_sel);
1216                         break;
1217                 }
1218         } else if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv)) {
1219                 /* presumably write lock depends on pipe, not port select */
1220                 pp_reg = PP_CONTROL(pipe);
1221                 panel_pipe = pipe;
1222         } else {
1223                 u32 port_sel;
1224
1225                 pp_reg = PP_CONTROL(0);
1226                 port_sel = I915_READ(PP_ON_DELAYS(0)) & PANEL_PORT_SELECT_MASK;
1227
1228                 WARN_ON(port_sel != PANEL_PORT_SELECT_LVDS);
1229                 intel_lvds_port_enabled(dev_priv, LVDS, &panel_pipe);
1230         }
1231
1232         val = I915_READ(pp_reg);
1233         if (!(val & PANEL_POWER_ON) ||
1234             ((val & PANEL_UNLOCK_MASK) == PANEL_UNLOCK_REGS))
1235                 locked = false;
1236
1237         I915_STATE_WARN(panel_pipe == pipe && locked,
1238              "panel assertion failure, pipe %c regs locked\n",
1239              pipe_name(pipe));
1240 }
1241
1242 void assert_pipe(struct drm_i915_private *dev_priv,
1243                  enum pipe pipe, bool state)
1244 {
1245         bool cur_state;
1246         enum transcoder cpu_transcoder = intel_pipe_to_cpu_transcoder(dev_priv,
1247                                                                       pipe);
1248         enum intel_display_power_domain power_domain;
1249         intel_wakeref_t wakeref;
1250
1251         /* we keep both pipes enabled on 830 */
1252         if (IS_I830(dev_priv))
1253                 state = true;
1254
1255         power_domain = POWER_DOMAIN_TRANSCODER(cpu_transcoder);
1256         wakeref = intel_display_power_get_if_enabled(dev_priv, power_domain);
1257         if (wakeref) {
1258                 u32 val = I915_READ(PIPECONF(cpu_transcoder));
1259                 cur_state = !!(val & PIPECONF_ENABLE);
1260
1261                 intel_display_power_put(dev_priv, power_domain, wakeref);
1262         } else {
1263                 cur_state = false;
1264         }
1265
1266         I915_STATE_WARN(cur_state != state,
1267              "pipe %c assertion failure (expected %s, current %s)\n",
1268                         pipe_name(pipe), onoff(state), onoff(cur_state));
1269 }
1270
1271 static void assert_plane(struct intel_plane *plane, bool state)
1272 {
1273         enum pipe pipe;
1274         bool cur_state;
1275
1276         cur_state = plane->get_hw_state(plane, &pipe);
1277
1278         I915_STATE_WARN(cur_state != state,
1279                         "%s assertion failure (expected %s, current %s)\n",
1280                         plane->base.name, onoff(state), onoff(cur_state));
1281 }
1282
1283 #define assert_plane_enabled(p) assert_plane(p, true)
1284 #define assert_plane_disabled(p) assert_plane(p, false)
1285
1286 static void assert_planes_disabled(struct intel_crtc *crtc)
1287 {
1288         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1289         struct intel_plane *plane;
1290
1291         for_each_intel_plane_on_crtc(&dev_priv->drm, crtc, plane)
1292                 assert_plane_disabled(plane);
1293 }
1294
1295 static void assert_vblank_disabled(struct drm_crtc *crtc)
1296 {
1297         if (I915_STATE_WARN_ON(drm_crtc_vblank_get(crtc) == 0))
1298                 drm_crtc_vblank_put(crtc);
1299 }
1300
1301 void assert_pch_transcoder_disabled(struct drm_i915_private *dev_priv,
1302                                     enum pipe pipe)
1303 {
1304         u32 val;
1305         bool enabled;
1306
1307         val = I915_READ(PCH_TRANSCONF(pipe));
1308         enabled = !!(val & TRANS_ENABLE);
1309         I915_STATE_WARN(enabled,
1310              "transcoder assertion failed, should be off on pipe %c but is still active\n",
1311              pipe_name(pipe));
1312 }
1313
1314 static void assert_pch_dp_disabled(struct drm_i915_private *dev_priv,
1315                                    enum pipe pipe, enum port port,
1316                                    i915_reg_t dp_reg)
1317 {
1318         enum pipe port_pipe;
1319         bool state;
1320
1321         state = intel_dp_port_enabled(dev_priv, dp_reg, port, &port_pipe);
1322
1323         I915_STATE_WARN(state && port_pipe == pipe,
1324                         "PCH DP %c enabled on transcoder %c, should be disabled\n",
1325                         port_name(port), pipe_name(pipe));
1326
1327         I915_STATE_WARN(HAS_PCH_IBX(dev_priv) && !state && port_pipe == PIPE_B,
1328                         "IBX PCH DP %c still using transcoder B\n",
1329                         port_name(port));
1330 }
1331
1332 static void assert_pch_hdmi_disabled(struct drm_i915_private *dev_priv,
1333                                      enum pipe pipe, enum port port,
1334                                      i915_reg_t hdmi_reg)
1335 {
1336         enum pipe port_pipe;
1337         bool state;
1338
1339         state = intel_sdvo_port_enabled(dev_priv, hdmi_reg, &port_pipe);
1340
1341         I915_STATE_WARN(state && port_pipe == pipe,
1342                         "PCH HDMI %c enabled on transcoder %c, should be disabled\n",
1343                         port_name(port), pipe_name(pipe));
1344
1345         I915_STATE_WARN(HAS_PCH_IBX(dev_priv) && !state && port_pipe == PIPE_B,
1346                         "IBX PCH HDMI %c still using transcoder B\n",
1347                         port_name(port));
1348 }
1349
1350 static void assert_pch_ports_disabled(struct drm_i915_private *dev_priv,
1351                                       enum pipe pipe)
1352 {
1353         enum pipe port_pipe;
1354
1355         assert_pch_dp_disabled(dev_priv, pipe, PORT_B, PCH_DP_B);
1356         assert_pch_dp_disabled(dev_priv, pipe, PORT_C, PCH_DP_C);
1357         assert_pch_dp_disabled(dev_priv, pipe, PORT_D, PCH_DP_D);
1358
1359         I915_STATE_WARN(intel_crt_port_enabled(dev_priv, PCH_ADPA, &port_pipe) &&
1360                         port_pipe == pipe,
1361                         "PCH VGA enabled on transcoder %c, should be disabled\n",
1362                         pipe_name(pipe));
1363
1364         I915_STATE_WARN(intel_lvds_port_enabled(dev_priv, PCH_LVDS, &port_pipe) &&
1365                         port_pipe == pipe,
1366                         "PCH LVDS enabled on transcoder %c, should be disabled\n",
1367                         pipe_name(pipe));
1368
1369         /* PCH SDVOB multiplex with HDMIB */
1370         assert_pch_hdmi_disabled(dev_priv, pipe, PORT_B, PCH_HDMIB);
1371         assert_pch_hdmi_disabled(dev_priv, pipe, PORT_C, PCH_HDMIC);
1372         assert_pch_hdmi_disabled(dev_priv, pipe, PORT_D, PCH_HDMID);
1373 }
1374
1375 static void _vlv_enable_pll(struct intel_crtc *crtc,
1376                             const struct intel_crtc_state *pipe_config)
1377 {
1378         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1379         enum pipe pipe = crtc->pipe;
1380
1381         I915_WRITE(DPLL(pipe), pipe_config->dpll_hw_state.dpll);
1382         POSTING_READ(DPLL(pipe));
1383         udelay(150);
1384
1385         if (intel_de_wait_for_set(dev_priv, DPLL(pipe), DPLL_LOCK_VLV, 1))
1386                 DRM_ERROR("DPLL %d failed to lock\n", pipe);
1387 }
1388
1389 static void vlv_enable_pll(struct intel_crtc *crtc,
1390                            const struct intel_crtc_state *pipe_config)
1391 {
1392         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1393         enum pipe pipe = crtc->pipe;
1394
1395         assert_pipe_disabled(dev_priv, pipe);
1396
1397         /* PLL is protected by panel, make sure we can write it */
1398         assert_panel_unlocked(dev_priv, pipe);
1399
1400         if (pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE)
1401                 _vlv_enable_pll(crtc, pipe_config);
1402
1403         I915_WRITE(DPLL_MD(pipe), pipe_config->dpll_hw_state.dpll_md);
1404         POSTING_READ(DPLL_MD(pipe));
1405 }
1406
1407
1408 static void _chv_enable_pll(struct intel_crtc *crtc,
1409                             const struct intel_crtc_state *pipe_config)
1410 {
1411         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1412         enum pipe pipe = crtc->pipe;
1413         enum dpio_channel port = vlv_pipe_to_channel(pipe);
1414         u32 tmp;
1415
1416         vlv_dpio_get(dev_priv);
1417
1418         /* Enable back the 10bit clock to display controller */
1419         tmp = vlv_dpio_read(dev_priv, pipe, CHV_CMN_DW14(port));
1420         tmp |= DPIO_DCLKP_EN;
1421         vlv_dpio_write(dev_priv, pipe, CHV_CMN_DW14(port), tmp);
1422
1423         vlv_dpio_put(dev_priv);
1424
1425         /*
1426          * Need to wait > 100ns between dclkp clock enable bit and PLL enable.
1427          */
1428         udelay(1);
1429
1430         /* Enable PLL */
1431         I915_WRITE(DPLL(pipe), pipe_config->dpll_hw_state.dpll);
1432
1433         /* Check PLL is locked */
1434         if (intel_de_wait_for_set(dev_priv, DPLL(pipe), DPLL_LOCK_VLV, 1))
1435                 DRM_ERROR("PLL %d failed to lock\n", pipe);
1436 }
1437
1438 static void chv_enable_pll(struct intel_crtc *crtc,
1439                            const struct intel_crtc_state *pipe_config)
1440 {
1441         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1442         enum pipe pipe = crtc->pipe;
1443
1444         assert_pipe_disabled(dev_priv, pipe);
1445
1446         /* PLL is protected by panel, make sure we can write it */
1447         assert_panel_unlocked(dev_priv, pipe);
1448
1449         if (pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE)
1450                 _chv_enable_pll(crtc, pipe_config);
1451
1452         if (pipe != PIPE_A) {
1453                 /*
1454                  * WaPixelRepeatModeFixForC0:chv
1455                  *
1456                  * DPLLCMD is AWOL. Use chicken bits to propagate
1457                  * the value from DPLLBMD to either pipe B or C.
1458                  */
1459                 I915_WRITE(CBR4_VLV, CBR_DPLLBMD_PIPE(pipe));
1460                 I915_WRITE(DPLL_MD(PIPE_B), pipe_config->dpll_hw_state.dpll_md);
1461                 I915_WRITE(CBR4_VLV, 0);
1462                 dev_priv->chv_dpll_md[pipe] = pipe_config->dpll_hw_state.dpll_md;
1463
1464                 /*
1465                  * DPLLB VGA mode also seems to cause problems.
1466                  * We should always have it disabled.
1467                  */
1468                 WARN_ON((I915_READ(DPLL(PIPE_B)) & DPLL_VGA_MODE_DIS) == 0);
1469         } else {
1470                 I915_WRITE(DPLL_MD(pipe), pipe_config->dpll_hw_state.dpll_md);
1471                 POSTING_READ(DPLL_MD(pipe));
1472         }
1473 }
1474
1475 static bool i9xx_has_pps(struct drm_i915_private *dev_priv)
1476 {
1477         if (IS_I830(dev_priv))
1478                 return false;
1479
1480         return IS_PINEVIEW(dev_priv) || IS_MOBILE(dev_priv);
1481 }
1482
1483 static void i9xx_enable_pll(struct intel_crtc *crtc,
1484                             const struct intel_crtc_state *crtc_state)
1485 {
1486         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1487         i915_reg_t reg = DPLL(crtc->pipe);
1488         u32 dpll = crtc_state->dpll_hw_state.dpll;
1489         int i;
1490
1491         assert_pipe_disabled(dev_priv, crtc->pipe);
1492
1493         /* PLL is protected by panel, make sure we can write it */
1494         if (i9xx_has_pps(dev_priv))
1495                 assert_panel_unlocked(dev_priv, crtc->pipe);
1496
1497         /*
1498          * Apparently we need to have VGA mode enabled prior to changing
1499          * the P1/P2 dividers. Otherwise the DPLL will keep using the old
1500          * dividers, even though the register value does change.
1501          */
1502         I915_WRITE(reg, dpll & ~DPLL_VGA_MODE_DIS);
1503         I915_WRITE(reg, dpll);
1504
1505         /* Wait for the clocks to stabilize. */
1506         POSTING_READ(reg);
1507         udelay(150);
1508
1509         if (INTEL_GEN(dev_priv) >= 4) {
1510                 I915_WRITE(DPLL_MD(crtc->pipe),
1511                            crtc_state->dpll_hw_state.dpll_md);
1512         } else {
1513                 /* The pixel multiplier can only be updated once the
1514                  * DPLL is enabled and the clocks are stable.
1515                  *
1516                  * So write it again.
1517                  */
1518                 I915_WRITE(reg, dpll);
1519         }
1520
1521         /* We do this three times for luck */
1522         for (i = 0; i < 3; i++) {
1523                 I915_WRITE(reg, dpll);
1524                 POSTING_READ(reg);
1525                 udelay(150); /* wait for warmup */
1526         }
1527 }
1528
1529 static void i9xx_disable_pll(const struct intel_crtc_state *crtc_state)
1530 {
1531         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
1532         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1533         enum pipe pipe = crtc->pipe;
1534
1535         /* Don't disable pipe or pipe PLLs if needed */
1536         if (IS_I830(dev_priv))
1537                 return;
1538
1539         /* Make sure the pipe isn't still relying on us */
1540         assert_pipe_disabled(dev_priv, pipe);
1541
1542         I915_WRITE(DPLL(pipe), DPLL_VGA_MODE_DIS);
1543         POSTING_READ(DPLL(pipe));
1544 }
1545
1546 static void vlv_disable_pll(struct drm_i915_private *dev_priv, enum pipe pipe)
1547 {
1548         u32 val;
1549
1550         /* Make sure the pipe isn't still relying on us */
1551         assert_pipe_disabled(dev_priv, pipe);
1552
1553         val = DPLL_INTEGRATED_REF_CLK_VLV |
1554                 DPLL_REF_CLK_ENABLE_VLV | DPLL_VGA_MODE_DIS;
1555         if (pipe != PIPE_A)
1556                 val |= DPLL_INTEGRATED_CRI_CLK_VLV;
1557
1558         I915_WRITE(DPLL(pipe), val);
1559         POSTING_READ(DPLL(pipe));
1560 }
1561
1562 static void chv_disable_pll(struct drm_i915_private *dev_priv, enum pipe pipe)
1563 {
1564         enum dpio_channel port = vlv_pipe_to_channel(pipe);
1565         u32 val;
1566
1567         /* Make sure the pipe isn't still relying on us */
1568         assert_pipe_disabled(dev_priv, pipe);
1569
1570         val = DPLL_SSC_REF_CLK_CHV |
1571                 DPLL_REF_CLK_ENABLE_VLV | DPLL_VGA_MODE_DIS;
1572         if (pipe != PIPE_A)
1573                 val |= DPLL_INTEGRATED_CRI_CLK_VLV;
1574
1575         I915_WRITE(DPLL(pipe), val);
1576         POSTING_READ(DPLL(pipe));
1577
1578         vlv_dpio_get(dev_priv);
1579
1580         /* Disable 10bit clock to display controller */
1581         val = vlv_dpio_read(dev_priv, pipe, CHV_CMN_DW14(port));
1582         val &= ~DPIO_DCLKP_EN;
1583         vlv_dpio_write(dev_priv, pipe, CHV_CMN_DW14(port), val);
1584
1585         vlv_dpio_put(dev_priv);
1586 }
1587
1588 void vlv_wait_port_ready(struct drm_i915_private *dev_priv,
1589                          struct intel_digital_port *dport,
1590                          unsigned int expected_mask)
1591 {
1592         u32 port_mask;
1593         i915_reg_t dpll_reg;
1594
1595         switch (dport->base.port) {
1596         case PORT_B:
1597                 port_mask = DPLL_PORTB_READY_MASK;
1598                 dpll_reg = DPLL(0);
1599                 break;
1600         case PORT_C:
1601                 port_mask = DPLL_PORTC_READY_MASK;
1602                 dpll_reg = DPLL(0);
1603                 expected_mask <<= 4;
1604                 break;
1605         case PORT_D:
1606                 port_mask = DPLL_PORTD_READY_MASK;
1607                 dpll_reg = DPIO_PHY_STATUS;
1608                 break;
1609         default:
1610                 BUG();
1611         }
1612
1613         if (intel_de_wait_for_register(dev_priv, dpll_reg,
1614                                        port_mask, expected_mask, 1000))
1615                 WARN(1, "timed out waiting for [ENCODER:%d:%s] port ready: got 0x%x, expected 0x%x\n",
1616                      dport->base.base.base.id, dport->base.base.name,
1617                      I915_READ(dpll_reg) & port_mask, expected_mask);
1618 }
1619
1620 static void ironlake_enable_pch_transcoder(const struct intel_crtc_state *crtc_state)
1621 {
1622         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
1623         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1624         enum pipe pipe = crtc->pipe;
1625         i915_reg_t reg;
1626         u32 val, pipeconf_val;
1627
1628         /* Make sure PCH DPLL is enabled */
1629         assert_shared_dpll_enabled(dev_priv, crtc_state->shared_dpll);
1630
1631         /* FDI must be feeding us bits for PCH ports */
1632         assert_fdi_tx_enabled(dev_priv, pipe);
1633         assert_fdi_rx_enabled(dev_priv, pipe);
1634
1635         if (HAS_PCH_CPT(dev_priv)) {
1636                 /* Workaround: Set the timing override bit before enabling the
1637                  * pch transcoder. */
1638                 reg = TRANS_CHICKEN2(pipe);
1639                 val = I915_READ(reg);
1640                 val |= TRANS_CHICKEN2_TIMING_OVERRIDE;
1641                 I915_WRITE(reg, val);
1642         }
1643
1644         reg = PCH_TRANSCONF(pipe);
1645         val = I915_READ(reg);
1646         pipeconf_val = I915_READ(PIPECONF(pipe));
1647
1648         if (HAS_PCH_IBX(dev_priv)) {
1649                 /*
1650                  * Make the BPC in transcoder be consistent with
1651                  * that in pipeconf reg. For HDMI we must use 8bpc
1652                  * here for both 8bpc and 12bpc.
1653                  */
1654                 val &= ~PIPECONF_BPC_MASK;
1655                 if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_HDMI))
1656                         val |= PIPECONF_8BPC;
1657                 else
1658                         val |= pipeconf_val & PIPECONF_BPC_MASK;
1659         }
1660
1661         val &= ~TRANS_INTERLACE_MASK;
1662         if ((pipeconf_val & PIPECONF_INTERLACE_MASK) == PIPECONF_INTERLACED_ILK) {
1663                 if (HAS_PCH_IBX(dev_priv) &&
1664                     intel_crtc_has_type(crtc_state, INTEL_OUTPUT_SDVO))
1665                         val |= TRANS_LEGACY_INTERLACED_ILK;
1666                 else
1667                         val |= TRANS_INTERLACED;
1668         } else {
1669                 val |= TRANS_PROGRESSIVE;
1670         }
1671
1672         I915_WRITE(reg, val | TRANS_ENABLE);
1673         if (intel_de_wait_for_set(dev_priv, reg, TRANS_STATE_ENABLE, 100))
1674                 DRM_ERROR("failed to enable transcoder %c\n", pipe_name(pipe));
1675 }
1676
1677 static void lpt_enable_pch_transcoder(struct drm_i915_private *dev_priv,
1678                                       enum transcoder cpu_transcoder)
1679 {
1680         u32 val, pipeconf_val;
1681
1682         /* FDI must be feeding us bits for PCH ports */
1683         assert_fdi_tx_enabled(dev_priv, (enum pipe) cpu_transcoder);
1684         assert_fdi_rx_enabled(dev_priv, PIPE_A);
1685
1686         /* Workaround: set timing override bit. */
1687         val = I915_READ(TRANS_CHICKEN2(PIPE_A));
1688         val |= TRANS_CHICKEN2_TIMING_OVERRIDE;
1689         I915_WRITE(TRANS_CHICKEN2(PIPE_A), val);
1690
1691         val = TRANS_ENABLE;
1692         pipeconf_val = I915_READ(PIPECONF(cpu_transcoder));
1693
1694         if ((pipeconf_val & PIPECONF_INTERLACE_MASK_HSW) ==
1695             PIPECONF_INTERLACED_ILK)
1696                 val |= TRANS_INTERLACED;
1697         else
1698                 val |= TRANS_PROGRESSIVE;
1699
1700         I915_WRITE(LPT_TRANSCONF, val);
1701         if (intel_de_wait_for_set(dev_priv, LPT_TRANSCONF,
1702                                   TRANS_STATE_ENABLE, 100))
1703                 DRM_ERROR("Failed to enable PCH transcoder\n");
1704 }
1705
1706 static void ironlake_disable_pch_transcoder(struct drm_i915_private *dev_priv,
1707                                             enum pipe pipe)
1708 {
1709         i915_reg_t reg;
1710         u32 val;
1711
1712         /* FDI relies on the transcoder */
1713         assert_fdi_tx_disabled(dev_priv, pipe);
1714         assert_fdi_rx_disabled(dev_priv, pipe);
1715
1716         /* Ports must be off as well */
1717         assert_pch_ports_disabled(dev_priv, pipe);
1718
1719         reg = PCH_TRANSCONF(pipe);
1720         val = I915_READ(reg);
1721         val &= ~TRANS_ENABLE;
1722         I915_WRITE(reg, val);
1723         /* wait for PCH transcoder off, transcoder state */
1724         if (intel_de_wait_for_clear(dev_priv, reg, TRANS_STATE_ENABLE, 50))
1725                 DRM_ERROR("failed to disable transcoder %c\n", pipe_name(pipe));
1726
1727         if (HAS_PCH_CPT(dev_priv)) {
1728                 /* Workaround: Clear the timing override chicken bit again. */
1729                 reg = TRANS_CHICKEN2(pipe);
1730                 val = I915_READ(reg);
1731                 val &= ~TRANS_CHICKEN2_TIMING_OVERRIDE;
1732                 I915_WRITE(reg, val);
1733         }
1734 }
1735
1736 void lpt_disable_pch_transcoder(struct drm_i915_private *dev_priv)
1737 {
1738         u32 val;
1739
1740         val = I915_READ(LPT_TRANSCONF);
1741         val &= ~TRANS_ENABLE;
1742         I915_WRITE(LPT_TRANSCONF, val);
1743         /* wait for PCH transcoder off, transcoder state */
1744         if (intel_de_wait_for_clear(dev_priv, LPT_TRANSCONF,
1745                                     TRANS_STATE_ENABLE, 50))
1746                 DRM_ERROR("Failed to disable PCH transcoder\n");
1747
1748         /* Workaround: clear timing override bit. */
1749         val = I915_READ(TRANS_CHICKEN2(PIPE_A));
1750         val &= ~TRANS_CHICKEN2_TIMING_OVERRIDE;
1751         I915_WRITE(TRANS_CHICKEN2(PIPE_A), val);
1752 }
1753
1754 enum pipe intel_crtc_pch_transcoder(struct intel_crtc *crtc)
1755 {
1756         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1757
1758         if (HAS_PCH_LPT(dev_priv))
1759                 return PIPE_A;
1760         else
1761                 return crtc->pipe;
1762 }
1763
1764 static u32 intel_crtc_max_vblank_count(const struct intel_crtc_state *crtc_state)
1765 {
1766         struct drm_i915_private *dev_priv = to_i915(crtc_state->base.crtc->dev);
1767
1768         /*
1769          * On i965gm the hardware frame counter reads
1770          * zero when the TV encoder is enabled :(
1771          */
1772         if (IS_I965GM(dev_priv) &&
1773             (crtc_state->output_types & BIT(INTEL_OUTPUT_TVOUT)))
1774                 return 0;
1775
1776         if (INTEL_GEN(dev_priv) >= 5 || IS_G4X(dev_priv))
1777                 return 0xffffffff; /* full 32 bit counter */
1778         else if (INTEL_GEN(dev_priv) >= 3)
1779                 return 0xffffff; /* only 24 bits of frame count */
1780         else
1781                 return 0; /* Gen2 doesn't have a hardware frame counter */
1782 }
1783
1784 static void intel_crtc_vblank_on(const struct intel_crtc_state *crtc_state)
1785 {
1786         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
1787
1788         drm_crtc_set_max_vblank_count(&crtc->base,
1789                                       intel_crtc_max_vblank_count(crtc_state));
1790         drm_crtc_vblank_on(&crtc->base);
1791 }
1792
1793 static void intel_enable_pipe(const struct intel_crtc_state *new_crtc_state)
1794 {
1795         struct intel_crtc *crtc = to_intel_crtc(new_crtc_state->base.crtc);
1796         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1797         enum transcoder cpu_transcoder = new_crtc_state->cpu_transcoder;
1798         enum pipe pipe = crtc->pipe;
1799         i915_reg_t reg;
1800         u32 val;
1801
1802         DRM_DEBUG_KMS("enabling pipe %c\n", pipe_name(pipe));
1803
1804         assert_planes_disabled(crtc);
1805
1806         /*
1807          * A pipe without a PLL won't actually be able to drive bits from
1808          * a plane.  On ILK+ the pipe PLLs are integrated, so we don't
1809          * need the check.
1810          */
1811         if (HAS_GMCH(dev_priv)) {
1812                 if (intel_crtc_has_type(new_crtc_state, INTEL_OUTPUT_DSI))
1813                         assert_dsi_pll_enabled(dev_priv);
1814                 else
1815                         assert_pll_enabled(dev_priv, pipe);
1816         } else {
1817                 if (new_crtc_state->has_pch_encoder) {
1818                         /* if driving the PCH, we need FDI enabled */
1819                         assert_fdi_rx_pll_enabled(dev_priv,
1820                                                   intel_crtc_pch_transcoder(crtc));
1821                         assert_fdi_tx_pll_enabled(dev_priv,
1822                                                   (enum pipe) cpu_transcoder);
1823                 }
1824                 /* FIXME: assert CPU port conditions for SNB+ */
1825         }
1826
1827         trace_intel_pipe_enable(crtc);
1828
1829         reg = PIPECONF(cpu_transcoder);
1830         val = I915_READ(reg);
1831         if (val & PIPECONF_ENABLE) {
1832                 /* we keep both pipes enabled on 830 */
1833                 WARN_ON(!IS_I830(dev_priv));
1834                 return;
1835         }
1836
1837         I915_WRITE(reg, val | PIPECONF_ENABLE);
1838         POSTING_READ(reg);
1839
1840         /*
1841          * Until the pipe starts PIPEDSL reads will return a stale value,
1842          * which causes an apparent vblank timestamp jump when PIPEDSL
1843          * resets to its proper value. That also messes up the frame count
1844          * when it's derived from the timestamps. So let's wait for the
1845          * pipe to start properly before we call drm_crtc_vblank_on()
1846          */
1847         if (intel_crtc_max_vblank_count(new_crtc_state) == 0)
1848                 intel_wait_for_pipe_scanline_moving(crtc);
1849 }
1850
1851 static void intel_disable_pipe(const struct intel_crtc_state *old_crtc_state)
1852 {
1853         struct intel_crtc *crtc = to_intel_crtc(old_crtc_state->base.crtc);
1854         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1855         enum transcoder cpu_transcoder = old_crtc_state->cpu_transcoder;
1856         enum pipe pipe = crtc->pipe;
1857         i915_reg_t reg;
1858         u32 val;
1859
1860         DRM_DEBUG_KMS("disabling pipe %c\n", pipe_name(pipe));
1861
1862         /*
1863          * Make sure planes won't keep trying to pump pixels to us,
1864          * or we might hang the display.
1865          */
1866         assert_planes_disabled(crtc);
1867
1868         trace_intel_pipe_disable(crtc);
1869
1870         reg = PIPECONF(cpu_transcoder);
1871         val = I915_READ(reg);
1872         if ((val & PIPECONF_ENABLE) == 0)
1873                 return;
1874
1875         /*
1876          * Double wide has implications for planes
1877          * so best keep it disabled when not needed.
1878          */
1879         if (old_crtc_state->double_wide)
1880                 val &= ~PIPECONF_DOUBLE_WIDE;
1881
1882         /* Don't disable pipe or pipe PLLs if needed */
1883         if (!IS_I830(dev_priv))
1884                 val &= ~PIPECONF_ENABLE;
1885
1886         I915_WRITE(reg, val);
1887         if ((val & PIPECONF_ENABLE) == 0)
1888                 intel_wait_for_pipe_off(old_crtc_state);
1889 }
1890
1891 static unsigned int intel_tile_size(const struct drm_i915_private *dev_priv)
1892 {
1893         return IS_GEN(dev_priv, 2) ? 2048 : 4096;
1894 }
1895
1896 static unsigned int
1897 intel_tile_width_bytes(const struct drm_framebuffer *fb, int color_plane)
1898 {
1899         struct drm_i915_private *dev_priv = to_i915(fb->dev);
1900         unsigned int cpp = fb->format->cpp[color_plane];
1901
1902         switch (fb->modifier) {
1903         case DRM_FORMAT_MOD_LINEAR:
1904                 return intel_tile_size(dev_priv);
1905         case I915_FORMAT_MOD_X_TILED:
1906                 if (IS_GEN(dev_priv, 2))
1907                         return 128;
1908                 else
1909                         return 512;
1910         case I915_FORMAT_MOD_Y_TILED_CCS:
1911                 if (color_plane == 1)
1912                         return 128;
1913                 /* fall through */
1914         case I915_FORMAT_MOD_Y_TILED:
1915                 if (IS_GEN(dev_priv, 2) || HAS_128_BYTE_Y_TILING(dev_priv))
1916                         return 128;
1917                 else
1918                         return 512;
1919         case I915_FORMAT_MOD_Yf_TILED_CCS:
1920                 if (color_plane == 1)
1921                         return 128;
1922                 /* fall through */
1923         case I915_FORMAT_MOD_Yf_TILED:
1924                 switch (cpp) {
1925                 case 1:
1926                         return 64;
1927                 case 2:
1928                 case 4:
1929                         return 128;
1930                 case 8:
1931                 case 16:
1932                         return 256;
1933                 default:
1934                         MISSING_CASE(cpp);
1935                         return cpp;
1936                 }
1937                 break;
1938         default:
1939                 MISSING_CASE(fb->modifier);
1940                 return cpp;
1941         }
1942 }
1943
1944 static unsigned int
1945 intel_tile_height(const struct drm_framebuffer *fb, int color_plane)
1946 {
1947         return intel_tile_size(to_i915(fb->dev)) /
1948                 intel_tile_width_bytes(fb, color_plane);
1949 }
1950
1951 /* Return the tile dimensions in pixel units */
1952 static void intel_tile_dims(const struct drm_framebuffer *fb, int color_plane,
1953                             unsigned int *tile_width,
1954                             unsigned int *tile_height)
1955 {
1956         unsigned int tile_width_bytes = intel_tile_width_bytes(fb, color_plane);
1957         unsigned int cpp = fb->format->cpp[color_plane];
1958
1959         *tile_width = tile_width_bytes / cpp;
1960         *tile_height = intel_tile_size(to_i915(fb->dev)) / tile_width_bytes;
1961 }
1962
1963 unsigned int
1964 intel_fb_align_height(const struct drm_framebuffer *fb,
1965                       int color_plane, unsigned int height)
1966 {
1967         unsigned int tile_height = intel_tile_height(fb, color_plane);
1968
1969         return ALIGN(height, tile_height);
1970 }
1971
1972 unsigned int intel_rotation_info_size(const struct intel_rotation_info *rot_info)
1973 {
1974         unsigned int size = 0;
1975         int i;
1976
1977         for (i = 0 ; i < ARRAY_SIZE(rot_info->plane); i++)
1978                 size += rot_info->plane[i].width * rot_info->plane[i].height;
1979
1980         return size;
1981 }
1982
1983 unsigned int intel_remapped_info_size(const struct intel_remapped_info *rem_info)
1984 {
1985         unsigned int size = 0;
1986         int i;
1987
1988         for (i = 0 ; i < ARRAY_SIZE(rem_info->plane); i++)
1989                 size += rem_info->plane[i].width * rem_info->plane[i].height;
1990
1991         return size;
1992 }
1993
1994 static void
1995 intel_fill_fb_ggtt_view(struct i915_ggtt_view *view,
1996                         const struct drm_framebuffer *fb,
1997                         unsigned int rotation)
1998 {
1999         view->type = I915_GGTT_VIEW_NORMAL;
2000         if (drm_rotation_90_or_270(rotation)) {
2001                 view->type = I915_GGTT_VIEW_ROTATED;
2002                 view->rotated = to_intel_framebuffer(fb)->rot_info;
2003         }
2004 }
2005
2006 static unsigned int intel_cursor_alignment(const struct drm_i915_private *dev_priv)
2007 {
2008         if (IS_I830(dev_priv))
2009                 return 16 * 1024;
2010         else if (IS_I85X(dev_priv))
2011                 return 256;
2012         else if (IS_I845G(dev_priv) || IS_I865G(dev_priv))
2013                 return 32;
2014         else
2015                 return 4 * 1024;
2016 }
2017
2018 static unsigned int intel_linear_alignment(const struct drm_i915_private *dev_priv)
2019 {
2020         if (INTEL_GEN(dev_priv) >= 9)
2021                 return 256 * 1024;
2022         else if (IS_I965G(dev_priv) || IS_I965GM(dev_priv) ||
2023                  IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
2024                 return 128 * 1024;
2025         else if (INTEL_GEN(dev_priv) >= 4)
2026                 return 4 * 1024;
2027         else
2028                 return 0;
2029 }
2030
2031 static unsigned int intel_surf_alignment(const struct drm_framebuffer *fb,
2032                                          int color_plane)
2033 {
2034         struct drm_i915_private *dev_priv = to_i915(fb->dev);
2035
2036         /* AUX_DIST needs only 4K alignment */
2037         if (color_plane == 1)
2038                 return 4096;
2039
2040         switch (fb->modifier) {
2041         case DRM_FORMAT_MOD_LINEAR:
2042                 return intel_linear_alignment(dev_priv);
2043         case I915_FORMAT_MOD_X_TILED:
2044                 if (INTEL_GEN(dev_priv) >= 9)
2045                         return 256 * 1024;
2046                 return 0;
2047         case I915_FORMAT_MOD_Y_TILED_CCS:
2048         case I915_FORMAT_MOD_Yf_TILED_CCS:
2049         case I915_FORMAT_MOD_Y_TILED:
2050         case I915_FORMAT_MOD_Yf_TILED:
2051                 return 1 * 1024 * 1024;
2052         default:
2053                 MISSING_CASE(fb->modifier);
2054                 return 0;
2055         }
2056 }
2057
2058 static bool intel_plane_uses_fence(const struct intel_plane_state *plane_state)
2059 {
2060         struct intel_plane *plane = to_intel_plane(plane_state->base.plane);
2061         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
2062
2063         return INTEL_GEN(dev_priv) < 4 ||
2064                 (plane->has_fbc &&
2065                  plane_state->view.type == I915_GGTT_VIEW_NORMAL);
2066 }
2067
2068 struct i915_vma *
2069 intel_pin_and_fence_fb_obj(struct drm_framebuffer *fb,
2070                            const struct i915_ggtt_view *view,
2071                            bool uses_fence,
2072                            unsigned long *out_flags)
2073 {
2074         struct drm_device *dev = fb->dev;
2075         struct drm_i915_private *dev_priv = to_i915(dev);
2076         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
2077         intel_wakeref_t wakeref;
2078         struct i915_vma *vma;
2079         unsigned int pinctl;
2080         u32 alignment;
2081
2082         WARN_ON(!mutex_is_locked(&dev->struct_mutex));
2083         if (WARN_ON(!i915_gem_object_is_framebuffer(obj)))
2084                 return ERR_PTR(-EINVAL);
2085
2086         alignment = intel_surf_alignment(fb, 0);
2087
2088         /* Note that the w/a also requires 64 PTE of padding following the
2089          * bo. We currently fill all unused PTE with the shadow page and so
2090          * we should always have valid PTE following the scanout preventing
2091          * the VT-d warning.
2092          */
2093         if (intel_scanout_needs_vtd_wa(dev_priv) && alignment < 256 * 1024)
2094                 alignment = 256 * 1024;
2095
2096         /*
2097          * Global gtt pte registers are special registers which actually forward
2098          * writes to a chunk of system memory. Which means that there is no risk
2099          * that the register values disappear as soon as we call
2100          * intel_runtime_pm_put(), so it is correct to wrap only the
2101          * pin/unpin/fence and not more.
2102          */
2103         wakeref = intel_runtime_pm_get(&dev_priv->runtime_pm);
2104         i915_gem_object_lock(obj);
2105
2106         atomic_inc(&dev_priv->gpu_error.pending_fb_pin);
2107
2108         pinctl = 0;
2109
2110         /* Valleyview is definitely limited to scanning out the first
2111          * 512MiB. Lets presume this behaviour was inherited from the
2112          * g4x display engine and that all earlier gen are similarly
2113          * limited. Testing suggests that it is a little more
2114          * complicated than this. For example, Cherryview appears quite
2115          * happy to scanout from anywhere within its global aperture.
2116          */
2117         if (HAS_GMCH(dev_priv))
2118                 pinctl |= PIN_MAPPABLE;
2119
2120         vma = i915_gem_object_pin_to_display_plane(obj,
2121                                                    alignment, view, pinctl);
2122         if (IS_ERR(vma))
2123                 goto err;
2124
2125         if (uses_fence && i915_vma_is_map_and_fenceable(vma)) {
2126                 int ret;
2127
2128                 /* Install a fence for tiled scan-out. Pre-i965 always needs a
2129                  * fence, whereas 965+ only requires a fence if using
2130                  * framebuffer compression.  For simplicity, we always, when
2131                  * possible, install a fence as the cost is not that onerous.
2132                  *
2133                  * If we fail to fence the tiled scanout, then either the
2134                  * modeset will reject the change (which is highly unlikely as
2135                  * the affected systems, all but one, do not have unmappable
2136                  * space) or we will not be able to enable full powersaving
2137                  * techniques (also likely not to apply due to various limits
2138                  * FBC and the like impose on the size of the buffer, which
2139                  * presumably we violated anyway with this unmappable buffer).
2140                  * Anyway, it is presumably better to stumble onwards with
2141                  * something and try to run the system in a "less than optimal"
2142                  * mode that matches the user configuration.
2143                  */
2144                 ret = i915_vma_pin_fence(vma);
2145                 if (ret != 0 && INTEL_GEN(dev_priv) < 4) {
2146                         i915_gem_object_unpin_from_display_plane(vma);
2147                         vma = ERR_PTR(ret);
2148                         goto err;
2149                 }
2150
2151                 if (ret == 0 && vma->fence)
2152                         *out_flags |= PLANE_HAS_FENCE;
2153         }
2154
2155         i915_vma_get(vma);
2156 err:
2157         atomic_dec(&dev_priv->gpu_error.pending_fb_pin);
2158
2159         i915_gem_object_unlock(obj);
2160         intel_runtime_pm_put(&dev_priv->runtime_pm, wakeref);
2161         return vma;
2162 }
2163
2164 void intel_unpin_fb_vma(struct i915_vma *vma, unsigned long flags)
2165 {
2166         lockdep_assert_held(&vma->vm->i915->drm.struct_mutex);
2167
2168         i915_gem_object_lock(vma->obj);
2169         if (flags & PLANE_HAS_FENCE)
2170                 i915_vma_unpin_fence(vma);
2171         i915_gem_object_unpin_from_display_plane(vma);
2172         i915_gem_object_unlock(vma->obj);
2173
2174         i915_vma_put(vma);
2175 }
2176
2177 static int intel_fb_pitch(const struct drm_framebuffer *fb, int color_plane,
2178                           unsigned int rotation)
2179 {
2180         if (drm_rotation_90_or_270(rotation))
2181                 return to_intel_framebuffer(fb)->rotated[color_plane].pitch;
2182         else
2183                 return fb->pitches[color_plane];
2184 }
2185
2186 /*
2187  * Convert the x/y offsets into a linear offset.
2188  * Only valid with 0/180 degree rotation, which is fine since linear
2189  * offset is only used with linear buffers on pre-hsw and tiled buffers
2190  * with gen2/3, and 90/270 degree rotations isn't supported on any of them.
2191  */
2192 u32 intel_fb_xy_to_linear(int x, int y,
2193                           const struct intel_plane_state *state,
2194                           int color_plane)
2195 {
2196         const struct drm_framebuffer *fb = state->base.fb;
2197         unsigned int cpp = fb->format->cpp[color_plane];
2198         unsigned int pitch = state->color_plane[color_plane].stride;
2199
2200         return y * pitch + x * cpp;
2201 }
2202
2203 /*
2204  * Add the x/y offsets derived from fb->offsets[] to the user
2205  * specified plane src x/y offsets. The resulting x/y offsets
2206  * specify the start of scanout from the beginning of the gtt mapping.
2207  */
2208 void intel_add_fb_offsets(int *x, int *y,
2209                           const struct intel_plane_state *state,
2210                           int color_plane)
2211
2212 {
2213         *x += state->color_plane[color_plane].x;
2214         *y += state->color_plane[color_plane].y;
2215 }
2216
2217 static u32 intel_adjust_tile_offset(int *x, int *y,
2218                                     unsigned int tile_width,
2219                                     unsigned int tile_height,
2220                                     unsigned int tile_size,
2221                                     unsigned int pitch_tiles,
2222                                     u32 old_offset,
2223                                     u32 new_offset)
2224 {
2225         unsigned int pitch_pixels = pitch_tiles * tile_width;
2226         unsigned int tiles;
2227
2228         WARN_ON(old_offset & (tile_size - 1));
2229         WARN_ON(new_offset & (tile_size - 1));
2230         WARN_ON(new_offset > old_offset);
2231
2232         tiles = (old_offset - new_offset) / tile_size;
2233
2234         *y += tiles / pitch_tiles * tile_height;
2235         *x += tiles % pitch_tiles * tile_width;
2236
2237         /* minimize x in case it got needlessly big */
2238         *y += *x / pitch_pixels * tile_height;
2239         *x %= pitch_pixels;
2240
2241         return new_offset;
2242 }
2243
2244 static bool is_surface_linear(u64 modifier, int color_plane)
2245 {
2246         return modifier == DRM_FORMAT_MOD_LINEAR;
2247 }
2248
2249 static u32 intel_adjust_aligned_offset(int *x, int *y,
2250                                        const struct drm_framebuffer *fb,
2251                                        int color_plane,
2252                                        unsigned int rotation,
2253                                        unsigned int pitch,
2254                                        u32 old_offset, u32 new_offset)
2255 {
2256         struct drm_i915_private *dev_priv = to_i915(fb->dev);
2257         unsigned int cpp = fb->format->cpp[color_plane];
2258
2259         WARN_ON(new_offset > old_offset);
2260
2261         if (!is_surface_linear(fb->modifier, color_plane)) {
2262                 unsigned int tile_size, tile_width, tile_height;
2263                 unsigned int pitch_tiles;
2264
2265                 tile_size = intel_tile_size(dev_priv);
2266                 intel_tile_dims(fb, color_plane, &tile_width, &tile_height);
2267
2268                 if (drm_rotation_90_or_270(rotation)) {
2269                         pitch_tiles = pitch / tile_height;
2270                         swap(tile_width, tile_height);
2271                 } else {
2272                         pitch_tiles = pitch / (tile_width * cpp);
2273                 }
2274
2275                 intel_adjust_tile_offset(x, y, tile_width, tile_height,
2276                                          tile_size, pitch_tiles,
2277                                          old_offset, new_offset);
2278         } else {
2279                 old_offset += *y * pitch + *x * cpp;
2280
2281                 *y = (old_offset - new_offset) / pitch;
2282                 *x = ((old_offset - new_offset) - *y * pitch) / cpp;
2283         }
2284
2285         return new_offset;
2286 }
2287
2288 /*
2289  * Adjust the tile offset by moving the difference into
2290  * the x/y offsets.
2291  */
2292 static u32 intel_plane_adjust_aligned_offset(int *x, int *y,
2293                                              const struct intel_plane_state *state,
2294                                              int color_plane,
2295                                              u32 old_offset, u32 new_offset)
2296 {
2297         return intel_adjust_aligned_offset(x, y, state->base.fb, color_plane,
2298                                            state->base.rotation,
2299                                            state->color_plane[color_plane].stride,
2300                                            old_offset, new_offset);
2301 }
2302
2303 /*
2304  * Computes the aligned offset to the base tile and adjusts
2305  * x, y. bytes per pixel is assumed to be a power-of-two.
2306  *
2307  * In the 90/270 rotated case, x and y are assumed
2308  * to be already rotated to match the rotated GTT view, and
2309  * pitch is the tile_height aligned framebuffer height.
2310  *
2311  * This function is used when computing the derived information
2312  * under intel_framebuffer, so using any of that information
2313  * here is not allowed. Anything under drm_framebuffer can be
2314  * used. This is why the user has to pass in the pitch since it
2315  * is specified in the rotated orientation.
2316  */
2317 static u32 intel_compute_aligned_offset(struct drm_i915_private *dev_priv,
2318                                         int *x, int *y,
2319                                         const struct drm_framebuffer *fb,
2320                                         int color_plane,
2321                                         unsigned int pitch,
2322                                         unsigned int rotation,
2323                                         u32 alignment)
2324 {
2325         unsigned int cpp = fb->format->cpp[color_plane];
2326         u32 offset, offset_aligned;
2327
2328         if (alignment)
2329                 alignment--;
2330
2331         if (!is_surface_linear(fb->modifier, color_plane)) {
2332                 unsigned int tile_size, tile_width, tile_height;
2333                 unsigned int tile_rows, tiles, pitch_tiles;
2334
2335                 tile_size = intel_tile_size(dev_priv);
2336                 intel_tile_dims(fb, color_plane, &tile_width, &tile_height);
2337
2338                 if (drm_rotation_90_or_270(rotation)) {
2339                         pitch_tiles = pitch / tile_height;
2340                         swap(tile_width, tile_height);
2341                 } else {
2342                         pitch_tiles = pitch / (tile_width * cpp);
2343                 }
2344
2345                 tile_rows = *y / tile_height;
2346                 *y %= tile_height;
2347
2348                 tiles = *x / tile_width;
2349                 *x %= tile_width;
2350
2351                 offset = (tile_rows * pitch_tiles + tiles) * tile_size;
2352                 offset_aligned = offset & ~alignment;
2353
2354                 intel_adjust_tile_offset(x, y, tile_width, tile_height,
2355                                          tile_size, pitch_tiles,
2356                                          offset, offset_aligned);
2357         } else {
2358                 offset = *y * pitch + *x * cpp;
2359                 offset_aligned = offset & ~alignment;
2360
2361                 *y = (offset & alignment) / pitch;
2362                 *x = ((offset & alignment) - *y * pitch) / cpp;
2363         }
2364
2365         return offset_aligned;
2366 }
2367
2368 static u32 intel_plane_compute_aligned_offset(int *x, int *y,
2369                                               const struct intel_plane_state *state,
2370                                               int color_plane)
2371 {
2372         struct intel_plane *intel_plane = to_intel_plane(state->base.plane);
2373         struct drm_i915_private *dev_priv = to_i915(intel_plane->base.dev);
2374         const struct drm_framebuffer *fb = state->base.fb;
2375         unsigned int rotation = state->base.rotation;
2376         int pitch = state->color_plane[color_plane].stride;
2377         u32 alignment;
2378
2379         if (intel_plane->id == PLANE_CURSOR)
2380                 alignment = intel_cursor_alignment(dev_priv);
2381         else
2382                 alignment = intel_surf_alignment(fb, color_plane);
2383
2384         return intel_compute_aligned_offset(dev_priv, x, y, fb, color_plane,
2385                                             pitch, rotation, alignment);
2386 }
2387
2388 /* Convert the fb->offset[] into x/y offsets */
2389 static int intel_fb_offset_to_xy(int *x, int *y,
2390                                  const struct drm_framebuffer *fb,
2391                                  int color_plane)
2392 {
2393         struct drm_i915_private *dev_priv = to_i915(fb->dev);
2394         unsigned int height;
2395
2396         if (fb->modifier != DRM_FORMAT_MOD_LINEAR &&
2397             fb->offsets[color_plane] % intel_tile_size(dev_priv)) {
2398                 DRM_DEBUG_KMS("Misaligned offset 0x%08x for color plane %d\n",
2399                               fb->offsets[color_plane], color_plane);
2400                 return -EINVAL;
2401         }
2402
2403         height = drm_framebuffer_plane_height(fb->height, fb, color_plane);
2404         height = ALIGN(height, intel_tile_height(fb, color_plane));
2405
2406         /* Catch potential overflows early */
2407         if (add_overflows_t(u32, mul_u32_u32(height, fb->pitches[color_plane]),
2408                             fb->offsets[color_plane])) {
2409                 DRM_DEBUG_KMS("Bad offset 0x%08x or pitch %d for color plane %d\n",
2410                               fb->offsets[color_plane], fb->pitches[color_plane],
2411                               color_plane);
2412                 return -ERANGE;
2413         }
2414
2415         *x = 0;
2416         *y = 0;
2417
2418         intel_adjust_aligned_offset(x, y,
2419                                     fb, color_plane, DRM_MODE_ROTATE_0,
2420                                     fb->pitches[color_plane],
2421                                     fb->offsets[color_plane], 0);
2422
2423         return 0;
2424 }
2425
2426 static unsigned int intel_fb_modifier_to_tiling(u64 fb_modifier)
2427 {
2428         switch (fb_modifier) {
2429         case I915_FORMAT_MOD_X_TILED:
2430                 return I915_TILING_X;
2431         case I915_FORMAT_MOD_Y_TILED:
2432         case I915_FORMAT_MOD_Y_TILED_CCS:
2433                 return I915_TILING_Y;
2434         default:
2435                 return I915_TILING_NONE;
2436         }
2437 }
2438
2439 /*
2440  * From the Sky Lake PRM:
2441  * "The Color Control Surface (CCS) contains the compression status of
2442  *  the cache-line pairs. The compression state of the cache-line pair
2443  *  is specified by 2 bits in the CCS. Each CCS cache-line represents
2444  *  an area on the main surface of 16 x16 sets of 128 byte Y-tiled
2445  *  cache-line-pairs. CCS is always Y tiled."
2446  *
2447  * Since cache line pairs refers to horizontally adjacent cache lines,
2448  * each cache line in the CCS corresponds to an area of 32x16 cache
2449  * lines on the main surface. Since each pixel is 4 bytes, this gives
2450  * us a ratio of one byte in the CCS for each 8x16 pixels in the
2451  * main surface.
2452  */
2453 static const struct drm_format_info ccs_formats[] = {
2454         { .format = DRM_FORMAT_XRGB8888, .depth = 24, .num_planes = 2,
2455           .cpp = { 4, 1, }, .hsub = 8, .vsub = 16, },
2456         { .format = DRM_FORMAT_XBGR8888, .depth = 24, .num_planes = 2,
2457           .cpp = { 4, 1, }, .hsub = 8, .vsub = 16, },
2458         { .format = DRM_FORMAT_ARGB8888, .depth = 32, .num_planes = 2,
2459           .cpp = { 4, 1, }, .hsub = 8, .vsub = 16, .has_alpha = true, },
2460         { .format = DRM_FORMAT_ABGR8888, .depth = 32, .num_planes = 2,
2461           .cpp = { 4, 1, }, .hsub = 8, .vsub = 16, .has_alpha = true, },
2462 };
2463
2464 static const struct drm_format_info *
2465 lookup_format_info(const struct drm_format_info formats[],
2466                    int num_formats, u32 format)
2467 {
2468         int i;
2469
2470         for (i = 0; i < num_formats; i++) {
2471                 if (formats[i].format == format)
2472                         return &formats[i];
2473         }
2474
2475         return NULL;
2476 }
2477
2478 static const struct drm_format_info *
2479 intel_get_format_info(const struct drm_mode_fb_cmd2 *cmd)
2480 {
2481         switch (cmd->modifier[0]) {
2482         case I915_FORMAT_MOD_Y_TILED_CCS:
2483         case I915_FORMAT_MOD_Yf_TILED_CCS:
2484                 return lookup_format_info(ccs_formats,
2485                                           ARRAY_SIZE(ccs_formats),
2486                                           cmd->pixel_format);
2487         default:
2488                 return NULL;
2489         }
2490 }
2491
2492 bool is_ccs_modifier(u64 modifier)
2493 {
2494         return modifier == I915_FORMAT_MOD_Y_TILED_CCS ||
2495                modifier == I915_FORMAT_MOD_Yf_TILED_CCS;
2496 }
2497
2498 u32 intel_plane_fb_max_stride(struct drm_i915_private *dev_priv,
2499                               u32 pixel_format, u64 modifier)
2500 {
2501         struct intel_crtc *crtc;
2502         struct intel_plane *plane;
2503
2504         /*
2505          * We assume the primary plane for pipe A has
2506          * the highest stride limits of them all.
2507          */
2508         crtc = intel_get_crtc_for_pipe(dev_priv, PIPE_A);
2509         plane = to_intel_plane(crtc->base.primary);
2510
2511         return plane->max_stride(plane, pixel_format, modifier,
2512                                  DRM_MODE_ROTATE_0);
2513 }
2514
2515 static
2516 u32 intel_fb_max_stride(struct drm_i915_private *dev_priv,
2517                         u32 pixel_format, u64 modifier)
2518 {
2519         /*
2520          * Arbitrary limit for gen4+ chosen to match the
2521          * render engine max stride.
2522          *
2523          * The new CCS hash mode makes remapping impossible
2524          */
2525         if (!is_ccs_modifier(modifier)) {
2526                 if (INTEL_GEN(dev_priv) >= 7)
2527                         return 256*1024;
2528                 else if (INTEL_GEN(dev_priv) >= 4)
2529                         return 128*1024;
2530         }
2531
2532         return intel_plane_fb_max_stride(dev_priv, pixel_format, modifier);
2533 }
2534
2535 static u32
2536 intel_fb_stride_alignment(const struct drm_framebuffer *fb, int color_plane)
2537 {
2538         struct drm_i915_private *dev_priv = to_i915(fb->dev);
2539
2540         if (fb->modifier == DRM_FORMAT_MOD_LINEAR) {
2541                 u32 max_stride = intel_plane_fb_max_stride(dev_priv,
2542                                                            fb->format->format,
2543                                                            fb->modifier);
2544
2545                 /*
2546                  * To make remapping with linear generally feasible
2547                  * we need the stride to be page aligned.
2548                  */
2549                 if (fb->pitches[color_plane] > max_stride)
2550                         return intel_tile_size(dev_priv);
2551                 else
2552                         return 64;
2553         } else {
2554                 return intel_tile_width_bytes(fb, color_plane);
2555         }
2556 }
2557
2558 bool intel_plane_can_remap(const struct intel_plane_state *plane_state)
2559 {
2560         struct intel_plane *plane = to_intel_plane(plane_state->base.plane);
2561         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
2562         const struct drm_framebuffer *fb = plane_state->base.fb;
2563         int i;
2564
2565         /* We don't want to deal with remapping with cursors */
2566         if (plane->id == PLANE_CURSOR)
2567                 return false;
2568
2569         /*
2570          * The display engine limits already match/exceed the
2571          * render engine limits, so not much point in remapping.
2572          * Would also need to deal with the fence POT alignment
2573          * and gen2 2KiB GTT tile size.
2574          */
2575         if (INTEL_GEN(dev_priv) < 4)
2576                 return false;
2577
2578         /*
2579          * The new CCS hash mode isn't compatible with remapping as
2580          * the virtual address of the pages affects the compressed data.
2581          */
2582         if (is_ccs_modifier(fb->modifier))
2583                 return false;
2584
2585         /* Linear needs a page aligned stride for remapping */
2586         if (fb->modifier == DRM_FORMAT_MOD_LINEAR) {
2587                 unsigned int alignment = intel_tile_size(dev_priv) - 1;
2588
2589                 for (i = 0; i < fb->format->num_planes; i++) {
2590                         if (fb->pitches[i] & alignment)
2591                                 return false;
2592                 }
2593         }
2594
2595         return true;
2596 }
2597
2598 static bool intel_plane_needs_remap(const struct intel_plane_state *plane_state)
2599 {
2600         struct intel_plane *plane = to_intel_plane(plane_state->base.plane);
2601         const struct drm_framebuffer *fb = plane_state->base.fb;
2602         unsigned int rotation = plane_state->base.rotation;
2603         u32 stride, max_stride;
2604
2605         /*
2606          * No remapping for invisible planes since we don't have
2607          * an actual source viewport to remap.
2608          */
2609         if (!plane_state->base.visible)
2610                 return false;
2611
2612         if (!intel_plane_can_remap(plane_state))
2613                 return false;
2614
2615         /*
2616          * FIXME: aux plane limits on gen9+ are
2617          * unclear in Bspec, for now no checking.
2618          */
2619         stride = intel_fb_pitch(fb, 0, rotation);
2620         max_stride = plane->max_stride(plane, fb->format->format,
2621                                        fb->modifier, rotation);
2622
2623         return stride > max_stride;
2624 }
2625
2626 static int
2627 intel_fill_fb_info(struct drm_i915_private *dev_priv,
2628                    struct drm_framebuffer *fb)
2629 {
2630         struct intel_framebuffer *intel_fb = to_intel_framebuffer(fb);
2631         struct intel_rotation_info *rot_info = &intel_fb->rot_info;
2632         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
2633         u32 gtt_offset_rotated = 0;
2634         unsigned int max_size = 0;
2635         int i, num_planes = fb->format->num_planes;
2636         unsigned int tile_size = intel_tile_size(dev_priv);
2637
2638         for (i = 0; i < num_planes; i++) {
2639                 unsigned int width, height;
2640                 unsigned int cpp, size;
2641                 u32 offset;
2642                 int x, y;
2643                 int ret;
2644
2645                 cpp = fb->format->cpp[i];
2646                 width = drm_framebuffer_plane_width(fb->width, fb, i);
2647                 height = drm_framebuffer_plane_height(fb->height, fb, i);
2648
2649                 ret = intel_fb_offset_to_xy(&x, &y, fb, i);
2650                 if (ret) {
2651                         DRM_DEBUG_KMS("bad fb plane %d offset: 0x%x\n",
2652                                       i, fb->offsets[i]);
2653                         return ret;
2654                 }
2655
2656                 if (is_ccs_modifier(fb->modifier) && i == 1) {
2657                         int hsub = fb->format->hsub;
2658                         int vsub = fb->format->vsub;
2659                         int tile_width, tile_height;
2660                         int main_x, main_y;
2661                         int ccs_x, ccs_y;
2662
2663                         intel_tile_dims(fb, i, &tile_width, &tile_height);
2664                         tile_width *= hsub;
2665                         tile_height *= vsub;
2666
2667                         ccs_x = (x * hsub) % tile_width;
2668                         ccs_y = (y * vsub) % tile_height;
2669                         main_x = intel_fb->normal[0].x % tile_width;
2670                         main_y = intel_fb->normal[0].y % tile_height;
2671
2672                         /*
2673                          * CCS doesn't have its own x/y offset register, so the intra CCS tile
2674                          * x/y offsets must match between CCS and the main surface.
2675                          */
2676                         if (main_x != ccs_x || main_y != ccs_y) {
2677                                 DRM_DEBUG_KMS("Bad CCS x/y (main %d,%d ccs %d,%d) full (main %d,%d ccs %d,%d)\n",
2678                                               main_x, main_y,
2679                                               ccs_x, ccs_y,
2680                                               intel_fb->normal[0].x,
2681                                               intel_fb->normal[0].y,
2682                                               x, y);
2683                                 return -EINVAL;
2684                         }
2685                 }
2686
2687                 /*
2688                  * The fence (if used) is aligned to the start of the object
2689                  * so having the framebuffer wrap around across the edge of the
2690                  * fenced region doesn't really work. We have no API to configure
2691                  * the fence start offset within the object (nor could we probably
2692                  * on gen2/3). So it's just easier if we just require that the
2693                  * fb layout agrees with the fence layout. We already check that the
2694                  * fb stride matches the fence stride elsewhere.
2695                  */
2696                 if (i == 0 && i915_gem_object_is_tiled(obj) &&
2697                     (x + width) * cpp > fb->pitches[i]) {
2698                         DRM_DEBUG_KMS("bad fb plane %d offset: 0x%x\n",
2699                                       i, fb->offsets[i]);
2700                         return -EINVAL;
2701                 }
2702
2703                 /*
2704                  * First pixel of the framebuffer from
2705                  * the start of the normal gtt mapping.
2706                  */
2707                 intel_fb->normal[i].x = x;
2708                 intel_fb->normal[i].y = y;
2709
2710                 offset = intel_compute_aligned_offset(dev_priv, &x, &y, fb, i,
2711                                                       fb->pitches[i],
2712                                                       DRM_MODE_ROTATE_0,
2713                                                       tile_size);
2714                 offset /= tile_size;
2715
2716                 if (!is_surface_linear(fb->modifier, i)) {
2717                         unsigned int tile_width, tile_height;
2718                         unsigned int pitch_tiles;
2719                         struct drm_rect r;
2720
2721                         intel_tile_dims(fb, i, &tile_width, &tile_height);
2722
2723                         rot_info->plane[i].offset = offset;
2724                         rot_info->plane[i].stride = DIV_ROUND_UP(fb->pitches[i], tile_width * cpp);
2725                         rot_info->plane[i].width = DIV_ROUND_UP(x + width, tile_width);
2726                         rot_info->plane[i].height = DIV_ROUND_UP(y + height, tile_height);
2727
2728                         intel_fb->rotated[i].pitch =
2729                                 rot_info->plane[i].height * tile_height;
2730
2731                         /* how many tiles does this plane need */
2732                         size = rot_info->plane[i].stride * rot_info->plane[i].height;
2733                         /*
2734                          * If the plane isn't horizontally tile aligned,
2735                          * we need one more tile.
2736                          */
2737                         if (x != 0)
2738                                 size++;
2739
2740                         /* rotate the x/y offsets to match the GTT view */
2741                         r.x1 = x;
2742                         r.y1 = y;
2743                         r.x2 = x + width;
2744                         r.y2 = y + height;
2745                         drm_rect_rotate(&r,
2746                                         rot_info->plane[i].width * tile_width,
2747                                         rot_info->plane[i].height * tile_height,
2748                                         DRM_MODE_ROTATE_270);
2749                         x = r.x1;
2750                         y = r.y1;
2751
2752                         /* rotate the tile dimensions to match the GTT view */
2753                         pitch_tiles = intel_fb->rotated[i].pitch / tile_height;
2754                         swap(tile_width, tile_height);
2755
2756                         /*
2757                          * We only keep the x/y offsets, so push all of the
2758                          * gtt offset into the x/y offsets.
2759                          */
2760                         intel_adjust_tile_offset(&x, &y,
2761                                                  tile_width, tile_height,
2762                                                  tile_size, pitch_tiles,
2763                                                  gtt_offset_rotated * tile_size, 0);
2764
2765                         gtt_offset_rotated += rot_info->plane[i].width * rot_info->plane[i].height;
2766
2767                         /*
2768                          * First pixel of the framebuffer from
2769                          * the start of the rotated gtt mapping.
2770                          */
2771                         intel_fb->rotated[i].x = x;
2772                         intel_fb->rotated[i].y = y;
2773                 } else {
2774                         size = DIV_ROUND_UP((y + height) * fb->pitches[i] +
2775                                             x * cpp, tile_size);
2776                 }
2777
2778                 /* how many tiles in total needed in the bo */
2779                 max_size = max(max_size, offset + size);
2780         }
2781
2782         if (mul_u32_u32(max_size, tile_size) > obj->base.size) {
2783                 DRM_DEBUG_KMS("fb too big for bo (need %llu bytes, have %zu bytes)\n",
2784                               mul_u32_u32(max_size, tile_size), obj->base.size);
2785                 return -EINVAL;
2786         }
2787
2788         return 0;
2789 }
2790
2791 static void
2792 intel_plane_remap_gtt(struct intel_plane_state *plane_state)
2793 {
2794         struct drm_i915_private *dev_priv =
2795                 to_i915(plane_state->base.plane->dev);
2796         struct drm_framebuffer *fb = plane_state->base.fb;
2797         struct intel_framebuffer *intel_fb = to_intel_framebuffer(fb);
2798         struct intel_rotation_info *info = &plane_state->view.rotated;
2799         unsigned int rotation = plane_state->base.rotation;
2800         int i, num_planes = fb->format->num_planes;
2801         unsigned int tile_size = intel_tile_size(dev_priv);
2802         unsigned int src_x, src_y;
2803         unsigned int src_w, src_h;
2804         u32 gtt_offset = 0;
2805
2806         memset(&plane_state->view, 0, sizeof(plane_state->view));
2807         plane_state->view.type = drm_rotation_90_or_270(rotation) ?
2808                 I915_GGTT_VIEW_ROTATED : I915_GGTT_VIEW_REMAPPED;
2809
2810         src_x = plane_state->base.src.x1 >> 16;
2811         src_y = plane_state->base.src.y1 >> 16;
2812         src_w = drm_rect_width(&plane_state->base.src) >> 16;
2813         src_h = drm_rect_height(&plane_state->base.src) >> 16;
2814
2815         WARN_ON(is_ccs_modifier(fb->modifier));
2816
2817         /* Make src coordinates relative to the viewport */
2818         drm_rect_translate(&plane_state->base.src,
2819                            -(src_x << 16), -(src_y << 16));
2820
2821         /* Rotate src coordinates to match rotated GTT view */
2822         if (drm_rotation_90_or_270(rotation))
2823                 drm_rect_rotate(&plane_state->base.src,
2824                                 src_w << 16, src_h << 16,
2825                                 DRM_MODE_ROTATE_270);
2826
2827         for (i = 0; i < num_planes; i++) {
2828                 unsigned int hsub = i ? fb->format->hsub : 1;
2829                 unsigned int vsub = i ? fb->format->vsub : 1;
2830                 unsigned int cpp = fb->format->cpp[i];
2831                 unsigned int tile_width, tile_height;
2832                 unsigned int width, height;
2833                 unsigned int pitch_tiles;
2834                 unsigned int x, y;
2835                 u32 offset;
2836
2837                 intel_tile_dims(fb, i, &tile_width, &tile_height);
2838
2839                 x = src_x / hsub;
2840                 y = src_y / vsub;
2841                 width = src_w / hsub;
2842                 height = src_h / vsub;
2843
2844                 /*
2845                  * First pixel of the src viewport from the
2846                  * start of the normal gtt mapping.
2847                  */
2848                 x += intel_fb->normal[i].x;
2849                 y += intel_fb->normal[i].y;
2850
2851                 offset = intel_compute_aligned_offset(dev_priv, &x, &y,
2852                                                       fb, i, fb->pitches[i],
2853                                                       DRM_MODE_ROTATE_0, tile_size);
2854                 offset /= tile_size;
2855
2856                 info->plane[i].offset = offset;
2857                 info->plane[i].stride = DIV_ROUND_UP(fb->pitches[i],
2858                                                      tile_width * cpp);
2859                 info->plane[i].width = DIV_ROUND_UP(x + width, tile_width);
2860                 info->plane[i].height = DIV_ROUND_UP(y + height, tile_height);
2861
2862                 if (drm_rotation_90_or_270(rotation)) {
2863                         struct drm_rect r;
2864
2865                         /* rotate the x/y offsets to match the GTT view */
2866                         r.x1 = x;
2867                         r.y1 = y;
2868                         r.x2 = x + width;
2869                         r.y2 = y + height;
2870                         drm_rect_rotate(&r,
2871                                         info->plane[i].width * tile_width,
2872                                         info->plane[i].height * tile_height,
2873                                         DRM_MODE_ROTATE_270);
2874                         x = r.x1;
2875                         y = r.y1;
2876
2877                         pitch_tiles = info->plane[i].height;
2878                         plane_state->color_plane[i].stride = pitch_tiles * tile_height;
2879
2880                         /* rotate the tile dimensions to match the GTT view */
2881                         swap(tile_width, tile_height);
2882                 } else {
2883                         pitch_tiles = info->plane[i].width;
2884                         plane_state->color_plane[i].stride = pitch_tiles * tile_width * cpp;
2885                 }
2886
2887                 /*
2888                  * We only keep the x/y offsets, so push all of the
2889                  * gtt offset into the x/y offsets.
2890                  */
2891                 intel_adjust_tile_offset(&x, &y,
2892                                          tile_width, tile_height,
2893                                          tile_size, pitch_tiles,
2894                                          gtt_offset * tile_size, 0);
2895
2896                 gtt_offset += info->plane[i].width * info->plane[i].height;
2897
2898                 plane_state->color_plane[i].offset = 0;
2899                 plane_state->color_plane[i].x = x;
2900                 plane_state->color_plane[i].y = y;
2901         }
2902 }
2903
2904 static int
2905 intel_plane_compute_gtt(struct intel_plane_state *plane_state)
2906 {
2907         const struct intel_framebuffer *fb =
2908                 to_intel_framebuffer(plane_state->base.fb);
2909         unsigned int rotation = plane_state->base.rotation;
2910         int i, num_planes;
2911
2912         if (!fb)
2913                 return 0;
2914
2915         num_planes = fb->base.format->num_planes;
2916
2917         if (intel_plane_needs_remap(plane_state)) {
2918                 intel_plane_remap_gtt(plane_state);
2919
2920                 /*
2921                  * Sometimes even remapping can't overcome
2922                  * the stride limitations :( Can happen with
2923                  * big plane sizes and suitably misaligned
2924                  * offsets.
2925                  */
2926                 return intel_plane_check_stride(plane_state);
2927         }
2928
2929         intel_fill_fb_ggtt_view(&plane_state->view, &fb->base, rotation);
2930
2931         for (i = 0; i < num_planes; i++) {
2932                 plane_state->color_plane[i].stride = intel_fb_pitch(&fb->base, i, rotation);
2933                 plane_state->color_plane[i].offset = 0;
2934
2935                 if (drm_rotation_90_or_270(rotation)) {
2936                         plane_state->color_plane[i].x = fb->rotated[i].x;
2937                         plane_state->color_plane[i].y = fb->rotated[i].y;
2938                 } else {
2939                         plane_state->color_plane[i].x = fb->normal[i].x;
2940                         plane_state->color_plane[i].y = fb->normal[i].y;
2941                 }
2942         }
2943
2944         /* Rotate src coordinates to match rotated GTT view */
2945         if (drm_rotation_90_or_270(rotation))
2946                 drm_rect_rotate(&plane_state->base.src,
2947                                 fb->base.width << 16, fb->base.height << 16,
2948                                 DRM_MODE_ROTATE_270);
2949
2950         return intel_plane_check_stride(plane_state);
2951 }
2952
2953 static int i9xx_format_to_fourcc(int format)
2954 {
2955         switch (format) {
2956         case DISPPLANE_8BPP:
2957                 return DRM_FORMAT_C8;
2958         case DISPPLANE_BGRX555:
2959                 return DRM_FORMAT_XRGB1555;
2960         case DISPPLANE_BGRX565:
2961                 return DRM_FORMAT_RGB565;
2962         default:
2963         case DISPPLANE_BGRX888:
2964                 return DRM_FORMAT_XRGB8888;
2965         case DISPPLANE_RGBX888:
2966                 return DRM_FORMAT_XBGR8888;
2967         case DISPPLANE_BGRX101010:
2968                 return DRM_FORMAT_XRGB2101010;
2969         case DISPPLANE_RGBX101010:
2970                 return DRM_FORMAT_XBGR2101010;
2971         }
2972 }
2973
2974 int skl_format_to_fourcc(int format, bool rgb_order, bool alpha)
2975 {
2976         switch (format) {
2977         case PLANE_CTL_FORMAT_RGB_565:
2978                 return DRM_FORMAT_RGB565;
2979         case PLANE_CTL_FORMAT_NV12:
2980                 return DRM_FORMAT_NV12;
2981         case PLANE_CTL_FORMAT_P010:
2982                 return DRM_FORMAT_P010;
2983         case PLANE_CTL_FORMAT_P012:
2984                 return DRM_FORMAT_P012;
2985         case PLANE_CTL_FORMAT_P016:
2986                 return DRM_FORMAT_P016;
2987         case PLANE_CTL_FORMAT_Y210:
2988                 return DRM_FORMAT_Y210;
2989         case PLANE_CTL_FORMAT_Y212:
2990                 return DRM_FORMAT_Y212;
2991         case PLANE_CTL_FORMAT_Y216:
2992                 return DRM_FORMAT_Y216;
2993         case PLANE_CTL_FORMAT_Y410:
2994                 return DRM_FORMAT_XVYU2101010;
2995         case PLANE_CTL_FORMAT_Y412:
2996                 return DRM_FORMAT_XVYU12_16161616;
2997         case PLANE_CTL_FORMAT_Y416:
2998                 return DRM_FORMAT_XVYU16161616;
2999         default:
3000         case PLANE_CTL_FORMAT_XRGB_8888:
3001                 if (rgb_order) {
3002                         if (alpha)
3003                                 return DRM_FORMAT_ABGR8888;
3004                         else
3005                                 return DRM_FORMAT_XBGR8888;
3006                 } else {
3007                         if (alpha)
3008                                 return DRM_FORMAT_ARGB8888;
3009                         else
3010                                 return DRM_FORMAT_XRGB8888;
3011                 }
3012         case PLANE_CTL_FORMAT_XRGB_2101010:
3013                 if (rgb_order)
3014                         return DRM_FORMAT_XBGR2101010;
3015                 else
3016                         return DRM_FORMAT_XRGB2101010;
3017         case PLANE_CTL_FORMAT_XRGB_16161616F:
3018                 if (rgb_order) {
3019                         if (alpha)
3020                                 return DRM_FORMAT_ABGR16161616F;
3021                         else
3022                                 return DRM_FORMAT_XBGR16161616F;
3023                 } else {
3024                         if (alpha)
3025                                 return DRM_FORMAT_ARGB16161616F;
3026                         else
3027                                 return DRM_FORMAT_XRGB16161616F;
3028                 }
3029         }
3030 }
3031
3032 static bool
3033 intel_alloc_initial_plane_obj(struct intel_crtc *crtc,
3034                               struct intel_initial_plane_config *plane_config)
3035 {
3036         struct drm_device *dev = crtc->base.dev;
3037         struct drm_i915_private *dev_priv = to_i915(dev);
3038         struct drm_mode_fb_cmd2 mode_cmd = { 0 };
3039         struct drm_framebuffer *fb = &plane_config->fb->base;
3040         u32 base_aligned = round_down(plane_config->base, PAGE_SIZE);
3041         u32 size_aligned = round_up(plane_config->base + plane_config->size,
3042                                     PAGE_SIZE);
3043         struct drm_i915_gem_object *obj;
3044         bool ret = false;
3045
3046         size_aligned -= base_aligned;
3047
3048         if (plane_config->size == 0)
3049                 return false;
3050
3051         /* If the FB is too big, just don't use it since fbdev is not very
3052          * important and we should probably use that space with FBC or other
3053          * features. */
3054         if (size_aligned * 2 > dev_priv->stolen_usable_size)
3055                 return false;
3056
3057         switch (fb->modifier) {
3058         case DRM_FORMAT_MOD_LINEAR:
3059         case I915_FORMAT_MOD_X_TILED:
3060         case I915_FORMAT_MOD_Y_TILED:
3061                 break;
3062         default:
3063                 DRM_DEBUG_DRIVER("Unsupported modifier for initial FB: 0x%llx\n",
3064                                  fb->modifier);
3065                 return false;
3066         }
3067
3068         mutex_lock(&dev->struct_mutex);
3069         obj = i915_gem_object_create_stolen_for_preallocated(dev_priv,
3070                                                              base_aligned,
3071                                                              base_aligned,
3072                                                              size_aligned);
3073         mutex_unlock(&dev->struct_mutex);
3074         if (!obj)
3075                 return false;
3076
3077         switch (plane_config->tiling) {
3078         case I915_TILING_NONE:
3079                 break;
3080         case I915_TILING_X:
3081         case I915_TILING_Y:
3082                 obj->tiling_and_stride = fb->pitches[0] | plane_config->tiling;
3083                 break;
3084         default:
3085                 MISSING_CASE(plane_config->tiling);
3086                 goto out;
3087         }
3088
3089         mode_cmd.pixel_format = fb->format->format;
3090         mode_cmd.width = fb->width;
3091         mode_cmd.height = fb->height;
3092         mode_cmd.pitches[0] = fb->pitches[0];
3093         mode_cmd.modifier[0] = fb->modifier;
3094         mode_cmd.flags = DRM_MODE_FB_MODIFIERS;
3095
3096         if (intel_framebuffer_init(to_intel_framebuffer(fb), obj, &mode_cmd)) {
3097                 DRM_DEBUG_KMS("intel fb init failed\n");
3098                 goto out;
3099         }
3100
3101
3102         DRM_DEBUG_KMS("initial plane fb obj %p\n", obj);
3103         ret = true;
3104 out:
3105         i915_gem_object_put(obj);
3106         return ret;
3107 }
3108
3109 static void
3110 intel_set_plane_visible(struct intel_crtc_state *crtc_state,
3111                         struct intel_plane_state *plane_state,
3112                         bool visible)
3113 {
3114         struct intel_plane *plane = to_intel_plane(plane_state->base.plane);
3115
3116         plane_state->base.visible = visible;
3117
3118         if (visible)
3119                 crtc_state->base.plane_mask |= drm_plane_mask(&plane->base);
3120         else
3121                 crtc_state->base.plane_mask &= ~drm_plane_mask(&plane->base);
3122 }
3123
3124 static void fixup_active_planes(struct intel_crtc_state *crtc_state)
3125 {
3126         struct drm_i915_private *dev_priv = to_i915(crtc_state->base.crtc->dev);
3127         struct drm_plane *plane;
3128
3129         /*
3130          * Active_planes aliases if multiple "primary" or cursor planes
3131          * have been used on the same (or wrong) pipe. plane_mask uses
3132          * unique ids, hence we can use that to reconstruct active_planes.
3133          */
3134         crtc_state->active_planes = 0;
3135
3136         drm_for_each_plane_mask(plane, &dev_priv->drm,
3137                                 crtc_state->base.plane_mask)
3138                 crtc_state->active_planes |= BIT(to_intel_plane(plane)->id);
3139 }
3140
3141 static void intel_plane_disable_noatomic(struct intel_crtc *crtc,
3142                                          struct intel_plane *plane)
3143 {
3144         struct intel_crtc_state *crtc_state =
3145                 to_intel_crtc_state(crtc->base.state);
3146         struct intel_plane_state *plane_state =
3147                 to_intel_plane_state(plane->base.state);
3148
3149         DRM_DEBUG_KMS("Disabling [PLANE:%d:%s] on [CRTC:%d:%s]\n",
3150                       plane->base.base.id, plane->base.name,
3151                       crtc->base.base.id, crtc->base.name);
3152
3153         intel_set_plane_visible(crtc_state, plane_state, false);
3154         fixup_active_planes(crtc_state);
3155         crtc_state->data_rate[plane->id] = 0;
3156
3157         if (plane->id == PLANE_PRIMARY)
3158                 intel_pre_disable_primary_noatomic(&crtc->base);
3159
3160         intel_disable_plane(plane, crtc_state);
3161 }
3162
3163 static struct intel_frontbuffer *
3164 to_intel_frontbuffer(struct drm_framebuffer *fb)
3165 {
3166         return fb ? to_intel_framebuffer(fb)->frontbuffer : NULL;
3167 }
3168
3169 static void
3170 intel_find_initial_plane_obj(struct intel_crtc *intel_crtc,
3171                              struct intel_initial_plane_config *plane_config)
3172 {
3173         struct drm_device *dev = intel_crtc->base.dev;
3174         struct drm_i915_private *dev_priv = to_i915(dev);
3175         struct drm_crtc *c;
3176         struct drm_plane *primary = intel_crtc->base.primary;
3177         struct drm_plane_state *plane_state = primary->state;
3178         struct intel_plane *intel_plane = to_intel_plane(primary);
3179         struct intel_plane_state *intel_state =
3180                 to_intel_plane_state(plane_state);
3181         struct drm_framebuffer *fb;
3182
3183         if (!plane_config->fb)
3184                 return;
3185
3186         if (intel_alloc_initial_plane_obj(intel_crtc, plane_config)) {
3187                 fb = &plane_config->fb->base;
3188                 goto valid_fb;
3189         }
3190
3191         kfree(plane_config->fb);
3192
3193         /*
3194          * Failed to alloc the obj, check to see if we should share
3195          * an fb with another CRTC instead
3196          */
3197         for_each_crtc(dev, c) {
3198                 struct intel_plane_state *state;
3199
3200                 if (c == &intel_crtc->base)
3201                         continue;
3202
3203                 if (!to_intel_crtc(c)->active)
3204                         continue;
3205
3206                 state = to_intel_plane_state(c->primary->state);
3207                 if (!state->vma)
3208                         continue;
3209
3210                 if (intel_plane_ggtt_offset(state) == plane_config->base) {
3211                         fb = state->base.fb;
3212                         drm_framebuffer_get(fb);
3213                         goto valid_fb;
3214                 }
3215         }
3216
3217         /*
3218          * We've failed to reconstruct the BIOS FB.  Current display state
3219          * indicates that the primary plane is visible, but has a NULL FB,
3220          * which will lead to problems later if we don't fix it up.  The
3221          * simplest solution is to just disable the primary plane now and
3222          * pretend the BIOS never had it enabled.
3223          */
3224         intel_plane_disable_noatomic(intel_crtc, intel_plane);
3225
3226         return;
3227
3228 valid_fb:
3229         intel_state->base.rotation = plane_config->rotation;
3230         intel_fill_fb_ggtt_view(&intel_state->view, fb,
3231                                 intel_state->base.rotation);
3232         intel_state->color_plane[0].stride =
3233                 intel_fb_pitch(fb, 0, intel_state->base.rotation);
3234
3235         mutex_lock(&dev->struct_mutex);
3236         intel_state->vma =
3237                 intel_pin_and_fence_fb_obj(fb,
3238                                            &intel_state->view,
3239                                            intel_plane_uses_fence(intel_state),
3240                                            &intel_state->flags);
3241         mutex_unlock(&dev->struct_mutex);
3242         if (IS_ERR(intel_state->vma)) {
3243                 DRM_ERROR("failed to pin boot fb on pipe %d: %li\n",
3244                           intel_crtc->pipe, PTR_ERR(intel_state->vma));
3245
3246                 intel_state->vma = NULL;
3247                 drm_framebuffer_put(fb);
3248                 return;
3249         }
3250
3251         intel_frontbuffer_flush(to_intel_frontbuffer(fb), ORIGIN_DIRTYFB);
3252
3253         plane_state->src_x = 0;
3254         plane_state->src_y = 0;
3255         plane_state->src_w = fb->width << 16;
3256         plane_state->src_h = fb->height << 16;
3257
3258         plane_state->crtc_x = 0;
3259         plane_state->crtc_y = 0;
3260         plane_state->crtc_w = fb->width;
3261         plane_state->crtc_h = fb->height;
3262
3263         intel_state->base.src = drm_plane_state_src(plane_state);
3264         intel_state->base.dst = drm_plane_state_dest(plane_state);
3265
3266         if (plane_config->tiling)
3267                 dev_priv->preserve_bios_swizzle = true;
3268
3269         plane_state->fb = fb;
3270         plane_state->crtc = &intel_crtc->base;
3271
3272         atomic_or(to_intel_plane(primary)->frontbuffer_bit,
3273                   &to_intel_frontbuffer(fb)->bits);
3274 }
3275
3276 static int skl_max_plane_width(const struct drm_framebuffer *fb,
3277                                int color_plane,
3278                                unsigned int rotation)
3279 {
3280         int cpp = fb->format->cpp[color_plane];
3281
3282         switch (fb->modifier) {
3283         case DRM_FORMAT_MOD_LINEAR:
3284         case I915_FORMAT_MOD_X_TILED:
3285                 return 4096;
3286         case I915_FORMAT_MOD_Y_TILED_CCS:
3287         case I915_FORMAT_MOD_Yf_TILED_CCS:
3288                 /* FIXME AUX plane? */
3289         case I915_FORMAT_MOD_Y_TILED:
3290         case I915_FORMAT_MOD_Yf_TILED:
3291                 if (cpp == 8)
3292                         return 2048;
3293                 else
3294                         return 4096;
3295         default:
3296                 MISSING_CASE(fb->modifier);
3297                 return 2048;
3298         }
3299 }
3300
3301 static int glk_max_plane_width(const struct drm_framebuffer *fb,
3302                                int color_plane,
3303                                unsigned int rotation)
3304 {
3305         int cpp = fb->format->cpp[color_plane];
3306
3307         switch (fb->modifier) {
3308         case DRM_FORMAT_MOD_LINEAR:
3309         case I915_FORMAT_MOD_X_TILED:
3310                 if (cpp == 8)
3311                         return 4096;
3312                 else
3313                         return 5120;
3314         case I915_FORMAT_MOD_Y_TILED_CCS:
3315         case I915_FORMAT_MOD_Yf_TILED_CCS:
3316                 /* FIXME AUX plane? */
3317         case I915_FORMAT_MOD_Y_TILED:
3318         case I915_FORMAT_MOD_Yf_TILED:
3319                 if (cpp == 8)
3320                         return 2048;
3321                 else
3322                         return 5120;
3323         default:
3324                 MISSING_CASE(fb->modifier);
3325                 return 2048;
3326         }
3327 }
3328
3329 static int icl_max_plane_width(const struct drm_framebuffer *fb,
3330                                int color_plane,
3331                                unsigned int rotation)
3332 {
3333         return 5120;
3334 }
3335
3336 static bool skl_check_main_ccs_coordinates(struct intel_plane_state *plane_state,
3337                                            int main_x, int main_y, u32 main_offset)
3338 {
3339         const struct drm_framebuffer *fb = plane_state->base.fb;
3340         int hsub = fb->format->hsub;
3341         int vsub = fb->format->vsub;
3342         int aux_x = plane_state->color_plane[1].x;
3343         int aux_y = plane_state->color_plane[1].y;
3344         u32 aux_offset = plane_state->color_plane[1].offset;
3345         u32 alignment = intel_surf_alignment(fb, 1);
3346
3347         while (aux_offset >= main_offset && aux_y <= main_y) {
3348                 int x, y;
3349
3350                 if (aux_x == main_x && aux_y == main_y)
3351                         break;
3352
3353                 if (aux_offset == 0)
3354                         break;
3355
3356                 x = aux_x / hsub;
3357                 y = aux_y / vsub;
3358                 aux_offset = intel_plane_adjust_aligned_offset(&x, &y, plane_state, 1,
3359                                                                aux_offset, aux_offset - alignment);
3360                 aux_x = x * hsub + aux_x % hsub;
3361                 aux_y = y * vsub + aux_y % vsub;
3362         }
3363
3364         if (aux_x != main_x || aux_y != main_y)
3365                 return false;
3366
3367         plane_state->color_plane[1].offset = aux_offset;
3368         plane_state->color_plane[1].x = aux_x;
3369         plane_state->color_plane[1].y = aux_y;
3370
3371         return true;
3372 }
3373
3374 static int skl_check_main_surface(struct intel_plane_state *plane_state)
3375 {
3376         struct drm_i915_private *dev_priv = to_i915(plane_state->base.plane->dev);
3377         const struct drm_framebuffer *fb = plane_state->base.fb;
3378         unsigned int rotation = plane_state->base.rotation;
3379         int x = plane_state->base.src.x1 >> 16;
3380         int y = plane_state->base.src.y1 >> 16;
3381         int w = drm_rect_width(&plane_state->base.src) >> 16;
3382         int h = drm_rect_height(&plane_state->base.src) >> 16;
3383         int max_width;
3384         int max_height = 4096;
3385         u32 alignment, offset, aux_offset = plane_state->color_plane[1].offset;
3386
3387         if (INTEL_GEN(dev_priv) >= 11)
3388                 max_width = icl_max_plane_width(fb, 0, rotation);
3389         else if (INTEL_GEN(dev_priv) >= 10 || IS_GEMINILAKE(dev_priv))
3390                 max_width = glk_max_plane_width(fb, 0, rotation);
3391         else
3392                 max_width = skl_max_plane_width(fb, 0, rotation);
3393
3394         if (w > max_width || h > max_height) {
3395                 DRM_DEBUG_KMS("requested Y/RGB source size %dx%d too big (limit %dx%d)\n",
3396                               w, h, max_width, max_height);
3397                 return -EINVAL;
3398         }
3399
3400         intel_add_fb_offsets(&x, &y, plane_state, 0);
3401         offset = intel_plane_compute_aligned_offset(&x, &y, plane_state, 0);
3402         alignment = intel_surf_alignment(fb, 0);
3403
3404         /*
3405          * AUX surface offset is specified as the distance from the
3406          * main surface offset, and it must be non-negative. Make
3407          * sure that is what we will get.
3408          */
3409         if (offset > aux_offset)
3410                 offset = intel_plane_adjust_aligned_offset(&x, &y, plane_state, 0,
3411                                                            offset, aux_offset & ~(alignment - 1));
3412
3413         /*
3414          * When using an X-tiled surface, the plane blows up
3415          * if the x offset + width exceed the stride.
3416          *
3417          * TODO: linear and Y-tiled seem fine, Yf untested,
3418          */
3419         if (fb->modifier == I915_FORMAT_MOD_X_TILED) {
3420                 int cpp = fb->format->cpp[0];
3421
3422                 while ((x + w) * cpp > plane_state->color_plane[0].stride) {
3423                         if (offset == 0) {
3424                                 DRM_DEBUG_KMS("Unable to find suitable display surface offset due to X-tiling\n");
3425                                 return -EINVAL;
3426                         }
3427
3428                         offset = intel_plane_adjust_aligned_offset(&x, &y, plane_state, 0,
3429                                                                    offset, offset - alignment);
3430                 }
3431         }
3432
3433         /*
3434          * CCS AUX surface doesn't have its own x/y offsets, we must make sure
3435          * they match with the main surface x/y offsets.
3436          */
3437         if (is_ccs_modifier(fb->modifier)) {
3438                 while (!skl_check_main_ccs_coordinates(plane_state, x, y, offset)) {
3439                         if (offset == 0)
3440                                 break;
3441
3442                         offset = intel_plane_adjust_aligned_offset(&x, &y, plane_state, 0,
3443                                                                    offset, offset - alignment);
3444                 }
3445
3446                 if (x != plane_state->color_plane[1].x || y != plane_state->color_plane[1].y) {
3447                         DRM_DEBUG_KMS("Unable to find suitable display surface offset due to CCS\n");
3448                         return -EINVAL;
3449                 }
3450         }
3451
3452         plane_state->color_plane[0].offset = offset;
3453         plane_state->color_plane[0].x = x;
3454         plane_state->color_plane[0].y = y;
3455
3456         /*
3457          * Put the final coordinates back so that the src
3458          * coordinate checks will see the right values.
3459          */
3460         drm_rect_translate(&plane_state->base.src,
3461                            (x << 16) - plane_state->base.src.x1,
3462                            (y << 16) - plane_state->base.src.y1);
3463
3464         return 0;
3465 }
3466
3467 static int skl_check_nv12_aux_surface(struct intel_plane_state *plane_state)
3468 {
3469         const struct drm_framebuffer *fb = plane_state->base.fb;
3470         unsigned int rotation = plane_state->base.rotation;
3471         int max_width = skl_max_plane_width(fb, 1, rotation);
3472         int max_height = 4096;
3473         int x = plane_state->base.src.x1 >> 17;
3474         int y = plane_state->base.src.y1 >> 17;
3475         int w = drm_rect_width(&plane_state->base.src) >> 17;
3476         int h = drm_rect_height(&plane_state->base.src) >> 17;
3477         u32 offset;
3478
3479         intel_add_fb_offsets(&x, &y, plane_state, 1);
3480         offset = intel_plane_compute_aligned_offset(&x, &y, plane_state, 1);
3481
3482         /* FIXME not quite sure how/if these apply to the chroma plane */
3483         if (w > max_width || h > max_height) {
3484                 DRM_DEBUG_KMS("CbCr source size %dx%d too big (limit %dx%d)\n",
3485                               w, h, max_width, max_height);
3486                 return -EINVAL;
3487         }
3488
3489         plane_state->color_plane[1].offset = offset;
3490         plane_state->color_plane[1].x = x;
3491         plane_state->color_plane[1].y = y;
3492
3493         return 0;
3494 }
3495
3496 static int skl_check_ccs_aux_surface(struct intel_plane_state *plane_state)
3497 {
3498         const struct drm_framebuffer *fb = plane_state->base.fb;
3499         int src_x = plane_state->base.src.x1 >> 16;
3500         int src_y = plane_state->base.src.y1 >> 16;
3501         int hsub = fb->format->hsub;
3502         int vsub = fb->format->vsub;
3503         int x = src_x / hsub;
3504         int y = src_y / vsub;
3505         u32 offset;
3506
3507         intel_add_fb_offsets(&x, &y, plane_state, 1);
3508         offset = intel_plane_compute_aligned_offset(&x, &y, plane_state, 1);
3509
3510         plane_state->color_plane[1].offset = offset;
3511         plane_state->color_plane[1].x = x * hsub + src_x % hsub;
3512         plane_state->color_plane[1].y = y * vsub + src_y % vsub;
3513
3514         return 0;
3515 }
3516
3517 int skl_check_plane_surface(struct intel_plane_state *plane_state)
3518 {
3519         const struct drm_framebuffer *fb = plane_state->base.fb;
3520         int ret;
3521
3522         ret = intel_plane_compute_gtt(plane_state);
3523         if (ret)
3524                 return ret;
3525
3526         if (!plane_state->base.visible)
3527                 return 0;
3528
3529         /*
3530          * Handle the AUX surface first since
3531          * the main surface setup depends on it.
3532          */
3533         if (is_planar_yuv_format(fb->format->format)) {
3534                 ret = skl_check_nv12_aux_surface(plane_state);
3535                 if (ret)
3536                         return ret;
3537         } else if (is_ccs_modifier(fb->modifier)) {
3538                 ret = skl_check_ccs_aux_surface(plane_state);
3539                 if (ret)
3540                         return ret;
3541         } else {
3542                 plane_state->color_plane[1].offset = ~0xfff;
3543                 plane_state->color_plane[1].x = 0;
3544                 plane_state->color_plane[1].y = 0;
3545         }
3546
3547         ret = skl_check_main_surface(plane_state);
3548         if (ret)
3549                 return ret;
3550
3551         return 0;
3552 }
3553
3554 unsigned int
3555 i9xx_plane_max_stride(struct intel_plane *plane,
3556                       u32 pixel_format, u64 modifier,
3557                       unsigned int rotation)
3558 {
3559         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
3560
3561         if (!HAS_GMCH(dev_priv)) {
3562                 return 32*1024;
3563         } else if (INTEL_GEN(dev_priv) >= 4) {
3564                 if (modifier == I915_FORMAT_MOD_X_TILED)
3565                         return 16*1024;
3566                 else
3567                         return 32*1024;
3568         } else if (INTEL_GEN(dev_priv) >= 3) {
3569                 if (modifier == I915_FORMAT_MOD_X_TILED)
3570                         return 8*1024;
3571                 else
3572                         return 16*1024;
3573         } else {
3574                 if (plane->i9xx_plane == PLANE_C)
3575                         return 4*1024;
3576                 else
3577                         return 8*1024;
3578         }
3579 }
3580
3581 static u32 i9xx_plane_ctl_crtc(const struct intel_crtc_state *crtc_state)
3582 {
3583         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
3584         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
3585         u32 dspcntr = 0;
3586
3587         if (crtc_state->gamma_enable)
3588                 dspcntr |= DISPPLANE_GAMMA_ENABLE;
3589
3590         if (crtc_state->csc_enable)
3591                 dspcntr |= DISPPLANE_PIPE_CSC_ENABLE;
3592
3593         if (INTEL_GEN(dev_priv) < 5)
3594                 dspcntr |= DISPPLANE_SEL_PIPE(crtc->pipe);
3595
3596         return dspcntr;
3597 }
3598
3599 static u32 i9xx_plane_ctl(const struct intel_crtc_state *crtc_state,
3600                           const struct intel_plane_state *plane_state)
3601 {
3602         struct drm_i915_private *dev_priv =
3603                 to_i915(plane_state->base.plane->dev);
3604         const struct drm_framebuffer *fb = plane_state->base.fb;
3605         unsigned int rotation = plane_state->base.rotation;
3606         u32 dspcntr;
3607
3608         dspcntr = DISPLAY_PLANE_ENABLE;
3609
3610         if (IS_G4X(dev_priv) || IS_GEN(dev_priv, 5) ||
3611             IS_GEN(dev_priv, 6) || IS_IVYBRIDGE(dev_priv))
3612                 dspcntr |= DISPPLANE_TRICKLE_FEED_DISABLE;
3613
3614         switch (fb->format->format) {
3615         case DRM_FORMAT_C8:
3616                 dspcntr |= DISPPLANE_8BPP;
3617                 break;
3618         case DRM_FORMAT_XRGB1555:
3619                 dspcntr |= DISPPLANE_BGRX555;
3620                 break;
3621         case DRM_FORMAT_RGB565:
3622                 dspcntr |= DISPPLANE_BGRX565;
3623                 break;
3624         case DRM_FORMAT_XRGB8888:
3625                 dspcntr |= DISPPLANE_BGRX888;
3626                 break;
3627         case DRM_FORMAT_XBGR8888:
3628                 dspcntr |= DISPPLANE_RGBX888;
3629                 break;
3630         case DRM_FORMAT_XRGB2101010:
3631                 dspcntr |= DISPPLANE_BGRX101010;
3632                 break;
3633         case DRM_FORMAT_XBGR2101010:
3634                 dspcntr |= DISPPLANE_RGBX101010;
3635                 break;
3636         default:
3637                 MISSING_CASE(fb->format->format);
3638                 return 0;
3639         }
3640
3641         if (INTEL_GEN(dev_priv) >= 4 &&
3642             fb->modifier == I915_FORMAT_MOD_X_TILED)
3643                 dspcntr |= DISPPLANE_TILED;
3644
3645         if (rotation & DRM_MODE_ROTATE_180)
3646                 dspcntr |= DISPPLANE_ROTATE_180;
3647
3648         if (rotation & DRM_MODE_REFLECT_X)
3649                 dspcntr |= DISPPLANE_MIRROR;
3650
3651         return dspcntr;
3652 }
3653
3654 int i9xx_check_plane_surface(struct intel_plane_state *plane_state)
3655 {
3656         struct drm_i915_private *dev_priv =
3657                 to_i915(plane_state->base.plane->dev);
3658         int src_x, src_y;
3659         u32 offset;
3660         int ret;
3661
3662         ret = intel_plane_compute_gtt(plane_state);
3663         if (ret)
3664                 return ret;
3665
3666         if (!plane_state->base.visible)
3667                 return 0;
3668
3669         src_x = plane_state->base.src.x1 >> 16;
3670         src_y = plane_state->base.src.y1 >> 16;
3671
3672         intel_add_fb_offsets(&src_x, &src_y, plane_state, 0);
3673
3674         if (INTEL_GEN(dev_priv) >= 4)
3675                 offset = intel_plane_compute_aligned_offset(&src_x, &src_y,
3676                                                             plane_state, 0);
3677         else
3678                 offset = 0;
3679
3680         /*
3681          * Put the final coordinates back so that the src
3682          * coordinate checks will see the right values.
3683          */
3684         drm_rect_translate(&plane_state->base.src,
3685                            (src_x << 16) - plane_state->base.src.x1,
3686                            (src_y << 16) - plane_state->base.src.y1);
3687
3688         /* HSW/BDW do this automagically in hardware */
3689         if (!IS_HASWELL(dev_priv) && !IS_BROADWELL(dev_priv)) {
3690                 unsigned int rotation = plane_state->base.rotation;
3691                 int src_w = drm_rect_width(&plane_state->base.src) >> 16;
3692                 int src_h = drm_rect_height(&plane_state->base.src) >> 16;
3693
3694                 if (rotation & DRM_MODE_ROTATE_180) {
3695                         src_x += src_w - 1;
3696                         src_y += src_h - 1;
3697                 } else if (rotation & DRM_MODE_REFLECT_X) {
3698                         src_x += src_w - 1;
3699                 }
3700         }
3701
3702         plane_state->color_plane[0].offset = offset;
3703         plane_state->color_plane[0].x = src_x;
3704         plane_state->color_plane[0].y = src_y;
3705
3706         return 0;
3707 }
3708
3709 static bool i9xx_plane_has_windowing(struct intel_plane *plane)
3710 {
3711         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
3712         enum i9xx_plane_id i9xx_plane = plane->i9xx_plane;
3713
3714         if (IS_CHERRYVIEW(dev_priv))
3715                 return i9xx_plane == PLANE_B;
3716         else if (INTEL_GEN(dev_priv) >= 5 || IS_G4X(dev_priv))
3717                 return false;
3718         else if (IS_GEN(dev_priv, 4))
3719                 return i9xx_plane == PLANE_C;
3720         else
3721                 return i9xx_plane == PLANE_B ||
3722                         i9xx_plane == PLANE_C;
3723 }
3724
3725 static int
3726 i9xx_plane_check(struct intel_crtc_state *crtc_state,
3727                  struct intel_plane_state *plane_state)
3728 {
3729         struct intel_plane *plane = to_intel_plane(plane_state->base.plane);
3730         int ret;
3731
3732         ret = chv_plane_check_rotation(plane_state);
3733         if (ret)
3734                 return ret;
3735
3736         ret = drm_atomic_helper_check_plane_state(&plane_state->base,
3737                                                   &crtc_state->base,
3738                                                   DRM_PLANE_HELPER_NO_SCALING,
3739                                                   DRM_PLANE_HELPER_NO_SCALING,
3740                                                   i9xx_plane_has_windowing(plane),
3741                                                   true);
3742         if (ret)
3743                 return ret;
3744
3745         ret = i9xx_check_plane_surface(plane_state);
3746         if (ret)
3747                 return ret;
3748
3749         if (!plane_state->base.visible)
3750                 return 0;
3751
3752         ret = intel_plane_check_src_coordinates(plane_state);
3753         if (ret)
3754                 return ret;
3755
3756         plane_state->ctl = i9xx_plane_ctl(crtc_state, plane_state);
3757
3758         return 0;
3759 }
3760
3761 static void i9xx_update_plane(struct intel_plane *plane,
3762                               const struct intel_crtc_state *crtc_state,
3763                               const struct intel_plane_state *plane_state)
3764 {
3765         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
3766         enum i9xx_plane_id i9xx_plane = plane->i9xx_plane;
3767         u32 linear_offset;
3768         int x = plane_state->color_plane[0].x;
3769         int y = plane_state->color_plane[0].y;
3770         int crtc_x = plane_state->base.dst.x1;
3771         int crtc_y = plane_state->base.dst.y1;
3772         int crtc_w = drm_rect_width(&plane_state->base.dst);
3773         int crtc_h = drm_rect_height(&plane_state->base.dst);
3774         unsigned long irqflags;
3775         u32 dspaddr_offset;
3776         u32 dspcntr;
3777
3778         dspcntr = plane_state->ctl | i9xx_plane_ctl_crtc(crtc_state);
3779
3780         linear_offset = intel_fb_xy_to_linear(x, y, plane_state, 0);
3781
3782         if (INTEL_GEN(dev_priv) >= 4)
3783                 dspaddr_offset = plane_state->color_plane[0].offset;
3784         else
3785                 dspaddr_offset = linear_offset;
3786
3787         spin_lock_irqsave(&dev_priv->uncore.lock, irqflags);
3788
3789         I915_WRITE_FW(DSPSTRIDE(i9xx_plane), plane_state->color_plane[0].stride);
3790
3791         if (INTEL_GEN(dev_priv) < 4) {
3792                 /*
3793                  * PLANE_A doesn't actually have a full window
3794                  * generator but let's assume we still need to
3795                  * program whatever is there.
3796                  */
3797                 I915_WRITE_FW(DSPPOS(i9xx_plane), (crtc_y << 16) | crtc_x);
3798                 I915_WRITE_FW(DSPSIZE(i9xx_plane),
3799                               ((crtc_h - 1) << 16) | (crtc_w - 1));
3800         } else if (IS_CHERRYVIEW(dev_priv) && i9xx_plane == PLANE_B) {
3801                 I915_WRITE_FW(PRIMPOS(i9xx_plane), (crtc_y << 16) | crtc_x);
3802                 I915_WRITE_FW(PRIMSIZE(i9xx_plane),
3803                               ((crtc_h - 1) << 16) | (crtc_w - 1));
3804                 I915_WRITE_FW(PRIMCNSTALPHA(i9xx_plane), 0);
3805         }
3806
3807         if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv)) {
3808                 I915_WRITE_FW(DSPOFFSET(i9xx_plane), (y << 16) | x);
3809         } else if (INTEL_GEN(dev_priv) >= 4) {
3810                 I915_WRITE_FW(DSPLINOFF(i9xx_plane), linear_offset);
3811                 I915_WRITE_FW(DSPTILEOFF(i9xx_plane), (y << 16) | x);
3812         }
3813
3814         /*
3815          * The control register self-arms if the plane was previously
3816          * disabled. Try to make the plane enable atomic by writing
3817          * the control register just before the surface register.
3818          */
3819         I915_WRITE_FW(DSPCNTR(i9xx_plane), dspcntr);
3820         if (INTEL_GEN(dev_priv) >= 4)
3821                 I915_WRITE_FW(DSPSURF(i9xx_plane),
3822                               intel_plane_ggtt_offset(plane_state) +
3823                               dspaddr_offset);
3824         else
3825                 I915_WRITE_FW(DSPADDR(i9xx_plane),
3826                               intel_plane_ggtt_offset(plane_state) +
3827                               dspaddr_offset);
3828
3829         spin_unlock_irqrestore(&dev_priv->uncore.lock, irqflags);
3830 }
3831
3832 static void i9xx_disable_plane(struct intel_plane *plane,
3833                                const struct intel_crtc_state *crtc_state)
3834 {
3835         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
3836         enum i9xx_plane_id i9xx_plane = plane->i9xx_plane;
3837         unsigned long irqflags;
3838         u32 dspcntr;
3839
3840         /*
3841          * DSPCNTR pipe gamma enable on g4x+ and pipe csc
3842          * enable on ilk+ affect the pipe bottom color as
3843          * well, so we must configure them even if the plane
3844          * is disabled.
3845          *
3846          * On pre-g4x there is no way to gamma correct the
3847          * pipe bottom color but we'll keep on doing this
3848          * anyway so that the crtc state readout works correctly.
3849          */
3850         dspcntr = i9xx_plane_ctl_crtc(crtc_state);
3851
3852         spin_lock_irqsave(&dev_priv->uncore.lock, irqflags);
3853
3854         I915_WRITE_FW(DSPCNTR(i9xx_plane), dspcntr);
3855         if (INTEL_GEN(dev_priv) >= 4)
3856                 I915_WRITE_FW(DSPSURF(i9xx_plane), 0);
3857         else
3858                 I915_WRITE_FW(DSPADDR(i9xx_plane), 0);
3859
3860         spin_unlock_irqrestore(&dev_priv->uncore.lock, irqflags);
3861 }
3862
3863 static bool i9xx_plane_get_hw_state(struct intel_plane *plane,
3864                                     enum pipe *pipe)
3865 {
3866         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
3867         enum intel_display_power_domain power_domain;
3868         enum i9xx_plane_id i9xx_plane = plane->i9xx_plane;
3869         intel_wakeref_t wakeref;
3870         bool ret;
3871         u32 val;
3872
3873         /*
3874          * Not 100% correct for planes that can move between pipes,
3875          * but that's only the case for gen2-4 which don't have any
3876          * display power wells.
3877          */
3878         power_domain = POWER_DOMAIN_PIPE(plane->pipe);
3879         wakeref = intel_display_power_get_if_enabled(dev_priv, power_domain);
3880         if (!wakeref)
3881                 return false;
3882
3883         val = I915_READ(DSPCNTR(i9xx_plane));
3884
3885         ret = val & DISPLAY_PLANE_ENABLE;
3886
3887         if (INTEL_GEN(dev_priv) >= 5)
3888                 *pipe = plane->pipe;
3889         else
3890                 *pipe = (val & DISPPLANE_SEL_PIPE_MASK) >>
3891                         DISPPLANE_SEL_PIPE_SHIFT;
3892
3893         intel_display_power_put(dev_priv, power_domain, wakeref);
3894
3895         return ret;
3896 }
3897
3898 static void skl_detach_scaler(struct intel_crtc *intel_crtc, int id)
3899 {
3900         struct drm_device *dev = intel_crtc->base.dev;
3901         struct drm_i915_private *dev_priv = to_i915(dev);
3902
3903         I915_WRITE(SKL_PS_CTRL(intel_crtc->pipe, id), 0);
3904         I915_WRITE(SKL_PS_WIN_POS(intel_crtc->pipe, id), 0);
3905         I915_WRITE(SKL_PS_WIN_SZ(intel_crtc->pipe, id), 0);
3906 }
3907
3908 /*
3909  * This function detaches (aka. unbinds) unused scalers in hardware
3910  */
3911 static void skl_detach_scalers(const struct intel_crtc_state *crtc_state)
3912 {
3913         struct intel_crtc *intel_crtc = to_intel_crtc(crtc_state->base.crtc);
3914         const struct intel_crtc_scaler_state *scaler_state =
3915                 &crtc_state->scaler_state;
3916         int i;
3917
3918         /* loop through and disable scalers that aren't in use */
3919         for (i = 0; i < intel_crtc->num_scalers; i++) {
3920                 if (!scaler_state->scalers[i].in_use)
3921                         skl_detach_scaler(intel_crtc, i);
3922         }
3923 }
3924
3925 static unsigned int skl_plane_stride_mult(const struct drm_framebuffer *fb,
3926                                           int color_plane, unsigned int rotation)
3927 {
3928         /*
3929          * The stride is either expressed as a multiple of 64 bytes chunks for
3930          * linear buffers or in number of tiles for tiled buffers.
3931          */
3932         if (fb->modifier == DRM_FORMAT_MOD_LINEAR)
3933                 return 64;
3934         else if (drm_rotation_90_or_270(rotation))
3935                 return intel_tile_height(fb, color_plane);
3936         else
3937                 return intel_tile_width_bytes(fb, color_plane);
3938 }
3939
3940 u32 skl_plane_stride(const struct intel_plane_state *plane_state,
3941                      int color_plane)
3942 {
3943         const struct drm_framebuffer *fb = plane_state->base.fb;
3944         unsigned int rotation = plane_state->base.rotation;
3945         u32 stride = plane_state->color_plane[color_plane].stride;
3946
3947         if (color_plane >= fb->format->num_planes)
3948                 return 0;
3949
3950         return stride / skl_plane_stride_mult(fb, color_plane, rotation);
3951 }
3952
3953 static u32 skl_plane_ctl_format(u32 pixel_format)
3954 {
3955         switch (pixel_format) {
3956         case DRM_FORMAT_C8:
3957                 return PLANE_CTL_FORMAT_INDEXED;
3958         case DRM_FORMAT_RGB565:
3959                 return PLANE_CTL_FORMAT_RGB_565;
3960         case DRM_FORMAT_XBGR8888:
3961         case DRM_FORMAT_ABGR8888:
3962                 return PLANE_CTL_FORMAT_XRGB_8888 | PLANE_CTL_ORDER_RGBX;
3963         case DRM_FORMAT_XRGB8888:
3964         case DRM_FORMAT_ARGB8888:
3965                 return PLANE_CTL_FORMAT_XRGB_8888;
3966         case DRM_FORMAT_XBGR2101010:
3967                 return PLANE_CTL_FORMAT_XRGB_2101010 | PLANE_CTL_ORDER_RGBX;
3968         case DRM_FORMAT_XRGB2101010:
3969                 return PLANE_CTL_FORMAT_XRGB_2101010;
3970         case DRM_FORMAT_XBGR16161616F:
3971         case DRM_FORMAT_ABGR16161616F:
3972                 return PLANE_CTL_FORMAT_XRGB_16161616F | PLANE_CTL_ORDER_RGBX;
3973         case DRM_FORMAT_XRGB16161616F:
3974         case DRM_FORMAT_ARGB16161616F:
3975                 return PLANE_CTL_FORMAT_XRGB_16161616F;
3976         case DRM_FORMAT_YUYV:
3977                 return PLANE_CTL_FORMAT_YUV422 | PLANE_CTL_YUV422_YUYV;
3978         case DRM_FORMAT_YVYU:
3979                 return PLANE_CTL_FORMAT_YUV422 | PLANE_CTL_YUV422_YVYU;
3980         case DRM_FORMAT_UYVY:
3981                 return PLANE_CTL_FORMAT_YUV422 | PLANE_CTL_YUV422_UYVY;
3982         case DRM_FORMAT_VYUY:
3983                 return PLANE_CTL_FORMAT_YUV422 | PLANE_CTL_YUV422_VYUY;
3984         case DRM_FORMAT_NV12:
3985                 return PLANE_CTL_FORMAT_NV12;
3986         case DRM_FORMAT_P010:
3987                 return PLANE_CTL_FORMAT_P010;
3988         case DRM_FORMAT_P012:
3989                 return PLANE_CTL_FORMAT_P012;
3990         case DRM_FORMAT_P016:
3991                 return PLANE_CTL_FORMAT_P016;
3992         case DRM_FORMAT_Y210:
3993                 return PLANE_CTL_FORMAT_Y210;
3994         case DRM_FORMAT_Y212:
3995                 return PLANE_CTL_FORMAT_Y212;
3996         case DRM_FORMAT_Y216:
3997                 return PLANE_CTL_FORMAT_Y216;
3998         case DRM_FORMAT_XVYU2101010:
3999                 return PLANE_CTL_FORMAT_Y410;
4000         case DRM_FORMAT_XVYU12_16161616:
4001                 return PLANE_CTL_FORMAT_Y412;
4002         case DRM_FORMAT_XVYU16161616:
4003                 return PLANE_CTL_FORMAT_Y416;
4004         default:
4005                 MISSING_CASE(pixel_format);
4006         }
4007
4008         return 0;
4009 }
4010
4011 static u32 skl_plane_ctl_alpha(const struct intel_plane_state *plane_state)
4012 {
4013         if (!plane_state->base.fb->format->has_alpha)
4014                 return PLANE_CTL_ALPHA_DISABLE;
4015
4016         switch (plane_state->base.pixel_blend_mode) {
4017         case DRM_MODE_BLEND_PIXEL_NONE:
4018                 return PLANE_CTL_ALPHA_DISABLE;
4019         case DRM_MODE_BLEND_PREMULTI:
4020                 return PLANE_CTL_ALPHA_SW_PREMULTIPLY;
4021         case DRM_MODE_BLEND_COVERAGE:
4022                 return PLANE_CTL_ALPHA_HW_PREMULTIPLY;
4023         default:
4024                 MISSING_CASE(plane_state->base.pixel_blend_mode);
4025                 return PLANE_CTL_ALPHA_DISABLE;
4026         }
4027 }
4028
4029 static u32 glk_plane_color_ctl_alpha(const struct intel_plane_state *plane_state)
4030 {
4031         if (!plane_state->base.fb->format->has_alpha)
4032                 return PLANE_COLOR_ALPHA_DISABLE;
4033
4034         switch (plane_state->base.pixel_blend_mode) {
4035         case DRM_MODE_BLEND_PIXEL_NONE:
4036                 return PLANE_COLOR_ALPHA_DISABLE;
4037         case DRM_MODE_BLEND_PREMULTI:
4038                 return PLANE_COLOR_ALPHA_SW_PREMULTIPLY;
4039         case DRM_MODE_BLEND_COVERAGE:
4040                 return PLANE_COLOR_ALPHA_HW_PREMULTIPLY;
4041         default:
4042                 MISSING_CASE(plane_state->base.pixel_blend_mode);
4043                 return PLANE_COLOR_ALPHA_DISABLE;
4044         }
4045 }
4046
4047 static u32 skl_plane_ctl_tiling(u64 fb_modifier)
4048 {
4049         switch (fb_modifier) {
4050         case DRM_FORMAT_MOD_LINEAR:
4051                 break;
4052         case I915_FORMAT_MOD_X_TILED:
4053                 return PLANE_CTL_TILED_X;
4054         case I915_FORMAT_MOD_Y_TILED:
4055                 return PLANE_CTL_TILED_Y;
4056         case I915_FORMAT_MOD_Y_TILED_CCS:
4057                 return PLANE_CTL_TILED_Y | PLANE_CTL_RENDER_DECOMPRESSION_ENABLE;
4058         case I915_FORMAT_MOD_Yf_TILED:
4059                 return PLANE_CTL_TILED_YF;
4060         case I915_FORMAT_MOD_Yf_TILED_CCS:
4061                 return PLANE_CTL_TILED_YF | PLANE_CTL_RENDER_DECOMPRESSION_ENABLE;
4062         default:
4063                 MISSING_CASE(fb_modifier);
4064         }
4065
4066         return 0;
4067 }
4068
4069 static u32 skl_plane_ctl_rotate(unsigned int rotate)
4070 {
4071         switch (rotate) {
4072         case DRM_MODE_ROTATE_0:
4073                 break;
4074         /*
4075          * DRM_MODE_ROTATE_ is counter clockwise to stay compatible with Xrandr
4076          * while i915 HW rotation is clockwise, thats why this swapping.
4077          */
4078         case DRM_MODE_ROTATE_90:
4079                 return PLANE_CTL_ROTATE_270;
4080         case DRM_MODE_ROTATE_180:
4081                 return PLANE_CTL_ROTATE_180;
4082         case DRM_MODE_ROTATE_270:
4083                 return PLANE_CTL_ROTATE_90;
4084         default:
4085                 MISSING_CASE(rotate);
4086         }
4087
4088         return 0;
4089 }
4090
4091 static u32 cnl_plane_ctl_flip(unsigned int reflect)
4092 {
4093         switch (reflect) {
4094         case 0:
4095                 break;
4096         case DRM_MODE_REFLECT_X:
4097                 return PLANE_CTL_FLIP_HORIZONTAL;
4098         case DRM_MODE_REFLECT_Y:
4099         default:
4100                 MISSING_CASE(reflect);
4101         }
4102
4103         return 0;
4104 }
4105
4106 u32 skl_plane_ctl_crtc(const struct intel_crtc_state *crtc_state)
4107 {
4108         struct drm_i915_private *dev_priv = to_i915(crtc_state->base.crtc->dev);
4109         u32 plane_ctl = 0;
4110
4111         if (INTEL_GEN(dev_priv) >= 10 || IS_GEMINILAKE(dev_priv))
4112                 return plane_ctl;
4113
4114         if (crtc_state->gamma_enable)
4115                 plane_ctl |= PLANE_CTL_PIPE_GAMMA_ENABLE;
4116
4117         if (crtc_state->csc_enable)
4118                 plane_ctl |= PLANE_CTL_PIPE_CSC_ENABLE;
4119
4120         return plane_ctl;
4121 }
4122
4123 u32 skl_plane_ctl(const struct intel_crtc_state *crtc_state,
4124                   const struct intel_plane_state *plane_state)
4125 {
4126         struct drm_i915_private *dev_priv =
4127                 to_i915(plane_state->base.plane->dev);
4128         const struct drm_framebuffer *fb = plane_state->base.fb;
4129         unsigned int rotation = plane_state->base.rotation;
4130         const struct drm_intel_sprite_colorkey *key = &plane_state->ckey;
4131         u32 plane_ctl;
4132
4133         plane_ctl = PLANE_CTL_ENABLE;
4134
4135         if (INTEL_GEN(dev_priv) < 10 && !IS_GEMINILAKE(dev_priv)) {
4136                 plane_ctl |= skl_plane_ctl_alpha(plane_state);
4137                 plane_ctl |= PLANE_CTL_PLANE_GAMMA_DISABLE;
4138
4139                 if (plane_state->base.color_encoding == DRM_COLOR_YCBCR_BT709)
4140                         plane_ctl |= PLANE_CTL_YUV_TO_RGB_CSC_FORMAT_BT709;
4141
4142                 if (plane_state->base.color_range == DRM_COLOR_YCBCR_FULL_RANGE)
4143                         plane_ctl |= PLANE_CTL_YUV_RANGE_CORRECTION_DISABLE;
4144         }
4145
4146         plane_ctl |= skl_plane_ctl_format(fb->format->format);
4147         plane_ctl |= skl_plane_ctl_tiling(fb->modifier);
4148         plane_ctl |= skl_plane_ctl_rotate(rotation & DRM_MODE_ROTATE_MASK);
4149
4150         if (INTEL_GEN(dev_priv) >= 10)
4151                 plane_ctl |= cnl_plane_ctl_flip(rotation &
4152                                                 DRM_MODE_REFLECT_MASK);
4153
4154         if (key->flags & I915_SET_COLORKEY_DESTINATION)
4155                 plane_ctl |= PLANE_CTL_KEY_ENABLE_DESTINATION;
4156         else if (key->flags & I915_SET_COLORKEY_SOURCE)
4157                 plane_ctl |= PLANE_CTL_KEY_ENABLE_SOURCE;
4158
4159         return plane_ctl;
4160 }
4161
4162 u32 glk_plane_color_ctl_crtc(const struct intel_crtc_state *crtc_state)
4163 {
4164         struct drm_i915_private *dev_priv = to_i915(crtc_state->base.crtc->dev);
4165         u32 plane_color_ctl = 0;
4166
4167         if (INTEL_GEN(dev_priv) >= 11)
4168                 return plane_color_ctl;
4169
4170         if (crtc_state->gamma_enable)
4171                 plane_color_ctl |= PLANE_COLOR_PIPE_GAMMA_ENABLE;
4172
4173         if (crtc_state->csc_enable)
4174                 plane_color_ctl |= PLANE_COLOR_PIPE_CSC_ENABLE;
4175
4176         return plane_color_ctl;
4177 }
4178
4179 u32 glk_plane_color_ctl(const struct intel_crtc_state *crtc_state,
4180                         const struct intel_plane_state *plane_state)
4181 {
4182         struct drm_i915_private *dev_priv =
4183                 to_i915(plane_state->base.plane->dev);
4184         const struct drm_framebuffer *fb = plane_state->base.fb;
4185         struct intel_plane *plane = to_intel_plane(plane_state->base.plane);
4186         u32 plane_color_ctl = 0;
4187
4188         plane_color_ctl |= PLANE_COLOR_PLANE_GAMMA_DISABLE;
4189         plane_color_ctl |= glk_plane_color_ctl_alpha(plane_state);
4190
4191         if (fb->format->is_yuv && !icl_is_hdr_plane(dev_priv, plane->id)) {
4192                 if (plane_state->base.color_encoding == DRM_COLOR_YCBCR_BT709)
4193                         plane_color_ctl |= PLANE_COLOR_CSC_MODE_YUV709_TO_RGB709;
4194                 else
4195                         plane_color_ctl |= PLANE_COLOR_CSC_MODE_YUV601_TO_RGB709;
4196
4197                 if (plane_state->base.color_range == DRM_COLOR_YCBCR_FULL_RANGE)
4198                         plane_color_ctl |= PLANE_COLOR_YUV_RANGE_CORRECTION_DISABLE;
4199         } else if (fb->format->is_yuv) {
4200                 plane_color_ctl |= PLANE_COLOR_INPUT_CSC_ENABLE;
4201         }
4202
4203         return plane_color_ctl;
4204 }
4205
4206 static int
4207 __intel_display_resume(struct drm_device *dev,
4208                        struct drm_atomic_state *state,
4209                        struct drm_modeset_acquire_ctx *ctx)
4210 {
4211         struct drm_crtc_state *crtc_state;
4212         struct drm_crtc *crtc;
4213         int i, ret;
4214
4215         intel_modeset_setup_hw_state(dev, ctx);
4216         i915_redisable_vga(to_i915(dev));
4217
4218         if (!state)
4219                 return 0;
4220
4221         /*
4222          * We've duplicated the state, pointers to the old state are invalid.
4223          *
4224          * Don't attempt to use the old state until we commit the duplicated state.
4225          */
4226         for_each_new_crtc_in_state(state, crtc, crtc_state, i) {
4227                 /*
4228                  * Force recalculation even if we restore
4229                  * current state. With fast modeset this may not result
4230                  * in a modeset when the state is compatible.
4231                  */
4232                 crtc_state->mode_changed = true;
4233         }
4234
4235         /* ignore any reset values/BIOS leftovers in the WM registers */
4236         if (!HAS_GMCH(to_i915(dev)))
4237                 to_intel_atomic_state(state)->skip_intermediate_wm = true;
4238
4239         ret = drm_atomic_helper_commit_duplicated_state(state, ctx);
4240
4241         WARN_ON(ret == -EDEADLK);
4242         return ret;
4243 }
4244
4245 static bool gpu_reset_clobbers_display(struct drm_i915_private *dev_priv)
4246 {
4247         return (INTEL_INFO(dev_priv)->gpu_reset_clobbers_display &&
4248                 intel_has_gpu_reset(dev_priv));
4249 }
4250
4251 void intel_prepare_reset(struct drm_i915_private *dev_priv)
4252 {
4253         struct drm_device *dev = &dev_priv->drm;
4254         struct drm_modeset_acquire_ctx *ctx = &dev_priv->reset_ctx;
4255         struct drm_atomic_state *state;
4256         int ret;
4257
4258         /* reset doesn't touch the display */
4259         if (!i915_modparams.force_reset_modeset_test &&
4260             !gpu_reset_clobbers_display(dev_priv))
4261                 return;
4262
4263         /* We have a modeset vs reset deadlock, defensively unbreak it. */
4264         set_bit(I915_RESET_MODESET, &dev_priv->gt.reset.flags);
4265         smp_mb__after_atomic();
4266         wake_up_bit(&dev_priv->gt.reset.flags, I915_RESET_MODESET);
4267
4268         if (atomic_read(&dev_priv->gpu_error.pending_fb_pin)) {
4269                 DRM_DEBUG_KMS("Modeset potentially stuck, unbreaking through wedging\n");
4270                 intel_gt_set_wedged(&dev_priv->gt);
4271         }
4272
4273         /*
4274          * Need mode_config.mutex so that we don't
4275          * trample ongoing ->detect() and whatnot.
4276          */
4277         mutex_lock(&dev->mode_config.mutex);
4278         drm_modeset_acquire_init(ctx, 0);
4279         while (1) {
4280                 ret = drm_modeset_lock_all_ctx(dev, ctx);
4281                 if (ret != -EDEADLK)
4282                         break;
4283
4284                 drm_modeset_backoff(ctx);
4285         }
4286         /*
4287          * Disabling the crtcs gracefully seems nicer. Also the
4288          * g33 docs say we should at least disable all the planes.
4289          */
4290         state = drm_atomic_helper_duplicate_state(dev, ctx);
4291         if (IS_ERR(state)) {
4292                 ret = PTR_ERR(state);
4293                 DRM_ERROR("Duplicating state failed with %i\n", ret);
4294                 return;
4295         }
4296
4297         ret = drm_atomic_helper_disable_all(dev, ctx);
4298         if (ret) {
4299                 DRM_ERROR("Suspending crtc's failed with %i\n", ret);
4300                 drm_atomic_state_put(state);
4301                 return;
4302         }
4303
4304         dev_priv->modeset_restore_state = state;
4305         state->acquire_ctx = ctx;
4306 }
4307
4308 void intel_finish_reset(struct drm_i915_private *dev_priv)
4309 {
4310         struct drm_device *dev = &dev_priv->drm;
4311         struct drm_modeset_acquire_ctx *ctx = &dev_priv->reset_ctx;
4312         struct drm_atomic_state *state;
4313         int ret;
4314
4315         /* reset doesn't touch the display */
4316         if (!test_bit(I915_RESET_MODESET, &dev_priv->gt.reset.flags))
4317                 return;
4318
4319         state = fetch_and_zero(&dev_priv->modeset_restore_state);
4320         if (!state)
4321                 goto unlock;
4322
4323         /* reset doesn't touch the display */
4324         if (!gpu_reset_clobbers_display(dev_priv)) {
4325                 /* for testing only restore the display */
4326                 ret = __intel_display_resume(dev, state, ctx);
4327                 if (ret)
4328                         DRM_ERROR("Restoring old state failed with %i\n", ret);
4329         } else {
4330                 /*
4331                  * The display has been reset as well,
4332                  * so need a full re-initialization.
4333                  */
4334                 intel_pps_unlock_regs_wa(dev_priv);
4335                 intel_modeset_init_hw(dev);
4336                 intel_init_clock_gating(dev_priv);
4337
4338                 spin_lock_irq(&dev_priv->irq_lock);
4339                 if (dev_priv->display.hpd_irq_setup)
4340                         dev_priv->display.hpd_irq_setup(dev_priv);
4341                 spin_unlock_irq(&dev_priv->irq_lock);
4342
4343                 ret = __intel_display_resume(dev, state, ctx);
4344                 if (ret)
4345                         DRM_ERROR("Restoring old state failed with %i\n", ret);
4346
4347                 intel_hpd_init(dev_priv);
4348         }
4349
4350         drm_atomic_state_put(state);
4351 unlock:
4352         drm_modeset_drop_locks(ctx);
4353         drm_modeset_acquire_fini(ctx);
4354         mutex_unlock(&dev->mode_config.mutex);
4355
4356         clear_bit_unlock(I915_RESET_MODESET, &dev_priv->gt.reset.flags);
4357 }
4358
4359 static void icl_set_pipe_chicken(struct intel_crtc *crtc)
4360 {
4361         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
4362         enum pipe pipe = crtc->pipe;
4363         u32 tmp;
4364
4365         tmp = I915_READ(PIPE_CHICKEN(pipe));
4366
4367         /*
4368          * Display WA #1153: icl
4369          * enable hardware to bypass the alpha math
4370          * and rounding for per-pixel values 00 and 0xff
4371          */
4372         tmp |= PER_PIXEL_ALPHA_BYPASS_EN;
4373         /*
4374          * Display WA # 1605353570: icl
4375          * Set the pixel rounding bit to 1 for allowing
4376          * passthrough of Frame buffer pixels unmodified
4377          * across pipe
4378          */
4379         tmp |= PIXEL_ROUNDING_TRUNC_FB_PASSTHRU;
4380         I915_WRITE(PIPE_CHICKEN(pipe), tmp);
4381 }
4382
4383 static void intel_update_pipe_config(const struct intel_crtc_state *old_crtc_state,
4384                                      const struct intel_crtc_state *new_crtc_state)
4385 {
4386         struct intel_crtc *crtc = to_intel_crtc(new_crtc_state->base.crtc);
4387         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
4388
4389         /* drm_atomic_helper_update_legacy_modeset_state might not be called. */
4390         crtc->base.mode = new_crtc_state->base.mode;
4391
4392         /*
4393          * Update pipe size and adjust fitter if needed: the reason for this is
4394          * that in compute_mode_changes we check the native mode (not the pfit
4395          * mode) to see if we can flip rather than do a full mode set. In the
4396          * fastboot case, we'll flip, but if we don't update the pipesrc and
4397          * pfit state, we'll end up with a big fb scanned out into the wrong
4398          * sized surface.
4399          */
4400
4401         I915_WRITE(PIPESRC(crtc->pipe),
4402                    ((new_crtc_state->pipe_src_w - 1) << 16) |
4403                    (new_crtc_state->pipe_src_h - 1));
4404
4405         /* on skylake this is done by detaching scalers */
4406         if (INTEL_GEN(dev_priv) >= 9) {
4407                 skl_detach_scalers(new_crtc_state);
4408
4409                 if (new_crtc_state->pch_pfit.enabled)
4410                         skylake_pfit_enable(new_crtc_state);
4411         } else if (HAS_PCH_SPLIT(dev_priv)) {
4412                 if (new_crtc_state->pch_pfit.enabled)
4413                         ironlake_pfit_enable(new_crtc_state);
4414                 else if (old_crtc_state->pch_pfit.enabled)
4415                         ironlake_pfit_disable(old_crtc_state);
4416         }
4417
4418         if (INTEL_GEN(dev_priv) >= 11)
4419                 icl_set_pipe_chicken(crtc);
4420 }
4421
4422 static void intel_fdi_normal_train(struct intel_crtc *crtc)
4423 {
4424         struct drm_device *dev = crtc->base.dev;
4425         struct drm_i915_private *dev_priv = to_i915(dev);
4426         enum pipe pipe = crtc->pipe;
4427         i915_reg_t reg;
4428         u32 temp;
4429
4430         /* enable normal train */
4431         reg = FDI_TX_CTL(pipe);
4432         temp = I915_READ(reg);
4433         if (IS_IVYBRIDGE(dev_priv)) {
4434                 temp &= ~FDI_LINK_TRAIN_NONE_IVB;
4435                 temp |= FDI_LINK_TRAIN_NONE_IVB | FDI_TX_ENHANCE_FRAME_ENABLE;
4436         } else {
4437                 temp &= ~FDI_LINK_TRAIN_NONE;
4438                 temp |= FDI_LINK_TRAIN_NONE | FDI_TX_ENHANCE_FRAME_ENABLE;
4439         }
4440         I915_WRITE(reg, temp);
4441
4442         reg = FDI_RX_CTL(pipe);
4443         temp = I915_READ(reg);
4444         if (HAS_PCH_CPT(dev_priv)) {
4445                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
4446                 temp |= FDI_LINK_TRAIN_NORMAL_CPT;
4447         } else {
4448                 temp &= ~FDI_LINK_TRAIN_NONE;
4449                 temp |= FDI_LINK_TRAIN_NONE;
4450         }
4451         I915_WRITE(reg, temp | FDI_RX_ENHANCE_FRAME_ENABLE);
4452
4453         /* wait one idle pattern time */
4454         POSTING_READ(reg);
4455         udelay(1000);
4456
4457         /* IVB wants error correction enabled */
4458         if (IS_IVYBRIDGE(dev_priv))
4459                 I915_WRITE(reg, I915_READ(reg) | FDI_FS_ERRC_ENABLE |
4460                            FDI_FE_ERRC_ENABLE);
4461 }
4462
4463 /* The FDI link training functions for ILK/Ibexpeak. */
4464 static void ironlake_fdi_link_train(struct intel_crtc *crtc,
4465                                     const struct intel_crtc_state *crtc_state)
4466 {
4467         struct drm_device *dev = crtc->base.dev;
4468         struct drm_i915_private *dev_priv = to_i915(dev);
4469         enum pipe pipe = crtc->pipe;
4470         i915_reg_t reg;
4471         u32 temp, tries;
4472
4473         /* FDI needs bits from pipe first */
4474         assert_pipe_enabled(dev_priv, pipe);
4475
4476         /* Train 1: umask FDI RX Interrupt symbol_lock and bit_lock bit
4477            for train result */
4478         reg = FDI_RX_IMR(pipe);
4479         temp = I915_READ(reg);
4480         temp &= ~FDI_RX_SYMBOL_LOCK;
4481         temp &= ~FDI_RX_BIT_LOCK;
4482         I915_WRITE(reg, temp);
4483         I915_READ(reg);
4484         udelay(150);
4485
4486         /* enable CPU FDI TX and PCH FDI RX */
4487         reg = FDI_TX_CTL(pipe);
4488         temp = I915_READ(reg);
4489         temp &= ~FDI_DP_PORT_WIDTH_MASK;
4490         temp |= FDI_DP_PORT_WIDTH(crtc_state->fdi_lanes);
4491         temp &= ~FDI_LINK_TRAIN_NONE;
4492         temp |= FDI_LINK_TRAIN_PATTERN_1;
4493         I915_WRITE(reg, temp | FDI_TX_ENABLE);
4494
4495         reg = FDI_RX_CTL(pipe);
4496         temp = I915_READ(reg);
4497         temp &= ~FDI_LINK_TRAIN_NONE;
4498         temp |= FDI_LINK_TRAIN_PATTERN_1;
4499         I915_WRITE(reg, temp | FDI_RX_ENABLE);
4500
4501         POSTING_READ(reg);
4502         udelay(150);
4503
4504         /* Ironlake workaround, enable clock pointer after FDI enable*/
4505         I915_WRITE(FDI_RX_CHICKEN(pipe), FDI_RX_PHASE_SYNC_POINTER_OVR);
4506         I915_WRITE(FDI_RX_CHICKEN(pipe), FDI_RX_PHASE_SYNC_POINTER_OVR |
4507                    FDI_RX_PHASE_SYNC_POINTER_EN);
4508
4509         reg = FDI_RX_IIR(pipe);
4510         for (tries = 0; tries < 5; tries++) {
4511                 temp = I915_READ(reg);
4512                 DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
4513
4514                 if ((temp & FDI_RX_BIT_LOCK)) {
4515                         DRM_DEBUG_KMS("FDI train 1 done.\n");
4516                         I915_WRITE(reg, temp | FDI_RX_BIT_LOCK);
4517                         break;
4518                 }
4519         }
4520         if (tries == 5)
4521                 DRM_ERROR("FDI train 1 fail!\n");
4522
4523         /* Train 2 */
4524         reg = FDI_TX_CTL(pipe);
4525         temp = I915_READ(reg);
4526         temp &= ~FDI_LINK_TRAIN_NONE;
4527         temp |= FDI_LINK_TRAIN_PATTERN_2;
4528         I915_WRITE(reg, temp);
4529
4530         reg = FDI_RX_CTL(pipe);
4531         temp = I915_READ(reg);
4532         temp &= ~FDI_LINK_TRAIN_NONE;
4533         temp |= FDI_LINK_TRAIN_PATTERN_2;
4534         I915_WRITE(reg, temp);
4535
4536         POSTING_READ(reg);
4537         udelay(150);
4538
4539         reg = FDI_RX_IIR(pipe);
4540         for (tries = 0; tries < 5; tries++) {
4541                 temp = I915_READ(reg);
4542                 DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
4543
4544                 if (temp & FDI_RX_SYMBOL_LOCK) {
4545                         I915_WRITE(reg, temp | FDI_RX_SYMBOL_LOCK);
4546                         DRM_DEBUG_KMS("FDI train 2 done.\n");
4547                         break;
4548                 }
4549         }
4550         if (tries == 5)
4551                 DRM_ERROR("FDI train 2 fail!\n");
4552
4553         DRM_DEBUG_KMS("FDI train done\n");
4554
4555 }
4556
4557 static const int snb_b_fdi_train_param[] = {
4558         FDI_LINK_TRAIN_400MV_0DB_SNB_B,
4559         FDI_LINK_TRAIN_400MV_6DB_SNB_B,
4560         FDI_LINK_TRAIN_600MV_3_5DB_SNB_B,
4561         FDI_LINK_TRAIN_800MV_0DB_SNB_B,
4562 };
4563
4564 /* The FDI link training functions for SNB/Cougarpoint. */
4565 static void gen6_fdi_link_train(struct intel_crtc *crtc,
4566                                 const struct intel_crtc_state *crtc_state)
4567 {
4568         struct drm_device *dev = crtc->base.dev;
4569         struct drm_i915_private *dev_priv = to_i915(dev);
4570         enum pipe pipe = crtc->pipe;
4571         i915_reg_t reg;
4572         u32 temp, i, retry;
4573
4574         /* Train 1: umask FDI RX Interrupt symbol_lock and bit_lock bit
4575            for train result */
4576         reg = FDI_RX_IMR(pipe);
4577         temp = I915_READ(reg);
4578         temp &= ~FDI_RX_SYMBOL_LOCK;
4579         temp &= ~FDI_RX_BIT_LOCK;
4580         I915_WRITE(reg, temp);
4581
4582         POSTING_READ(reg);
4583         udelay(150);
4584
4585         /* enable CPU FDI TX and PCH FDI RX */
4586         reg = FDI_TX_CTL(pipe);
4587         temp = I915_READ(reg);
4588         temp &= ~FDI_DP_PORT_WIDTH_MASK;
4589         temp |= FDI_DP_PORT_WIDTH(crtc_state->fdi_lanes);
4590         temp &= ~FDI_LINK_TRAIN_NONE;
4591         temp |= FDI_LINK_TRAIN_PATTERN_1;
4592         temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
4593         /* SNB-B */
4594         temp |= FDI_LINK_TRAIN_400MV_0DB_SNB_B;
4595         I915_WRITE(reg, temp | FDI_TX_ENABLE);
4596
4597         I915_WRITE(FDI_RX_MISC(pipe),
4598                    FDI_RX_TP1_TO_TP2_48 | FDI_RX_FDI_DELAY_90);
4599
4600         reg = FDI_RX_CTL(pipe);
4601         temp = I915_READ(reg);
4602         if (HAS_PCH_CPT(dev_priv)) {
4603                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
4604                 temp |= FDI_LINK_TRAIN_PATTERN_1_CPT;
4605         } else {
4606                 temp &= ~FDI_LINK_TRAIN_NONE;
4607                 temp |= FDI_LINK_TRAIN_PATTERN_1;
4608         }
4609         I915_WRITE(reg, temp | FDI_RX_ENABLE);
4610
4611         POSTING_READ(reg);
4612         udelay(150);
4613
4614         for (i = 0; i < 4; i++) {
4615                 reg = FDI_TX_CTL(pipe);
4616                 temp = I915_READ(reg);
4617                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
4618                 temp |= snb_b_fdi_train_param[i];
4619                 I915_WRITE(reg, temp);
4620
4621                 POSTING_READ(reg);
4622                 udelay(500);
4623
4624                 for (retry = 0; retry < 5; retry++) {
4625                         reg = FDI_RX_IIR(pipe);
4626                         temp = I915_READ(reg);
4627                         DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
4628                         if (temp & FDI_RX_BIT_LOCK) {
4629                                 I915_WRITE(reg, temp | FDI_RX_BIT_LOCK);
4630                                 DRM_DEBUG_KMS("FDI train 1 done.\n");
4631                                 break;
4632                         }
4633                         udelay(50);
4634                 }
4635                 if (retry < 5)
4636                         break;
4637         }
4638         if (i == 4)
4639                 DRM_ERROR("FDI train 1 fail!\n");
4640
4641         /* Train 2 */
4642         reg = FDI_TX_CTL(pipe);
4643         temp = I915_READ(reg);
4644         temp &= ~FDI_LINK_TRAIN_NONE;
4645         temp |= FDI_LINK_TRAIN_PATTERN_2;
4646         if (IS_GEN(dev_priv, 6)) {
4647                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
4648                 /* SNB-B */
4649                 temp |= FDI_LINK_TRAIN_400MV_0DB_SNB_B;
4650         }
4651         I915_WRITE(reg, temp);
4652
4653         reg = FDI_RX_CTL(pipe);
4654         temp = I915_READ(reg);
4655         if (HAS_PCH_CPT(dev_priv)) {
4656                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
4657                 temp |= FDI_LINK_TRAIN_PATTERN_2_CPT;
4658         } else {
4659                 temp &= ~FDI_LINK_TRAIN_NONE;
4660                 temp |= FDI_LINK_TRAIN_PATTERN_2;
4661         }
4662         I915_WRITE(reg, temp);
4663
4664         POSTING_READ(reg);
4665         udelay(150);
4666
4667         for (i = 0; i < 4; i++) {
4668                 reg = FDI_TX_CTL(pipe);
4669                 temp = I915_READ(reg);
4670                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
4671                 temp |= snb_b_fdi_train_param[i];
4672                 I915_WRITE(reg, temp);
4673
4674                 POSTING_READ(reg);
4675                 udelay(500);
4676
4677                 for (retry = 0; retry < 5; retry++) {
4678                         reg = FDI_RX_IIR(pipe);
4679                         temp = I915_READ(reg);
4680                         DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
4681                         if (temp & FDI_RX_SYMBOL_LOCK) {
4682                                 I915_WRITE(reg, temp | FDI_RX_SYMBOL_LOCK);
4683                                 DRM_DEBUG_KMS("FDI train 2 done.\n");
4684                                 break;
4685                         }
4686                         udelay(50);
4687                 }
4688                 if (retry < 5)
4689                         break;
4690         }
4691         if (i == 4)
4692                 DRM_ERROR("FDI train 2 fail!\n");
4693
4694         DRM_DEBUG_KMS("FDI train done.\n");
4695 }
4696
4697 /* Manual link training for Ivy Bridge A0 parts */
4698 static void ivb_manual_fdi_link_train(struct intel_crtc *crtc,
4699                                       const struct intel_crtc_state *crtc_state)
4700 {
4701         struct drm_device *dev = crtc->base.dev;
4702         struct drm_i915_private *dev_priv = to_i915(dev);
4703         enum pipe pipe = crtc->pipe;
4704         i915_reg_t reg;
4705         u32 temp, i, j;
4706
4707         /* Train 1: umask FDI RX Interrupt symbol_lock and bit_lock bit
4708            for train result */
4709         reg = FDI_RX_IMR(pipe);
4710         temp = I915_READ(reg);
4711         temp &= ~FDI_RX_SYMBOL_LOCK;
4712         temp &= ~FDI_RX_BIT_LOCK;
4713         I915_WRITE(reg, temp);
4714
4715         POSTING_READ(reg);
4716         udelay(150);
4717
4718         DRM_DEBUG_KMS("FDI_RX_IIR before link train 0x%x\n",
4719                       I915_READ(FDI_RX_IIR(pipe)));
4720
4721         /* Try each vswing and preemphasis setting twice before moving on */
4722         for (j = 0; j < ARRAY_SIZE(snb_b_fdi_train_param) * 2; j++) {
4723                 /* disable first in case we need to retry */
4724                 reg = FDI_TX_CTL(pipe);
4725                 temp = I915_READ(reg);
4726                 temp &= ~(FDI_LINK_TRAIN_AUTO | FDI_LINK_TRAIN_NONE_IVB);
4727                 temp &= ~FDI_TX_ENABLE;
4728                 I915_WRITE(reg, temp);
4729
4730                 reg = FDI_RX_CTL(pipe);
4731                 temp = I915_READ(reg);
4732                 temp &= ~FDI_LINK_TRAIN_AUTO;
4733                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
4734                 temp &= ~FDI_RX_ENABLE;
4735                 I915_WRITE(reg, temp);
4736
4737                 /* enable CPU FDI TX and PCH FDI RX */
4738                 reg = FDI_TX_CTL(pipe);
4739                 temp = I915_READ(reg);
4740                 temp &= ~FDI_DP_PORT_WIDTH_MASK;
4741                 temp |= FDI_DP_PORT_WIDTH(crtc_state->fdi_lanes);
4742                 temp |= FDI_LINK_TRAIN_PATTERN_1_IVB;
4743                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
4744                 temp |= snb_b_fdi_train_param[j/2];
4745                 temp |= FDI_COMPOSITE_SYNC;
4746                 I915_WRITE(reg, temp | FDI_TX_ENABLE);
4747
4748                 I915_WRITE(FDI_RX_MISC(pipe),
4749                            FDI_RX_TP1_TO_TP2_48 | FDI_RX_FDI_DELAY_90);
4750
4751                 reg = FDI_RX_CTL(pipe);
4752                 temp = I915_READ(reg);
4753                 temp |= FDI_LINK_TRAIN_PATTERN_1_CPT;
4754                 temp |= FDI_COMPOSITE_SYNC;
4755                 I915_WRITE(reg, temp | FDI_RX_ENABLE);
4756
4757                 POSTING_READ(reg);
4758                 udelay(1); /* should be 0.5us */
4759
4760                 for (i = 0; i < 4; i++) {
4761                         reg = FDI_RX_IIR(pipe);
4762                         temp = I915_READ(reg);
4763                         DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
4764
4765                         if (temp & FDI_RX_BIT_LOCK ||
4766                             (I915_READ(reg) & FDI_RX_BIT_LOCK)) {
4767                                 I915_WRITE(reg, temp | FDI_RX_BIT_LOCK);
4768                                 DRM_DEBUG_KMS("FDI train 1 done, level %i.\n",
4769                                               i);
4770                                 break;
4771                         }
4772                         udelay(1); /* should be 0.5us */
4773                 }
4774                 if (i == 4) {
4775                         DRM_DEBUG_KMS("FDI train 1 fail on vswing %d\n", j / 2);
4776                         continue;
4777                 }
4778
4779                 /* Train 2 */
4780                 reg = FDI_TX_CTL(pipe);
4781                 temp = I915_READ(reg);
4782                 temp &= ~FDI_LINK_TRAIN_NONE_IVB;
4783                 temp |= FDI_LINK_TRAIN_PATTERN_2_IVB;
4784                 I915_WRITE(reg, temp);
4785
4786                 reg = FDI_RX_CTL(pipe);
4787                 temp = I915_READ(reg);
4788                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
4789                 temp |= FDI_LINK_TRAIN_PATTERN_2_CPT;
4790                 I915_WRITE(reg, temp);
4791
4792                 POSTING_READ(reg);
4793                 udelay(2); /* should be 1.5us */
4794
4795                 for (i = 0; i < 4; i++) {
4796                         reg = FDI_RX_IIR(pipe);
4797                         temp = I915_READ(reg);
4798                         DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
4799
4800                         if (temp & FDI_RX_SYMBOL_LOCK ||
4801                             (I915_READ(reg) & FDI_RX_SYMBOL_LOCK)) {
4802                                 I915_WRITE(reg, temp | FDI_RX_SYMBOL_LOCK);
4803                                 DRM_DEBUG_KMS("FDI train 2 done, level %i.\n",
4804                                               i);
4805                                 goto train_done;
4806                         }
4807                         udelay(2); /* should be 1.5us */
4808                 }
4809                 if (i == 4)
4810                         DRM_DEBUG_KMS("FDI train 2 fail on vswing %d\n", j / 2);
4811         }
4812
4813 train_done:
4814         DRM_DEBUG_KMS("FDI train done.\n");
4815 }
4816
4817 static void ironlake_fdi_pll_enable(const struct intel_crtc_state *crtc_state)
4818 {
4819         struct intel_crtc *intel_crtc = to_intel_crtc(crtc_state->base.crtc);
4820         struct drm_i915_private *dev_priv = to_i915(intel_crtc->base.dev);
4821         enum pipe pipe = intel_crtc->pipe;
4822         i915_reg_t reg;
4823         u32 temp;
4824
4825         /* enable PCH FDI RX PLL, wait warmup plus DMI latency */
4826         reg = FDI_RX_CTL(pipe);
4827         temp = I915_READ(reg);
4828         temp &= ~(FDI_DP_PORT_WIDTH_MASK | (0x7 << 16));
4829         temp |= FDI_DP_PORT_WIDTH(crtc_state->fdi_lanes);
4830         temp |= (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) << 11;
4831         I915_WRITE(reg, temp | FDI_RX_PLL_ENABLE);
4832
4833         POSTING_READ(reg);
4834         udelay(200);
4835
4836         /* Switch from Rawclk to PCDclk */
4837         temp = I915_READ(reg);
4838         I915_WRITE(reg, temp | FDI_PCDCLK);
4839
4840         POSTING_READ(reg);
4841         udelay(200);
4842
4843         /* Enable CPU FDI TX PLL, always on for Ironlake */
4844         reg = FDI_TX_CTL(pipe);
4845         temp = I915_READ(reg);
4846         if ((temp & FDI_TX_PLL_ENABLE) == 0) {
4847                 I915_WRITE(reg, temp | FDI_TX_PLL_ENABLE);
4848
4849                 POSTING_READ(reg);
4850                 udelay(100);
4851         }
4852 }
4853
4854 static void ironlake_fdi_pll_disable(struct intel_crtc *intel_crtc)
4855 {
4856         struct drm_device *dev = intel_crtc->base.dev;
4857         struct drm_i915_private *dev_priv = to_i915(dev);
4858         enum pipe pipe = intel_crtc->pipe;
4859         i915_reg_t reg;
4860         u32 temp;
4861
4862         /* Switch from PCDclk to Rawclk */
4863         reg = FDI_RX_CTL(pipe);
4864         temp = I915_READ(reg);
4865         I915_WRITE(reg, temp & ~FDI_PCDCLK);
4866
4867         /* Disable CPU FDI TX PLL */
4868         reg = FDI_TX_CTL(pipe);
4869         temp = I915_READ(reg);
4870         I915_WRITE(reg, temp & ~FDI_TX_PLL_ENABLE);
4871
4872         POSTING_READ(reg);
4873         udelay(100);
4874
4875         reg = FDI_RX_CTL(pipe);
4876         temp = I915_READ(reg);
4877         I915_WRITE(reg, temp & ~FDI_RX_PLL_ENABLE);
4878
4879         /* Wait for the clocks to turn off. */
4880         POSTING_READ(reg);
4881         udelay(100);
4882 }
4883
4884 static void ironlake_fdi_disable(struct drm_crtc *crtc)
4885 {
4886         struct drm_device *dev = crtc->dev;
4887         struct drm_i915_private *dev_priv = to_i915(dev);
4888         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4889         enum pipe pipe = intel_crtc->pipe;
4890         i915_reg_t reg;
4891         u32 temp;
4892
4893         /* disable CPU FDI tx and PCH FDI rx */
4894         reg = FDI_TX_CTL(pipe);
4895         temp = I915_READ(reg);
4896         I915_WRITE(reg, temp & ~FDI_TX_ENABLE);
4897         POSTING_READ(reg);
4898
4899         reg = FDI_RX_CTL(pipe);
4900         temp = I915_READ(reg);
4901         temp &= ~(0x7 << 16);
4902         temp |= (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) << 11;
4903         I915_WRITE(reg, temp & ~FDI_RX_ENABLE);
4904
4905         POSTING_READ(reg);
4906         udelay(100);
4907
4908         /* Ironlake workaround, disable clock pointer after downing FDI */
4909         if (HAS_PCH_IBX(dev_priv))
4910                 I915_WRITE(FDI_RX_CHICKEN(pipe), FDI_RX_PHASE_SYNC_POINTER_OVR);
4911
4912         /* still set train pattern 1 */
4913         reg = FDI_TX_CTL(pipe);
4914         temp = I915_READ(reg);
4915         temp &= ~FDI_LINK_TRAIN_NONE;
4916         temp |= FDI_LINK_TRAIN_PATTERN_1;
4917         I915_WRITE(reg, temp);
4918
4919         reg = FDI_RX_CTL(pipe);
4920         temp = I915_READ(reg);
4921         if (HAS_PCH_CPT(dev_priv)) {
4922                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
4923                 temp |= FDI_LINK_TRAIN_PATTERN_1_CPT;
4924         } else {
4925                 temp &= ~FDI_LINK_TRAIN_NONE;
4926                 temp |= FDI_LINK_TRAIN_PATTERN_1;
4927         }
4928         /* BPC in FDI rx is consistent with that in PIPECONF */
4929         temp &= ~(0x07 << 16);
4930         temp |= (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) << 11;
4931         I915_WRITE(reg, temp);
4932
4933         POSTING_READ(reg);
4934         udelay(100);
4935 }
4936
4937 bool intel_has_pending_fb_unpin(struct drm_i915_private *dev_priv)
4938 {
4939         struct drm_crtc *crtc;
4940         bool cleanup_done;
4941
4942         drm_for_each_crtc(crtc, &dev_priv->drm) {
4943                 struct drm_crtc_commit *commit;
4944                 spin_lock(&crtc->commit_lock);
4945                 commit = list_first_entry_or_null(&crtc->commit_list,
4946                                                   struct drm_crtc_commit, commit_entry);
4947                 cleanup_done = commit ?
4948                         try_wait_for_completion(&commit->cleanup_done) : true;
4949                 spin_unlock(&crtc->commit_lock);
4950
4951                 if (cleanup_done)
4952                         continue;
4953
4954                 drm_crtc_wait_one_vblank(crtc);
4955
4956                 return true;
4957         }
4958
4959         return false;
4960 }
4961
4962 void lpt_disable_iclkip(struct drm_i915_private *dev_priv)
4963 {
4964         u32 temp;
4965
4966         I915_WRITE(PIXCLK_GATE, PIXCLK_GATE_GATE);
4967
4968         mutex_lock(&dev_priv->sb_lock);
4969
4970         temp = intel_sbi_read(dev_priv, SBI_SSCCTL6, SBI_ICLK);
4971         temp |= SBI_SSCCTL_DISABLE;
4972         intel_sbi_write(dev_priv, SBI_SSCCTL6, temp, SBI_ICLK);
4973
4974         mutex_unlock(&dev_priv->sb_lock);
4975 }
4976
4977 /* Program iCLKIP clock to the desired frequency */
4978 static void lpt_program_iclkip(const struct intel_crtc_state *crtc_state)
4979 {
4980         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
4981         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
4982         int clock = crtc_state->base.adjusted_mode.crtc_clock;
4983         u32 divsel, phaseinc, auxdiv, phasedir = 0;
4984         u32 temp;
4985
4986         lpt_disable_iclkip(dev_priv);
4987
4988         /* The iCLK virtual clock root frequency is in MHz,
4989          * but the adjusted_mode->crtc_clock in in KHz. To get the
4990          * divisors, it is necessary to divide one by another, so we
4991          * convert the virtual clock precision to KHz here for higher
4992          * precision.
4993          */
4994         for (auxdiv = 0; auxdiv < 2; auxdiv++) {
4995                 u32 iclk_virtual_root_freq = 172800 * 1000;
4996                 u32 iclk_pi_range = 64;
4997                 u32 desired_divisor;
4998
4999                 desired_divisor = DIV_ROUND_CLOSEST(iclk_virtual_root_freq,
5000                                                     clock << auxdiv);
5001                 divsel = (desired_divisor / iclk_pi_range) - 2;
5002                 phaseinc = desired_divisor % iclk_pi_range;
5003
5004                 /*
5005                  * Near 20MHz is a corner case which is
5006                  * out of range for the 7-bit divisor
5007                  */
5008                 if (divsel <= 0x7f)
5009                         break;
5010         }
5011
5012         /* This should not happen with any sane values */
5013         WARN_ON(SBI_SSCDIVINTPHASE_DIVSEL(divsel) &
5014                 ~SBI_SSCDIVINTPHASE_DIVSEL_MASK);
5015         WARN_ON(SBI_SSCDIVINTPHASE_DIR(phasedir) &
5016                 ~SBI_SSCDIVINTPHASE_INCVAL_MASK);
5017
5018         DRM_DEBUG_KMS("iCLKIP clock: found settings for %dKHz refresh rate: auxdiv=%x, divsel=%x, phasedir=%x, phaseinc=%x\n",
5019                         clock,
5020                         auxdiv,
5021                         divsel,
5022                         phasedir,
5023                         phaseinc);
5024
5025         mutex_lock(&dev_priv->sb_lock);
5026
5027         /* Program SSCDIVINTPHASE6 */
5028         temp = intel_sbi_read(dev_priv, SBI_SSCDIVINTPHASE6, SBI_ICLK);
5029         temp &= ~SBI_SSCDIVINTPHASE_DIVSEL_MASK;
5030         temp |= SBI_SSCDIVINTPHASE_DIVSEL(divsel);
5031         temp &= ~SBI_SSCDIVINTPHASE_INCVAL_MASK;
5032         temp |= SBI_SSCDIVINTPHASE_INCVAL(phaseinc);
5033         temp |= SBI_SSCDIVINTPHASE_DIR(phasedir);
5034         temp |= SBI_SSCDIVINTPHASE_PROPAGATE;
5035         intel_sbi_write(dev_priv, SBI_SSCDIVINTPHASE6, temp, SBI_ICLK);
5036
5037         /* Program SSCAUXDIV */
5038         temp = intel_sbi_read(dev_priv, SBI_SSCAUXDIV6, SBI_ICLK);
5039         temp &= ~SBI_SSCAUXDIV_FINALDIV2SEL(1);
5040         temp |= SBI_SSCAUXDIV_FINALDIV2SEL(auxdiv);
5041         intel_sbi_write(dev_priv, SBI_SSCAUXDIV6, temp, SBI_ICLK);
5042
5043         /* Enable modulator and associated divider */
5044         temp = intel_sbi_read(dev_priv, SBI_SSCCTL6, SBI_ICLK);
5045         temp &= ~SBI_SSCCTL_DISABLE;
5046         intel_sbi_write(dev_priv, SBI_SSCCTL6, temp, SBI_ICLK);
5047
5048         mutex_unlock(&dev_priv->sb_lock);
5049
5050         /* Wait for initialization time */
5051         udelay(24);
5052
5053         I915_WRITE(PIXCLK_GATE, PIXCLK_GATE_UNGATE);
5054 }
5055
5056 int lpt_get_iclkip(struct drm_i915_private *dev_priv)
5057 {
5058         u32 divsel, phaseinc, auxdiv;
5059         u32 iclk_virtual_root_freq = 172800 * 1000;
5060         u32 iclk_pi_range = 64;
5061         u32 desired_divisor;
5062         u32 temp;
5063
5064         if ((I915_READ(PIXCLK_GATE) & PIXCLK_GATE_UNGATE) == 0)
5065                 return 0;
5066
5067         mutex_lock(&dev_priv->sb_lock);
5068
5069         temp = intel_sbi_read(dev_priv, SBI_SSCCTL6, SBI_ICLK);
5070         if (temp & SBI_SSCCTL_DISABLE) {
5071                 mutex_unlock(&dev_priv->sb_lock);
5072                 return 0;
5073         }
5074
5075         temp = intel_sbi_read(dev_priv, SBI_SSCDIVINTPHASE6, SBI_ICLK);
5076         divsel = (temp & SBI_SSCDIVINTPHASE_DIVSEL_MASK) >>
5077                 SBI_SSCDIVINTPHASE_DIVSEL_SHIFT;
5078         phaseinc = (temp & SBI_SSCDIVINTPHASE_INCVAL_MASK) >>
5079                 SBI_SSCDIVINTPHASE_INCVAL_SHIFT;
5080
5081         temp = intel_sbi_read(dev_priv, SBI_SSCAUXDIV6, SBI_ICLK);
5082         auxdiv = (temp & SBI_SSCAUXDIV_FINALDIV2SEL_MASK) >>
5083                 SBI_SSCAUXDIV_FINALDIV2SEL_SHIFT;
5084
5085         mutex_unlock(&dev_priv->sb_lock);
5086
5087         desired_divisor = (divsel + 2) * iclk_pi_range + phaseinc;
5088
5089         return DIV_ROUND_CLOSEST(iclk_virtual_root_freq,
5090                                  desired_divisor << auxdiv);
5091 }
5092
5093 static void ironlake_pch_transcoder_set_timings(const struct intel_crtc_state *crtc_state,
5094                                                 enum pipe pch_transcoder)
5095 {
5096         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
5097         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
5098         enum transcoder cpu_transcoder = crtc_state->cpu_transcoder;
5099
5100         I915_WRITE(PCH_TRANS_HTOTAL(pch_transcoder),
5101                    I915_READ(HTOTAL(cpu_transcoder)));
5102         I915_WRITE(PCH_TRANS_HBLANK(pch_transcoder),
5103                    I915_READ(HBLANK(cpu_transcoder)));
5104         I915_WRITE(PCH_TRANS_HSYNC(pch_transcoder),
5105                    I915_READ(HSYNC(cpu_transcoder)));
5106
5107         I915_WRITE(PCH_TRANS_VTOTAL(pch_transcoder),
5108                    I915_READ(VTOTAL(cpu_transcoder)));
5109         I915_WRITE(PCH_TRANS_VBLANK(pch_transcoder),
5110                    I915_READ(VBLANK(cpu_transcoder)));
5111         I915_WRITE(PCH_TRANS_VSYNC(pch_transcoder),
5112                    I915_READ(VSYNC(cpu_transcoder)));
5113         I915_WRITE(PCH_TRANS_VSYNCSHIFT(pch_transcoder),
5114                    I915_READ(VSYNCSHIFT(cpu_transcoder)));
5115 }
5116
5117 static void cpt_set_fdi_bc_bifurcation(struct drm_i915_private *dev_priv, bool enable)
5118 {
5119         u32 temp;
5120
5121         temp = I915_READ(SOUTH_CHICKEN1);
5122         if (!!(temp & FDI_BC_BIFURCATION_SELECT) == enable)
5123                 return;
5124
5125         WARN_ON(I915_READ(FDI_RX_CTL(PIPE_B)) & FDI_RX_ENABLE);
5126         WARN_ON(I915_READ(FDI_RX_CTL(PIPE_C)) & FDI_RX_ENABLE);
5127
5128         temp &= ~FDI_BC_BIFURCATION_SELECT;
5129         if (enable)
5130                 temp |= FDI_BC_BIFURCATION_SELECT;
5131
5132         DRM_DEBUG_KMS("%sabling fdi C rx\n", enable ? "en" : "dis");
5133         I915_WRITE(SOUTH_CHICKEN1, temp);
5134         POSTING_READ(SOUTH_CHICKEN1);
5135 }
5136
5137 static void ivybridge_update_fdi_bc_bifurcation(const struct intel_crtc_state *crtc_state)
5138 {
5139         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
5140         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
5141
5142         switch (crtc->pipe) {
5143         case PIPE_A:
5144                 break;
5145         case PIPE_B:
5146                 if (crtc_state->fdi_lanes > 2)
5147                         cpt_set_fdi_bc_bifurcation(dev_priv, false);
5148                 else
5149                         cpt_set_fdi_bc_bifurcation(dev_priv, true);
5150
5151                 break;
5152         case PIPE_C:
5153                 cpt_set_fdi_bc_bifurcation(dev_priv, true);
5154
5155                 break;
5156         default:
5157                 BUG();
5158         }
5159 }
5160
5161 /*
5162  * Finds the encoder associated with the given CRTC. This can only be
5163  * used when we know that the CRTC isn't feeding multiple encoders!
5164  */
5165 static struct intel_encoder *
5166 intel_get_crtc_new_encoder(const struct intel_atomic_state *state,
5167                            const struct intel_crtc_state *crtc_state)
5168 {
5169         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
5170         const struct drm_connector_state *connector_state;
5171         const struct drm_connector *connector;
5172         struct intel_encoder *encoder = NULL;
5173         int num_encoders = 0;
5174         int i;
5175
5176         for_each_new_connector_in_state(&state->base, connector, connector_state, i) {
5177                 if (connector_state->crtc != &crtc->base)
5178                         continue;
5179
5180                 encoder = to_intel_encoder(connector_state->best_encoder);
5181                 num_encoders++;
5182         }
5183
5184         WARN(num_encoders != 1, "%d encoders for pipe %c\n",
5185              num_encoders, pipe_name(crtc->pipe));
5186
5187         return encoder;
5188 }
5189
5190 /*
5191  * Enable PCH resources required for PCH ports:
5192  *   - PCH PLLs
5193  *   - FDI training & RX/TX
5194  *   - update transcoder timings
5195  *   - DP transcoding bits
5196  *   - transcoder
5197  */
5198 static void ironlake_pch_enable(const struct intel_atomic_state *state,
5199                                 const struct intel_crtc_state *crtc_state)
5200 {
5201         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
5202         struct drm_device *dev = crtc->base.dev;
5203         struct drm_i915_private *dev_priv = to_i915(dev);
5204         enum pipe pipe = crtc->pipe;
5205         u32 temp;
5206
5207         assert_pch_transcoder_disabled(dev_priv, pipe);
5208
5209         if (IS_IVYBRIDGE(dev_priv))
5210                 ivybridge_update_fdi_bc_bifurcation(crtc_state);
5211
5212         /* Write the TU size bits before fdi link training, so that error
5213          * detection works. */
5214         I915_WRITE(FDI_RX_TUSIZE1(pipe),
5215                    I915_READ(PIPE_DATA_M1(pipe)) & TU_SIZE_MASK);
5216
5217         /* For PCH output, training FDI link */
5218         dev_priv->display.fdi_link_train(crtc, crtc_state);
5219
5220         /* We need to program the right clock selection before writing the pixel
5221          * mutliplier into the DPLL. */
5222         if (HAS_PCH_CPT(dev_priv)) {
5223                 u32 sel;
5224
5225                 temp = I915_READ(PCH_DPLL_SEL);
5226                 temp |= TRANS_DPLL_ENABLE(pipe);
5227                 sel = TRANS_DPLLB_SEL(pipe);
5228                 if (crtc_state->shared_dpll ==
5229                     intel_get_shared_dpll_by_id(dev_priv, DPLL_ID_PCH_PLL_B))
5230                         temp |= sel;
5231                 else
5232                         temp &= ~sel;
5233                 I915_WRITE(PCH_DPLL_SEL, temp);
5234         }
5235
5236         /* XXX: pch pll's can be enabled any time before we enable the PCH
5237          * transcoder, and we actually should do this to not upset any PCH
5238          * transcoder that already use the clock when we share it.
5239          *
5240          * Note that enable_shared_dpll tries to do the right thing, but
5241          * get_shared_dpll unconditionally resets the pll - we need that to have
5242          * the right LVDS enable sequence. */
5243         intel_enable_shared_dpll(crtc_state);
5244
5245         /* set transcoder timing, panel must allow it */
5246         assert_panel_unlocked(dev_priv, pipe);
5247         ironlake_pch_transcoder_set_timings(crtc_state, pipe);
5248
5249         intel_fdi_normal_train(crtc);
5250
5251         /* For PCH DP, enable TRANS_DP_CTL */
5252         if (HAS_PCH_CPT(dev_priv) &&
5253             intel_crtc_has_dp_encoder(crtc_state)) {
5254                 const struct drm_display_mode *adjusted_mode =
5255                         &crtc_state->base.adjusted_mode;
5256                 u32 bpc = (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) >> 5;
5257                 i915_reg_t reg = TRANS_DP_CTL(pipe);
5258                 enum port port;
5259
5260                 temp = I915_READ(reg);
5261                 temp &= ~(TRANS_DP_PORT_SEL_MASK |
5262                           TRANS_DP_SYNC_MASK |
5263                           TRANS_DP_BPC_MASK);
5264                 temp |= TRANS_DP_OUTPUT_ENABLE;
5265                 temp |= bpc << 9; /* same format but at 11:9 */
5266
5267                 if (adjusted_mode->flags & DRM_MODE_FLAG_PHSYNC)
5268                         temp |= TRANS_DP_HSYNC_ACTIVE_HIGH;
5269                 if (adjusted_mode->flags & DRM_MODE_FLAG_PVSYNC)
5270                         temp |= TRANS_DP_VSYNC_ACTIVE_HIGH;
5271
5272                 port = intel_get_crtc_new_encoder(state, crtc_state)->port;
5273                 WARN_ON(port < PORT_B || port > PORT_D);
5274                 temp |= TRANS_DP_PORT_SEL(port);
5275
5276                 I915_WRITE(reg, temp);
5277         }
5278
5279         ironlake_enable_pch_transcoder(crtc_state);
5280 }
5281
5282 static void lpt_pch_enable(const struct intel_atomic_state *state,
5283                            const struct intel_crtc_state *crtc_state)
5284 {
5285         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
5286         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
5287         enum transcoder cpu_transcoder = crtc_state->cpu_transcoder;
5288
5289         assert_pch_transcoder_disabled(dev_priv, PIPE_A);
5290
5291         lpt_program_iclkip(crtc_state);
5292
5293         /* Set transcoder timing. */
5294         ironlake_pch_transcoder_set_timings(crtc_state, PIPE_A);
5295
5296         lpt_enable_pch_transcoder(dev_priv, cpu_transcoder);
5297 }
5298
5299 static void cpt_verify_modeset(struct drm_device *dev, enum pipe pipe)
5300 {
5301         struct drm_i915_private *dev_priv = to_i915(dev);
5302         i915_reg_t dslreg = PIPEDSL(pipe);
5303         u32 temp;
5304
5305         temp = I915_READ(dslreg);
5306         udelay(500);
5307         if (wait_for(I915_READ(dslreg) != temp, 5)) {
5308                 if (wait_for(I915_READ(dslreg) != temp, 5))
5309                         DRM_ERROR("mode set failed: pipe %c stuck\n", pipe_name(pipe));
5310         }
5311 }
5312
5313 /*
5314  * The hardware phase 0.0 refers to the center of the pixel.
5315  * We want to start from the top/left edge which is phase
5316  * -0.5. That matches how the hardware calculates the scaling
5317  * factors (from top-left of the first pixel to bottom-right
5318  * of the last pixel, as opposed to the pixel centers).
5319  *
5320  * For 4:2:0 subsampled chroma planes we obviously have to
5321  * adjust that so that the chroma sample position lands in
5322  * the right spot.
5323  *
5324  * Note that for packed YCbCr 4:2:2 formats there is no way to
5325  * control chroma siting. The hardware simply replicates the
5326  * chroma samples for both of the luma samples, and thus we don't
5327  * actually get the expected MPEG2 chroma siting convention :(
5328  * The same behaviour is observed on pre-SKL platforms as well.
5329  *
5330  * Theory behind the formula (note that we ignore sub-pixel
5331  * source coordinates):
5332  * s = source sample position
5333  * d = destination sample position
5334  *
5335  * Downscaling 4:1:
5336  * -0.5
5337  * | 0.0
5338  * | |     1.5 (initial phase)
5339  * | |     |
5340  * v v     v
5341  * | s | s | s | s |
5342  * |       d       |
5343  *
5344  * Upscaling 1:4:
5345  * -0.5
5346  * | -0.375 (initial phase)
5347  * | |     0.0
5348  * | |     |
5349  * v v     v
5350  * |       s       |
5351  * | d | d | d | d |
5352  */
5353 u16 skl_scaler_calc_phase(int sub, int scale, bool chroma_cosited)
5354 {
5355         int phase = -0x8000;
5356         u16 trip = 0;
5357
5358         if (chroma_cosited)
5359                 phase += (sub - 1) * 0x8000 / sub;
5360
5361         phase += scale / (2 * sub);
5362
5363         /*
5364          * Hardware initial phase limited to [-0.5:1.5].
5365          * Since the max hardware scale factor is 3.0, we
5366          * should never actually excdeed 1.0 here.
5367          */
5368         WARN_ON(phase < -0x8000 || phase > 0x18000);
5369
5370         if (phase < 0)
5371                 phase = 0x10000 + phase;
5372         else
5373                 trip = PS_PHASE_TRIP;
5374
5375         return ((phase >> 2) & PS_PHASE_MASK) | trip;
5376 }
5377
5378 #define SKL_MIN_SRC_W 8
5379 #define SKL_MAX_SRC_W 4096
5380 #define SKL_MIN_SRC_H 8
5381 #define SKL_MAX_SRC_H 4096
5382 #define SKL_MIN_DST_W 8
5383 #define SKL_MAX_DST_W 4096
5384 #define SKL_MIN_DST_H 8
5385 #define SKL_MAX_DST_H 4096
5386 #define ICL_MAX_SRC_W 5120
5387 #define ICL_MAX_SRC_H 4096
5388 #define ICL_MAX_DST_W 5120
5389 #define ICL_MAX_DST_H 4096
5390 #define SKL_MIN_YUV_420_SRC_W 16
5391 #define SKL_MIN_YUV_420_SRC_H 16
5392
5393 static int
5394 skl_update_scaler(struct intel_crtc_state *crtc_state, bool force_detach,
5395                   unsigned int scaler_user, int *scaler_id,
5396                   int src_w, int src_h, int dst_w, int dst_h,
5397                   const struct drm_format_info *format, bool need_scaler)
5398 {
5399         struct intel_crtc_scaler_state *scaler_state =
5400                 &crtc_state->scaler_state;
5401         struct intel_crtc *intel_crtc =
5402                 to_intel_crtc(crtc_state->base.crtc);
5403         struct drm_i915_private *dev_priv = to_i915(intel_crtc->base.dev);
5404         const struct drm_display_mode *adjusted_mode =
5405                 &crtc_state->base.adjusted_mode;
5406
5407         /*
5408          * Src coordinates are already rotated by 270 degrees for
5409          * the 90/270 degree plane rotation cases (to match the
5410          * GTT mapping), hence no need to account for rotation here.
5411          */
5412         if (src_w != dst_w || src_h != dst_h)
5413                 need_scaler = true;
5414
5415         /*
5416          * Scaling/fitting not supported in IF-ID mode in GEN9+
5417          * TODO: Interlace fetch mode doesn't support YUV420 planar formats.
5418          * Once NV12 is enabled, handle it here while allocating scaler
5419          * for NV12.
5420          */
5421         if (INTEL_GEN(dev_priv) >= 9 && crtc_state->base.enable &&
5422             need_scaler && adjusted_mode->flags & DRM_MODE_FLAG_INTERLACE) {
5423                 DRM_DEBUG_KMS("Pipe/Plane scaling not supported with IF-ID mode\n");
5424                 return -EINVAL;
5425         }
5426
5427         /*
5428          * if plane is being disabled or scaler is no more required or force detach
5429          *  - free scaler binded to this plane/crtc
5430          *  - in order to do this, update crtc->scaler_usage
5431          *
5432          * Here scaler state in crtc_state is set free so that
5433          * scaler can be assigned to other user. Actual register
5434          * update to free the scaler is done in plane/panel-fit programming.
5435          * For this purpose crtc/plane_state->scaler_id isn't reset here.
5436          */
5437         if (force_detach || !need_scaler) {
5438                 if (*scaler_id >= 0) {
5439                         scaler_state->scaler_users &= ~(1 << scaler_user);
5440                         scaler_state->scalers[*scaler_id].in_use = 0;
5441
5442                         DRM_DEBUG_KMS("scaler_user index %u.%u: "
5443                                 "Staged freeing scaler id %d scaler_users = 0x%x\n",
5444                                 intel_crtc->pipe, scaler_user, *scaler_id,
5445                                 scaler_state->scaler_users);
5446                         *scaler_id = -1;
5447                 }
5448                 return 0;
5449         }
5450
5451         if (format && is_planar_yuv_format(format->format) &&
5452             (src_h < SKL_MIN_YUV_420_SRC_H || src_w < SKL_MIN_YUV_420_SRC_W)) {
5453                 DRM_DEBUG_KMS("Planar YUV: src dimensions not met\n");
5454                 return -EINVAL;
5455         }
5456
5457         /* range checks */
5458         if (src_w < SKL_MIN_SRC_W || src_h < SKL_MIN_SRC_H ||
5459             dst_w < SKL_MIN_DST_W || dst_h < SKL_MIN_DST_H ||
5460             (INTEL_GEN(dev_priv) >= 11 &&
5461              (src_w > ICL_MAX_SRC_W || src_h > ICL_MAX_SRC_H ||
5462               dst_w > ICL_MAX_DST_W || dst_h > ICL_MAX_DST_H)) ||
5463             (INTEL_GEN(dev_priv) < 11 &&
5464              (src_w > SKL_MAX_SRC_W || src_h > SKL_MAX_SRC_H ||
5465               dst_w > SKL_MAX_DST_W || dst_h > SKL_MAX_DST_H))) {
5466                 DRM_DEBUG_KMS("scaler_user index %u.%u: src %ux%u dst %ux%u "
5467                         "size is out of scaler range\n",
5468                         intel_crtc->pipe, scaler_user, src_w, src_h, dst_w, dst_h);
5469                 return -EINVAL;
5470         }
5471
5472         /* mark this plane as a scaler user in crtc_state */
5473         scaler_state->scaler_users |= (1 << scaler_user);
5474         DRM_DEBUG_KMS("scaler_user index %u.%u: "
5475                 "staged scaling request for %ux%u->%ux%u scaler_users = 0x%x\n",
5476                 intel_crtc->pipe, scaler_user, src_w, src_h, dst_w, dst_h,
5477                 scaler_state->scaler_users);
5478
5479         return 0;
5480 }
5481
5482 /**
5483  * skl_update_scaler_crtc - Stages update to scaler state for a given crtc.
5484  *
5485  * @state: crtc's scaler state
5486  *
5487  * Return
5488  *     0 - scaler_usage updated successfully
5489  *    error - requested scaling cannot be supported or other error condition
5490  */
5491 int skl_update_scaler_crtc(struct intel_crtc_state *state)
5492 {
5493         const struct drm_display_mode *adjusted_mode = &state->base.adjusted_mode;
5494         bool need_scaler = false;
5495
5496         if (state->output_format == INTEL_OUTPUT_FORMAT_YCBCR420)
5497                 need_scaler = true;
5498
5499         return skl_update_scaler(state, !state->base.active, SKL_CRTC_INDEX,
5500                                  &state->scaler_state.scaler_id,
5501                                  state->pipe_src_w, state->pipe_src_h,
5502                                  adjusted_mode->crtc_hdisplay,
5503                                  adjusted_mode->crtc_vdisplay, NULL, need_scaler);
5504 }
5505
5506 /**
5507  * skl_update_scaler_plane - Stages update to scaler state for a given plane.
5508  * @crtc_state: crtc's scaler state
5509  * @plane_state: atomic plane state to update
5510  *
5511  * Return
5512  *     0 - scaler_usage updated successfully
5513  *    error - requested scaling cannot be supported or other error condition
5514  */
5515 static int skl_update_scaler_plane(struct intel_crtc_state *crtc_state,
5516                                    struct intel_plane_state *plane_state)
5517 {
5518         struct intel_plane *intel_plane =
5519                 to_intel_plane(plane_state->base.plane);
5520         struct drm_i915_private *dev_priv = to_i915(intel_plane->base.dev);
5521         struct drm_framebuffer *fb = plane_state->base.fb;
5522         int ret;
5523         bool force_detach = !fb || !plane_state->base.visible;
5524         bool need_scaler = false;
5525
5526         /* Pre-gen11 and SDR planes always need a scaler for planar formats. */
5527         if (!icl_is_hdr_plane(dev_priv, intel_plane->id) &&
5528             fb && is_planar_yuv_format(fb->format->format))
5529                 need_scaler = true;
5530
5531         ret = skl_update_scaler(crtc_state, force_detach,
5532                                 drm_plane_index(&intel_plane->base),
5533                                 &plane_state->scaler_id,
5534                                 drm_rect_width(&plane_state->base.src) >> 16,
5535                                 drm_rect_height(&plane_state->base.src) >> 16,
5536                                 drm_rect_width(&plane_state->base.dst),
5537                                 drm_rect_height(&plane_state->base.dst),
5538                                 fb ? fb->format : NULL, need_scaler);
5539
5540         if (ret || plane_state->scaler_id < 0)
5541                 return ret;
5542
5543         /* check colorkey */
5544         if (plane_state->ckey.flags) {
5545                 DRM_DEBUG_KMS("[PLANE:%d:%s] scaling with color key not allowed",
5546                               intel_plane->base.base.id,
5547                               intel_plane->base.name);
5548                 return -EINVAL;
5549         }
5550
5551         /* Check src format */
5552         switch (fb->format->format) {
5553         case DRM_FORMAT_RGB565:
5554         case DRM_FORMAT_XBGR8888:
5555         case DRM_FORMAT_XRGB8888:
5556         case DRM_FORMAT_ABGR8888:
5557         case DRM_FORMAT_ARGB8888:
5558         case DRM_FORMAT_XRGB2101010:
5559         case DRM_FORMAT_XBGR2101010:
5560         case DRM_FORMAT_XBGR16161616F:
5561         case DRM_FORMAT_ABGR16161616F:
5562         case DRM_FORMAT_XRGB16161616F:
5563         case DRM_FORMAT_ARGB16161616F:
5564         case DRM_FORMAT_YUYV:
5565         case DRM_FORMAT_YVYU:
5566         case DRM_FORMAT_UYVY:
5567         case DRM_FORMAT_VYUY:
5568         case DRM_FORMAT_NV12:
5569         case DRM_FORMAT_P010:
5570         case DRM_FORMAT_P012:
5571         case DRM_FORMAT_P016:
5572         case DRM_FORMAT_Y210:
5573         case DRM_FORMAT_Y212:
5574         case DRM_FORMAT_Y216:
5575         case DRM_FORMAT_XVYU2101010:
5576         case DRM_FORMAT_XVYU12_16161616:
5577         case DRM_FORMAT_XVYU16161616:
5578                 break;
5579         default:
5580                 DRM_DEBUG_KMS("[PLANE:%d:%s] FB:%d unsupported scaling format 0x%x\n",
5581                               intel_plane->base.base.id, intel_plane->base.name,
5582                               fb->base.id, fb->format->format);
5583                 return -EINVAL;
5584         }
5585
5586         return 0;
5587 }
5588
5589 static void skylake_scaler_disable(struct intel_crtc *crtc)
5590 {
5591         int i;
5592
5593         for (i = 0; i < crtc->num_scalers; i++)
5594                 skl_detach_scaler(crtc, i);
5595 }
5596
5597 static void skylake_pfit_enable(const struct intel_crtc_state *crtc_state)
5598 {
5599         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
5600         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
5601         enum pipe pipe = crtc->pipe;
5602         const struct intel_crtc_scaler_state *scaler_state =
5603                 &crtc_state->scaler_state;
5604
5605         if (crtc_state->pch_pfit.enabled) {
5606                 u16 uv_rgb_hphase, uv_rgb_vphase;
5607                 int pfit_w, pfit_h, hscale, vscale;
5608                 int id;
5609
5610                 if (WARN_ON(crtc_state->scaler_state.scaler_id < 0))
5611                         return;
5612
5613                 pfit_w = (crtc_state->pch_pfit.size >> 16) & 0xFFFF;
5614                 pfit_h = crtc_state->pch_pfit.size & 0xFFFF;
5615
5616                 hscale = (crtc_state->pipe_src_w << 16) / pfit_w;
5617                 vscale = (crtc_state->pipe_src_h << 16) / pfit_h;
5618
5619                 uv_rgb_hphase = skl_scaler_calc_phase(1, hscale, false);
5620                 uv_rgb_vphase = skl_scaler_calc_phase(1, vscale, false);
5621
5622                 id = scaler_state->scaler_id;
5623                 I915_WRITE(SKL_PS_CTRL(pipe, id), PS_SCALER_EN |
5624                         PS_FILTER_MEDIUM | scaler_state->scalers[id].mode);
5625                 I915_WRITE_FW(SKL_PS_VPHASE(pipe, id),
5626                               PS_Y_PHASE(0) | PS_UV_RGB_PHASE(uv_rgb_vphase));
5627                 I915_WRITE_FW(SKL_PS_HPHASE(pipe, id),
5628                               PS_Y_PHASE(0) | PS_UV_RGB_PHASE(uv_rgb_hphase));
5629                 I915_WRITE(SKL_PS_WIN_POS(pipe, id), crtc_state->pch_pfit.pos);
5630                 I915_WRITE(SKL_PS_WIN_SZ(pipe, id), crtc_state->pch_pfit.size);
5631         }
5632 }
5633
5634 static void ironlake_pfit_enable(const struct intel_crtc_state *crtc_state)
5635 {
5636         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
5637         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
5638         enum pipe pipe = crtc->pipe;
5639
5640         if (crtc_state->pch_pfit.enabled) {
5641                 /* Force use of hard-coded filter coefficients
5642                  * as some pre-programmed values are broken,
5643                  * e.g. x201.
5644                  */
5645                 if (IS_IVYBRIDGE(dev_priv) || IS_HASWELL(dev_priv))
5646                         I915_WRITE(PF_CTL(pipe), PF_ENABLE | PF_FILTER_MED_3x3 |
5647                                                  PF_PIPE_SEL_IVB(pipe));
5648                 else
5649                         I915_WRITE(PF_CTL(pipe), PF_ENABLE | PF_FILTER_MED_3x3);
5650                 I915_WRITE(PF_WIN_POS(pipe), crtc_state->pch_pfit.pos);
5651                 I915_WRITE(PF_WIN_SZ(pipe), crtc_state->pch_pfit.size);
5652         }
5653 }
5654
5655 void hsw_enable_ips(const struct intel_crtc_state *crtc_state)
5656 {
5657         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
5658         struct drm_device *dev = crtc->base.dev;
5659         struct drm_i915_private *dev_priv = to_i915(dev);
5660
5661         if (!crtc_state->ips_enabled)
5662                 return;
5663
5664         /*
5665          * We can only enable IPS after we enable a plane and wait for a vblank
5666          * This function is called from post_plane_update, which is run after
5667          * a vblank wait.
5668          */
5669         WARN_ON(!(crtc_state->active_planes & ~BIT(PLANE_CURSOR)));
5670
5671         if (IS_BROADWELL(dev_priv)) {
5672                 WARN_ON(sandybridge_pcode_write(dev_priv, DISPLAY_IPS_CONTROL,
5673                                                 IPS_ENABLE | IPS_PCODE_CONTROL));
5674                 /* Quoting Art Runyan: "its not safe to expect any particular
5675                  * value in IPS_CTL bit 31 after enabling IPS through the
5676                  * mailbox." Moreover, the mailbox may return a bogus state,
5677                  * so we need to just enable it and continue on.
5678                  */
5679         } else {
5680                 I915_WRITE(IPS_CTL, IPS_ENABLE);
5681                 /* The bit only becomes 1 in the next vblank, so this wait here
5682                  * is essentially intel_wait_for_vblank. If we don't have this
5683                  * and don't wait for vblanks until the end of crtc_enable, then
5684                  * the HW state readout code will complain that the expected
5685                  * IPS_CTL value is not the one we read. */
5686                 if (intel_de_wait_for_set(dev_priv, IPS_CTL, IPS_ENABLE, 50))
5687                         DRM_ERROR("Timed out waiting for IPS enable\n");
5688         }
5689 }
5690
5691 void hsw_disable_ips(const struct intel_crtc_state *crtc_state)
5692 {
5693         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
5694         struct drm_device *dev = crtc->base.dev;
5695         struct drm_i915_private *dev_priv = to_i915(dev);
5696
5697         if (!crtc_state->ips_enabled)
5698                 return;
5699
5700         if (IS_BROADWELL(dev_priv)) {
5701                 WARN_ON(sandybridge_pcode_write(dev_priv, DISPLAY_IPS_CONTROL, 0));
5702                 /*
5703                  * Wait for PCODE to finish disabling IPS. The BSpec specified
5704                  * 42ms timeout value leads to occasional timeouts so use 100ms
5705                  * instead.
5706                  */
5707                 if (intel_de_wait_for_clear(dev_priv, IPS_CTL, IPS_ENABLE, 100))
5708                         DRM_ERROR("Timed out waiting for IPS disable\n");
5709         } else {
5710                 I915_WRITE(IPS_CTL, 0);
5711                 POSTING_READ(IPS_CTL);
5712         }
5713
5714         /* We need to wait for a vblank before we can disable the plane. */
5715         intel_wait_for_vblank(dev_priv, crtc->pipe);
5716 }
5717
5718 static void intel_crtc_dpms_overlay_disable(struct intel_crtc *intel_crtc)
5719 {
5720         if (intel_crtc->overlay) {
5721                 struct drm_device *dev = intel_crtc->base.dev;
5722
5723                 mutex_lock(&dev->struct_mutex);
5724                 (void) intel_overlay_switch_off(intel_crtc->overlay);
5725                 mutex_unlock(&dev->struct_mutex);
5726         }
5727
5728         /* Let userspace switch the overlay on again. In most cases userspace
5729          * has to recompute where to put it anyway.
5730          */
5731 }
5732
5733 /**
5734  * intel_post_enable_primary - Perform operations after enabling primary plane
5735  * @crtc: the CRTC whose primary plane was just enabled
5736  * @new_crtc_state: the enabling state
5737  *
5738  * Performs potentially sleeping operations that must be done after the primary
5739  * plane is enabled, such as updating FBC and IPS.  Note that this may be
5740  * called due to an explicit primary plane update, or due to an implicit
5741  * re-enable that is caused when a sprite plane is updated to no longer
5742  * completely hide the primary plane.
5743  */
5744 static void
5745 intel_post_enable_primary(struct drm_crtc *crtc,
5746                           const struct intel_crtc_state *new_crtc_state)
5747 {
5748         struct drm_device *dev = crtc->dev;
5749         struct drm_i915_private *dev_priv = to_i915(dev);
5750         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5751         enum pipe pipe = intel_crtc->pipe;
5752
5753         /*
5754          * Gen2 reports pipe underruns whenever all planes are disabled.
5755          * So don't enable underrun reporting before at least some planes
5756          * are enabled.
5757          * FIXME: Need to fix the logic to work when we turn off all planes
5758          * but leave the pipe running.
5759          */
5760         if (IS_GEN(dev_priv, 2))
5761                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
5762
5763         /* Underruns don't always raise interrupts, so check manually. */
5764         intel_check_cpu_fifo_underruns(dev_priv);
5765         intel_check_pch_fifo_underruns(dev_priv);
5766 }
5767
5768 /* FIXME get rid of this and use pre_plane_update */
5769 static void
5770 intel_pre_disable_primary_noatomic(struct drm_crtc *crtc)
5771 {
5772         struct drm_device *dev = crtc->dev;
5773         struct drm_i915_private *dev_priv = to_i915(dev);
5774         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5775         enum pipe pipe = intel_crtc->pipe;
5776
5777         /*
5778          * Gen2 reports pipe underruns whenever all planes are disabled.
5779          * So disable underrun reporting before all the planes get disabled.
5780          */
5781         if (IS_GEN(dev_priv, 2))
5782                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
5783
5784         hsw_disable_ips(to_intel_crtc_state(crtc->state));
5785
5786         /*
5787          * Vblank time updates from the shadow to live plane control register
5788          * are blocked if the memory self-refresh mode is active at that
5789          * moment. So to make sure the plane gets truly disabled, disable
5790          * first the self-refresh mode. The self-refresh enable bit in turn
5791          * will be checked/applied by the HW only at the next frame start
5792          * event which is after the vblank start event, so we need to have a
5793          * wait-for-vblank between disabling the plane and the pipe.
5794          */
5795         if (HAS_GMCH(dev_priv) &&
5796             intel_set_memory_cxsr(dev_priv, false))
5797                 intel_wait_for_vblank(dev_priv, pipe);
5798 }
5799
5800 static bool hsw_pre_update_disable_ips(const struct intel_crtc_state *old_crtc_state,
5801                                        const struct intel_crtc_state *new_crtc_state)
5802 {
5803         struct intel_crtc *crtc = to_intel_crtc(new_crtc_state->base.crtc);
5804         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
5805
5806         if (!old_crtc_state->ips_enabled)
5807                 return false;
5808
5809         if (needs_modeset(new_crtc_state))
5810                 return true;
5811
5812         /*
5813          * Workaround : Do not read or write the pipe palette/gamma data while
5814          * GAMMA_MODE is configured for split gamma and IPS_CTL has IPS enabled.
5815          *
5816          * Disable IPS before we program the LUT.
5817          */
5818         if (IS_HASWELL(dev_priv) &&
5819             (new_crtc_state->base.color_mgmt_changed ||
5820              new_crtc_state->update_pipe) &&
5821             new_crtc_state->gamma_mode == GAMMA_MODE_MODE_SPLIT)
5822                 return true;
5823
5824         return !new_crtc_state->ips_enabled;
5825 }
5826
5827 static bool hsw_post_update_enable_ips(const struct intel_crtc_state *old_crtc_state,
5828                                        const struct intel_crtc_state *new_crtc_state)
5829 {
5830         struct intel_crtc *crtc = to_intel_crtc(new_crtc_state->base.crtc);
5831         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
5832
5833         if (!new_crtc_state->ips_enabled)
5834                 return false;
5835
5836         if (needs_modeset(new_crtc_state))
5837                 return true;
5838
5839         /*
5840          * Workaround : Do not read or write the pipe palette/gamma data while
5841          * GAMMA_MODE is configured for split gamma and IPS_CTL has IPS enabled.
5842          *
5843          * Re-enable IPS after the LUT has been programmed.
5844          */
5845         if (IS_HASWELL(dev_priv) &&
5846             (new_crtc_state->base.color_mgmt_changed ||
5847              new_crtc_state->update_pipe) &&
5848             new_crtc_state->gamma_mode == GAMMA_MODE_MODE_SPLIT)
5849                 return true;
5850
5851         /*
5852          * We can't read out IPS on broadwell, assume the worst and
5853          * forcibly enable IPS on the first fastset.
5854          */
5855         if (new_crtc_state->update_pipe &&
5856             old_crtc_state->base.adjusted_mode.private_flags & I915_MODE_FLAG_INHERITED)
5857                 return true;
5858
5859         return !old_crtc_state->ips_enabled;
5860 }
5861
5862 static bool needs_nv12_wa(struct drm_i915_private *dev_priv,
5863                           const struct intel_crtc_state *crtc_state)
5864 {
5865         if (!crtc_state->nv12_planes)
5866                 return false;
5867
5868         /* WA Display #0827: Gen9:all */
5869         if (IS_GEN(dev_priv, 9) && !IS_GEMINILAKE(dev_priv))
5870                 return true;
5871
5872         return false;
5873 }
5874
5875 static bool needs_scalerclk_wa(struct drm_i915_private *dev_priv,
5876                                const struct intel_crtc_state *crtc_state)
5877 {
5878         /* Wa_2006604312:icl */
5879         if (crtc_state->scaler_state.scaler_users > 0 && IS_ICELAKE(dev_priv))
5880                 return true;
5881
5882         return false;
5883 }
5884
5885 static void intel_post_plane_update(struct intel_crtc_state *old_crtc_state)
5886 {
5887         struct intel_crtc *crtc = to_intel_crtc(old_crtc_state->base.crtc);
5888         struct drm_device *dev = crtc->base.dev;
5889         struct drm_i915_private *dev_priv = to_i915(dev);
5890         struct drm_atomic_state *state = old_crtc_state->base.state;
5891         struct intel_crtc_state *pipe_config =
5892                 intel_atomic_get_new_crtc_state(to_intel_atomic_state(state),
5893                                                 crtc);
5894         struct drm_plane *primary = crtc->base.primary;
5895         struct drm_plane_state *old_primary_state =
5896                 drm_atomic_get_old_plane_state(state, primary);
5897
5898         intel_frontbuffer_flip(to_i915(crtc->base.dev), pipe_config->fb_bits);
5899
5900         if (pipe_config->update_wm_post && pipe_config->base.active)
5901                 intel_update_watermarks(crtc);
5902
5903         if (hsw_post_update_enable_ips(old_crtc_state, pipe_config))
5904                 hsw_enable_ips(pipe_config);
5905
5906         if (old_primary_state) {
5907                 struct drm_plane_state *new_primary_state =
5908                         drm_atomic_get_new_plane_state(state, primary);
5909
5910                 intel_fbc_post_update(crtc);
5911
5912                 if (new_primary_state->visible &&
5913                     (needs_modeset(pipe_config) ||
5914                      !old_primary_state->visible))
5915                         intel_post_enable_primary(&crtc->base, pipe_config);
5916         }
5917
5918         if (needs_nv12_wa(dev_priv, old_crtc_state) &&
5919             !needs_nv12_wa(dev_priv, pipe_config))
5920                 skl_wa_827(dev_priv, crtc->pipe, false);
5921
5922         if (needs_scalerclk_wa(dev_priv, old_crtc_state) &&
5923             !needs_scalerclk_wa(dev_priv, pipe_config))
5924                 icl_wa_scalerclkgating(dev_priv, crtc->pipe, false);
5925 }
5926
5927 static void intel_pre_plane_update(struct intel_crtc_state *old_crtc_state,
5928                                    struct intel_crtc_state *pipe_config)
5929 {
5930         struct intel_crtc *crtc = to_intel_crtc(old_crtc_state->base.crtc);
5931         struct drm_device *dev = crtc->base.dev;
5932         struct drm_i915_private *dev_priv = to_i915(dev);
5933         struct drm_atomic_state *state = old_crtc_state->base.state;
5934         struct drm_plane *primary = crtc->base.primary;
5935         struct drm_plane_state *old_primary_state =
5936                 drm_atomic_get_old_plane_state(state, primary);
5937         bool modeset = needs_modeset(pipe_config);
5938         struct intel_atomic_state *intel_state =
5939                 to_intel_atomic_state(state);
5940
5941         if (hsw_pre_update_disable_ips(old_crtc_state, pipe_config))
5942                 hsw_disable_ips(old_crtc_state);
5943
5944         if (old_primary_state) {
5945                 struct intel_plane_state *new_primary_state =
5946                         intel_atomic_get_new_plane_state(intel_state,
5947                                                          to_intel_plane(primary));
5948
5949                 intel_fbc_pre_update(crtc, pipe_config, new_primary_state);
5950                 /*
5951                  * Gen2 reports pipe underruns whenever all planes are disabled.
5952                  * So disable underrun reporting before all the planes get disabled.
5953                  */
5954                 if (IS_GEN(dev_priv, 2) && old_primary_state->visible &&
5955                     (modeset || !new_primary_state->base.visible))
5956                         intel_set_cpu_fifo_underrun_reporting(dev_priv, crtc->pipe, false);
5957         }
5958
5959         /* Display WA 827 */
5960         if (!needs_nv12_wa(dev_priv, old_crtc_state) &&
5961             needs_nv12_wa(dev_priv, pipe_config))
5962                 skl_wa_827(dev_priv, crtc->pipe, true);
5963
5964         /* Wa_2006604312:icl */
5965         if (!needs_scalerclk_wa(dev_priv, old_crtc_state) &&
5966             needs_scalerclk_wa(dev_priv, pipe_config))
5967                 icl_wa_scalerclkgating(dev_priv, crtc->pipe, true);
5968
5969         /*
5970          * Vblank time updates from the shadow to live plane control register
5971          * are blocked if the memory self-refresh mode is active at that
5972          * moment. So to make sure the plane gets truly disabled, disable
5973          * first the self-refresh mode. The self-refresh enable bit in turn
5974          * will be checked/applied by the HW only at the next frame start
5975          * event which is after the vblank start event, so we need to have a
5976          * wait-for-vblank between disabling the plane and the pipe.
5977          */
5978         if (HAS_GMCH(dev_priv) && old_crtc_state->base.active &&
5979             pipe_config->disable_cxsr && intel_set_memory_cxsr(dev_priv, false))
5980                 intel_wait_for_vblank(dev_priv, crtc->pipe);
5981
5982         /*
5983          * IVB workaround: must disable low power watermarks for at least
5984          * one frame before enabling scaling.  LP watermarks can be re-enabled
5985          * when scaling is disabled.
5986          *
5987          * WaCxSRDisabledForSpriteScaling:ivb
5988          */
5989         if (pipe_config->disable_lp_wm && ilk_disable_lp_wm(dev) &&
5990             old_crtc_state->base.active)
5991                 intel_wait_for_vblank(dev_priv, crtc->pipe);
5992
5993         /*
5994          * If we're doing a modeset, we're done.  No need to do any pre-vblank
5995          * watermark programming here.
5996          */
5997         if (needs_modeset(pipe_config))
5998                 return;
5999
6000         /*
6001          * For platforms that support atomic watermarks, program the
6002          * 'intermediate' watermarks immediately.  On pre-gen9 platforms, these
6003          * will be the intermediate values that are safe for both pre- and
6004          * post- vblank; when vblank happens, the 'active' values will be set
6005          * to the final 'target' values and we'll do this again to get the
6006          * optimal watermarks.  For gen9+ platforms, the values we program here
6007          * will be the final target values which will get automatically latched
6008          * at vblank time; no further programming will be necessary.
6009          *
6010          * If a platform hasn't been transitioned to atomic watermarks yet,
6011          * we'll continue to update watermarks the old way, if flags tell
6012          * us to.
6013          */
6014         if (dev_priv->display.initial_watermarks != NULL)
6015                 dev_priv->display.initial_watermarks(intel_state,
6016                                                      pipe_config);
6017         else if (pipe_config->update_wm_pre)
6018                 intel_update_watermarks(crtc);
6019 }
6020
6021 static void intel_crtc_disable_planes(struct intel_atomic_state *state,
6022                                       struct intel_crtc *crtc)
6023 {
6024         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
6025         const struct intel_crtc_state *new_crtc_state =
6026                 intel_atomic_get_new_crtc_state(state, crtc);
6027         unsigned int update_mask = new_crtc_state->update_planes;
6028         const struct intel_plane_state *old_plane_state;
6029         struct intel_plane *plane;
6030         unsigned fb_bits = 0;
6031         int i;
6032
6033         intel_crtc_dpms_overlay_disable(crtc);
6034
6035         for_each_old_intel_plane_in_state(state, plane, old_plane_state, i) {
6036                 if (crtc->pipe != plane->pipe ||
6037                     !(update_mask & BIT(plane->id)))
6038                         continue;
6039
6040                 intel_disable_plane(plane, new_crtc_state);
6041
6042                 if (old_plane_state->base.visible)
6043                         fb_bits |= plane->frontbuffer_bit;
6044         }
6045
6046         intel_frontbuffer_flip(dev_priv, fb_bits);
6047 }
6048
6049 /*
6050  * intel_connector_primary_encoder - get the primary encoder for a connector
6051  * @connector: connector for which to return the encoder
6052  *
6053  * Returns the primary encoder for a connector. There is a 1:1 mapping from
6054  * all connectors to their encoder, except for DP-MST connectors which have
6055  * both a virtual and a primary encoder. These DP-MST primary encoders can be
6056  * pointed to by as many DP-MST connectors as there are pipes.
6057  */
6058 static struct intel_encoder *
6059 intel_connector_primary_encoder(struct intel_connector *connector)
6060 {
6061         struct intel_encoder *encoder;
6062
6063         if (connector->mst_port)
6064                 return &dp_to_dig_port(connector->mst_port)->base;
6065
6066         encoder = intel_attached_encoder(&connector->base);
6067         WARN_ON(!encoder);
6068
6069         return encoder;
6070 }
6071
6072 static bool
6073 intel_connector_needs_modeset(struct intel_atomic_state *state,
6074                               const struct drm_connector_state *old_conn_state,
6075                               const struct drm_connector_state *new_conn_state)
6076 {
6077         struct intel_crtc *old_crtc = old_conn_state->crtc ?
6078                                       to_intel_crtc(old_conn_state->crtc) : NULL;
6079         struct intel_crtc *new_crtc = new_conn_state->crtc ?
6080                                       to_intel_crtc(new_conn_state->crtc) : NULL;
6081
6082         return new_crtc != old_crtc ||
6083                (new_crtc &&
6084                 needs_modeset(intel_atomic_get_new_crtc_state(state, new_crtc)));
6085 }
6086
6087 static void intel_encoders_update_prepare(struct intel_atomic_state *state)
6088 {
6089         struct drm_connector_state *old_conn_state;
6090         struct drm_connector_state *new_conn_state;
6091         struct drm_connector *conn;
6092         int i;
6093
6094         for_each_oldnew_connector_in_state(&state->base, conn,
6095                                            old_conn_state, new_conn_state, i) {
6096                 struct intel_encoder *encoder;
6097                 struct intel_crtc *crtc;
6098
6099                 if (!intel_connector_needs_modeset(state,
6100                                                    old_conn_state,
6101                                                    new_conn_state))
6102                         continue;
6103
6104                 encoder = intel_connector_primary_encoder(to_intel_connector(conn));
6105                 if (!encoder->update_prepare)
6106                         continue;
6107
6108                 crtc = new_conn_state->crtc ?
6109                         to_intel_crtc(new_conn_state->crtc) : NULL;
6110                 encoder->update_prepare(state, encoder, crtc);
6111         }
6112 }
6113
6114 static void intel_encoders_update_complete(struct intel_atomic_state *state)
6115 {
6116         struct drm_connector_state *old_conn_state;
6117         struct drm_connector_state *new_conn_state;
6118         struct drm_connector *conn;
6119         int i;
6120
6121         for_each_oldnew_connector_in_state(&state->base, conn,
6122                                            old_conn_state, new_conn_state, i) {
6123                 struct intel_encoder *encoder;
6124                 struct intel_crtc *crtc;
6125
6126                 if (!intel_connector_needs_modeset(state,
6127                                                    old_conn_state,
6128                                                    new_conn_state))
6129                         continue;
6130
6131                 encoder = intel_connector_primary_encoder(to_intel_connector(conn));
6132                 if (!encoder->update_complete)
6133                         continue;
6134
6135                 crtc = new_conn_state->crtc ?
6136                         to_intel_crtc(new_conn_state->crtc) : NULL;
6137                 encoder->update_complete(state, encoder, crtc);
6138         }
6139 }
6140
6141 static void intel_encoders_pre_pll_enable(struct intel_crtc *crtc,
6142                                           struct intel_crtc_state *crtc_state,
6143                                           struct intel_atomic_state *state)
6144 {
6145         struct drm_connector_state *conn_state;
6146         struct drm_connector *conn;
6147         int i;
6148
6149         for_each_new_connector_in_state(&state->base, conn, conn_state, i) {
6150                 struct intel_encoder *encoder =
6151                         to_intel_encoder(conn_state->best_encoder);
6152
6153                 if (conn_state->crtc != &crtc->base)
6154                         continue;
6155
6156                 if (encoder->pre_pll_enable)
6157                         encoder->pre_pll_enable(encoder, crtc_state, conn_state);
6158         }
6159 }
6160
6161 static void intel_encoders_pre_enable(struct intel_crtc *crtc,
6162                                       struct intel_crtc_state *crtc_state,
6163                                       struct intel_atomic_state *state)
6164 {
6165         struct drm_connector_state *conn_state;
6166         struct drm_connector *conn;
6167         int i;
6168
6169         for_each_new_connector_in_state(&state->base, conn, conn_state, i) {
6170                 struct intel_encoder *encoder =
6171                         to_intel_encoder(conn_state->best_encoder);
6172
6173                 if (conn_state->crtc != &crtc->base)
6174                         continue;
6175
6176                 if (encoder->pre_enable)
6177                         encoder->pre_enable(encoder, crtc_state, conn_state);
6178         }
6179 }
6180
6181 static void intel_encoders_enable(struct intel_crtc *crtc,
6182                                   struct intel_crtc_state *crtc_state,
6183                                   struct intel_atomic_state *state)
6184 {
6185         struct drm_connector_state *conn_state;
6186         struct drm_connector *conn;
6187         int i;
6188
6189         for_each_new_connector_in_state(&state->base, conn, conn_state, i) {
6190                 struct intel_encoder *encoder =
6191                         to_intel_encoder(conn_state->best_encoder);
6192
6193                 if (conn_state->crtc != &crtc->base)
6194                         continue;
6195
6196                 if (encoder->enable)
6197                         encoder->enable(encoder, crtc_state, conn_state);
6198                 intel_opregion_notify_encoder(encoder, true);
6199         }
6200 }
6201
6202 static void intel_encoders_disable(struct intel_crtc *crtc,
6203                                    struct intel_crtc_state *old_crtc_state,
6204                                    struct intel_atomic_state *state)
6205 {
6206         struct drm_connector_state *old_conn_state;
6207         struct drm_connector *conn;
6208         int i;
6209
6210         for_each_old_connector_in_state(&state->base, conn, old_conn_state, i) {
6211                 struct intel_encoder *encoder =
6212                         to_intel_encoder(old_conn_state->best_encoder);
6213
6214                 if (old_conn_state->crtc != &crtc->base)
6215                         continue;
6216
6217                 intel_opregion_notify_encoder(encoder, false);
6218                 if (encoder->disable)
6219                         encoder->disable(encoder, old_crtc_state, old_conn_state);
6220         }
6221 }
6222
6223 static void intel_encoders_post_disable(struct intel_crtc *crtc,
6224                                         struct intel_crtc_state *old_crtc_state,
6225                                         struct intel_atomic_state *state)
6226 {
6227         struct drm_connector_state *old_conn_state;
6228         struct drm_connector *conn;
6229         int i;
6230
6231         for_each_old_connector_in_state(&state->base, conn, old_conn_state, i) {
6232                 struct intel_encoder *encoder =
6233                         to_intel_encoder(old_conn_state->best_encoder);
6234
6235                 if (old_conn_state->crtc != &crtc->base)
6236                         continue;
6237
6238                 if (encoder->post_disable)
6239                         encoder->post_disable(encoder, old_crtc_state, old_conn_state);
6240         }
6241 }
6242
6243 static void intel_encoders_post_pll_disable(struct intel_crtc *crtc,
6244                                             struct intel_crtc_state *old_crtc_state,
6245                                             struct intel_atomic_state *state)
6246 {
6247         struct drm_connector_state *old_conn_state;
6248         struct drm_connector *conn;
6249         int i;
6250
6251         for_each_old_connector_in_state(&state->base, conn, old_conn_state, i) {
6252                 struct intel_encoder *encoder =
6253                         to_intel_encoder(old_conn_state->best_encoder);
6254
6255                 if (old_conn_state->crtc != &crtc->base)
6256                         continue;
6257
6258                 if (encoder->post_pll_disable)
6259                         encoder->post_pll_disable(encoder, old_crtc_state, old_conn_state);
6260         }
6261 }
6262
6263 static void intel_encoders_update_pipe(struct intel_crtc *crtc,
6264                                        struct intel_crtc_state *crtc_state,
6265                                        struct intel_atomic_state *state)
6266 {
6267         struct drm_connector_state *conn_state;
6268         struct drm_connector *conn;
6269         int i;
6270
6271         for_each_new_connector_in_state(&state->base, conn, conn_state, i) {
6272                 struct intel_encoder *encoder =
6273                         to_intel_encoder(conn_state->best_encoder);
6274
6275                 if (conn_state->crtc != &crtc->base)
6276                         continue;
6277
6278                 if (encoder->update_pipe)
6279                         encoder->update_pipe(encoder, crtc_state, conn_state);
6280         }
6281 }
6282
6283 static void intel_disable_primary_plane(const struct intel_crtc_state *crtc_state)
6284 {
6285         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
6286         struct intel_plane *plane = to_intel_plane(crtc->base.primary);
6287
6288         plane->disable_plane(plane, crtc_state);
6289 }
6290
6291 static void ironlake_crtc_enable(struct intel_crtc_state *pipe_config,
6292                                  struct intel_atomic_state *state)
6293 {
6294         struct drm_crtc *crtc = pipe_config->base.crtc;
6295         struct drm_device *dev = crtc->dev;
6296         struct drm_i915_private *dev_priv = to_i915(dev);
6297         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
6298         enum pipe pipe = intel_crtc->pipe;
6299
6300         if (WARN_ON(intel_crtc->active))
6301                 return;
6302
6303         /*
6304          * Sometimes spurious CPU pipe underruns happen during FDI
6305          * training, at least with VGA+HDMI cloning. Suppress them.
6306          *
6307          * On ILK we get an occasional spurious CPU pipe underruns
6308          * between eDP port A enable and vdd enable. Also PCH port
6309          * enable seems to result in the occasional CPU pipe underrun.
6310          *
6311          * Spurious PCH underruns also occur during PCH enabling.
6312          */
6313         intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
6314         intel_set_pch_fifo_underrun_reporting(dev_priv, pipe, false);
6315
6316         if (pipe_config->has_pch_encoder)
6317                 intel_prepare_shared_dpll(pipe_config);
6318
6319         if (intel_crtc_has_dp_encoder(pipe_config))
6320                 intel_dp_set_m_n(pipe_config, M1_N1);
6321
6322         intel_set_pipe_timings(pipe_config);
6323         intel_set_pipe_src_size(pipe_config);
6324
6325         if (pipe_config->has_pch_encoder) {
6326                 intel_cpu_transcoder_set_m_n(pipe_config,
6327                                              &pipe_config->fdi_m_n, NULL);
6328         }
6329
6330         ironlake_set_pipeconf(pipe_config);
6331
6332         intel_crtc->active = true;
6333
6334         intel_encoders_pre_enable(intel_crtc, pipe_config, state);
6335
6336         if (pipe_config->has_pch_encoder) {
6337                 /* Note: FDI PLL enabling _must_ be done before we enable the
6338                  * cpu pipes, hence this is separate from all the other fdi/pch
6339                  * enabling. */
6340                 ironlake_fdi_pll_enable(pipe_config);
6341         } else {
6342                 assert_fdi_tx_disabled(dev_priv, pipe);
6343                 assert_fdi_rx_disabled(dev_priv, pipe);
6344         }
6345
6346         ironlake_pfit_enable(pipe_config);
6347
6348         /*
6349          * On ILK+ LUT must be loaded before the pipe is running but with
6350          * clocks enabled
6351          */
6352         intel_color_load_luts(pipe_config);
6353         intel_color_commit(pipe_config);
6354         /* update DSPCNTR to configure gamma for pipe bottom color */
6355         intel_disable_primary_plane(pipe_config);
6356
6357         if (dev_priv->display.initial_watermarks != NULL)
6358                 dev_priv->display.initial_watermarks(state, pipe_config);
6359         intel_enable_pipe(pipe_config);
6360
6361         if (pipe_config->has_pch_encoder)
6362                 ironlake_pch_enable(state, pipe_config);
6363
6364         assert_vblank_disabled(crtc);
6365         intel_crtc_vblank_on(pipe_config);
6366
6367         intel_encoders_enable(intel_crtc, pipe_config, state);
6368
6369         if (HAS_PCH_CPT(dev_priv))
6370                 cpt_verify_modeset(dev, intel_crtc->pipe);
6371
6372         /*
6373          * Must wait for vblank to avoid spurious PCH FIFO underruns.
6374          * And a second vblank wait is needed at least on ILK with
6375          * some interlaced HDMI modes. Let's do the double wait always
6376          * in case there are more corner cases we don't know about.
6377          */
6378         if (pipe_config->has_pch_encoder) {
6379                 intel_wait_for_vblank(dev_priv, pipe);
6380                 intel_wait_for_vblank(dev_priv, pipe);
6381         }
6382         intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
6383         intel_set_pch_fifo_underrun_reporting(dev_priv, pipe, true);
6384 }
6385
6386 /* IPS only exists on ULT machines and is tied to pipe A. */
6387 static bool hsw_crtc_supports_ips(struct intel_crtc *crtc)
6388 {
6389         return HAS_IPS(to_i915(crtc->base.dev)) && crtc->pipe == PIPE_A;
6390 }
6391
6392 static void glk_pipe_scaler_clock_gating_wa(struct drm_i915_private *dev_priv,
6393                                             enum pipe pipe, bool apply)
6394 {
6395         u32 val = I915_READ(CLKGATE_DIS_PSL(pipe));
6396         u32 mask = DPF_GATING_DIS | DPF_RAM_GATING_DIS | DPFR_GATING_DIS;
6397
6398         if (apply)
6399                 val |= mask;
6400         else
6401                 val &= ~mask;
6402
6403         I915_WRITE(CLKGATE_DIS_PSL(pipe), val);
6404 }
6405
6406 static void icl_pipe_mbus_enable(struct intel_crtc *crtc)
6407 {
6408         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
6409         enum pipe pipe = crtc->pipe;
6410         u32 val;
6411
6412         val = MBUS_DBOX_A_CREDIT(2);
6413
6414         if (INTEL_GEN(dev_priv) >= 12) {
6415                 val |= MBUS_DBOX_BW_CREDIT(2);
6416                 val |= MBUS_DBOX_B_CREDIT(12);
6417         } else {
6418                 val |= MBUS_DBOX_BW_CREDIT(1);
6419                 val |= MBUS_DBOX_B_CREDIT(8);
6420         }
6421
6422         I915_WRITE(PIPE_MBUS_DBOX_CTL(pipe), val);
6423 }
6424
6425 static void haswell_crtc_enable(struct intel_crtc_state *pipe_config,
6426                                 struct intel_atomic_state *state)
6427 {
6428         struct drm_crtc *crtc = pipe_config->base.crtc;
6429         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
6430         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
6431         enum pipe pipe = intel_crtc->pipe, hsw_workaround_pipe;
6432         enum transcoder cpu_transcoder = pipe_config->cpu_transcoder;
6433         bool psl_clkgate_wa;
6434
6435         if (WARN_ON(intel_crtc->active))
6436                 return;
6437
6438         intel_encoders_pre_pll_enable(intel_crtc, pipe_config, state);
6439
6440         if (pipe_config->shared_dpll)
6441                 intel_enable_shared_dpll(pipe_config);
6442
6443         intel_encoders_pre_enable(intel_crtc, pipe_config, state);
6444
6445         if (intel_crtc_has_dp_encoder(pipe_config))
6446                 intel_dp_set_m_n(pipe_config, M1_N1);
6447
6448         if (!transcoder_is_dsi(cpu_transcoder))
6449                 intel_set_pipe_timings(pipe_config);
6450
6451         intel_set_pipe_src_size(pipe_config);
6452
6453         if (cpu_transcoder != TRANSCODER_EDP &&
6454             !transcoder_is_dsi(cpu_transcoder)) {
6455                 I915_WRITE(PIPE_MULT(cpu_transcoder),
6456                            pipe_config->pixel_multiplier - 1);
6457         }
6458
6459         if (pipe_config->has_pch_encoder) {
6460                 intel_cpu_transcoder_set_m_n(pipe_config,
6461                                              &pipe_config->fdi_m_n, NULL);
6462         }
6463
6464         if (!transcoder_is_dsi(cpu_transcoder))
6465                 haswell_set_pipeconf(pipe_config);
6466
6467         if (INTEL_GEN(dev_priv) >= 9 || IS_BROADWELL(dev_priv))
6468                 bdw_set_pipemisc(pipe_config);
6469
6470         intel_crtc->active = true;
6471
6472         /* Display WA #1180: WaDisableScalarClockGating: glk, cnl */
6473         psl_clkgate_wa = (IS_GEMINILAKE(dev_priv) || IS_CANNONLAKE(dev_priv)) &&
6474                          pipe_config->pch_pfit.enabled;
6475         if (psl_clkgate_wa)
6476                 glk_pipe_scaler_clock_gating_wa(dev_priv, pipe, true);
6477
6478         if (INTEL_GEN(dev_priv) >= 9)
6479                 skylake_pfit_enable(pipe_config);
6480         else
6481                 ironlake_pfit_enable(pipe_config);
6482
6483         /*
6484          * On ILK+ LUT must be loaded before the pipe is running but with
6485          * clocks enabled
6486          */
6487         intel_color_load_luts(pipe_config);
6488         intel_color_commit(pipe_config);
6489         /* update DSPCNTR to configure gamma/csc for pipe bottom color */
6490         if (INTEL_GEN(dev_priv) < 9)
6491                 intel_disable_primary_plane(pipe_config);
6492
6493         if (INTEL_GEN(dev_priv) >= 11)
6494                 icl_set_pipe_chicken(intel_crtc);
6495
6496         intel_ddi_set_pipe_settings(pipe_config);
6497         if (!transcoder_is_dsi(cpu_transcoder))
6498                 intel_ddi_enable_transcoder_func(pipe_config);
6499
6500         if (dev_priv->display.initial_watermarks != NULL)
6501                 dev_priv->display.initial_watermarks(state, pipe_config);
6502
6503         if (INTEL_GEN(dev_priv) >= 11)
6504                 icl_pipe_mbus_enable(intel_crtc);
6505
6506         /* XXX: Do the pipe assertions at the right place for BXT DSI. */
6507         if (!transcoder_is_dsi(cpu_transcoder))
6508                 intel_enable_pipe(pipe_config);
6509
6510         if (pipe_config->has_pch_encoder)
6511                 lpt_pch_enable(state, pipe_config);
6512
6513         if (intel_crtc_has_type(pipe_config, INTEL_OUTPUT_DP_MST))
6514                 intel_ddi_set_vc_payload_alloc(pipe_config, true);
6515
6516         assert_vblank_disabled(crtc);
6517         intel_crtc_vblank_on(pipe_config);
6518
6519         intel_encoders_enable(intel_crtc, pipe_config, state);
6520
6521         if (psl_clkgate_wa) {
6522                 intel_wait_for_vblank(dev_priv, pipe);
6523                 glk_pipe_scaler_clock_gating_wa(dev_priv, pipe, false);
6524         }
6525
6526         /* If we change the relative order between pipe/planes enabling, we need
6527          * to change the workaround. */
6528         hsw_workaround_pipe = pipe_config->hsw_workaround_pipe;
6529         if (IS_HASWELL(dev_priv) && hsw_workaround_pipe != INVALID_PIPE) {
6530                 intel_wait_for_vblank(dev_priv, hsw_workaround_pipe);
6531                 intel_wait_for_vblank(dev_priv, hsw_workaround_pipe);
6532         }
6533 }
6534
6535 static void ironlake_pfit_disable(const struct intel_crtc_state *old_crtc_state)
6536 {
6537         struct intel_crtc *crtc = to_intel_crtc(old_crtc_state->base.crtc);
6538         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
6539         enum pipe pipe = crtc->pipe;
6540
6541         /* To avoid upsetting the power well on haswell only disable the pfit if
6542          * it's in use. The hw state code will make sure we get this right. */
6543         if (old_crtc_state->pch_pfit.enabled) {
6544                 I915_WRITE(PF_CTL(pipe), 0);
6545                 I915_WRITE(PF_WIN_POS(pipe), 0);
6546                 I915_WRITE(PF_WIN_SZ(pipe), 0);
6547         }
6548 }
6549
6550 static void ironlake_crtc_disable(struct intel_crtc_state *old_crtc_state,
6551                                   struct intel_atomic_state *state)
6552 {
6553         struct drm_crtc *crtc = old_crtc_state->base.crtc;
6554         struct drm_device *dev = crtc->dev;
6555         struct drm_i915_private *dev_priv = to_i915(dev);
6556         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
6557         enum pipe pipe = intel_crtc->pipe;
6558
6559         /*
6560          * Sometimes spurious CPU pipe underruns happen when the
6561          * pipe is already disabled, but FDI RX/TX is still enabled.
6562          * Happens at least with VGA+HDMI cloning. Suppress them.
6563          */
6564         intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
6565         intel_set_pch_fifo_underrun_reporting(dev_priv, pipe, false);
6566
6567         intel_encoders_disable(intel_crtc, old_crtc_state, state);
6568
6569         drm_crtc_vblank_off(crtc);
6570         assert_vblank_disabled(crtc);
6571
6572         intel_disable_pipe(old_crtc_state);
6573
6574         ironlake_pfit_disable(old_crtc_state);
6575
6576         if (old_crtc_state->has_pch_encoder)
6577                 ironlake_fdi_disable(crtc);
6578
6579         intel_encoders_post_disable(intel_crtc, old_crtc_state, state);
6580
6581         if (old_crtc_state->has_pch_encoder) {
6582                 ironlake_disable_pch_transcoder(dev_priv, pipe);
6583
6584                 if (HAS_PCH_CPT(dev_priv)) {
6585                         i915_reg_t reg;
6586                         u32 temp;
6587
6588                         /* disable TRANS_DP_CTL */
6589                         reg = TRANS_DP_CTL(pipe);
6590                         temp = I915_READ(reg);
6591                         temp &= ~(TRANS_DP_OUTPUT_ENABLE |
6592                                   TRANS_DP_PORT_SEL_MASK);
6593                         temp |= TRANS_DP_PORT_SEL_NONE;
6594                         I915_WRITE(reg, temp);
6595
6596                         /* disable DPLL_SEL */
6597                         temp = I915_READ(PCH_DPLL_SEL);
6598                         temp &= ~(TRANS_DPLL_ENABLE(pipe) | TRANS_DPLLB_SEL(pipe));
6599                         I915_WRITE(PCH_DPLL_SEL, temp);
6600                 }
6601
6602                 ironlake_fdi_pll_disable(intel_crtc);
6603         }
6604
6605         intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
6606         intel_set_pch_fifo_underrun_reporting(dev_priv, pipe, true);
6607 }
6608
6609 static void haswell_crtc_disable(struct intel_crtc_state *old_crtc_state,
6610                                  struct intel_atomic_state *state)
6611 {
6612         struct drm_crtc *crtc = old_crtc_state->base.crtc;
6613         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
6614         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
6615         enum transcoder cpu_transcoder = old_crtc_state->cpu_transcoder;
6616
6617         intel_encoders_disable(intel_crtc, old_crtc_state, state);
6618
6619         drm_crtc_vblank_off(crtc);
6620         assert_vblank_disabled(crtc);
6621
6622         /* XXX: Do the pipe assertions at the right place for BXT DSI. */
6623         if (!transcoder_is_dsi(cpu_transcoder))
6624                 intel_disable_pipe(old_crtc_state);
6625
6626         if (intel_crtc_has_type(old_crtc_state, INTEL_OUTPUT_DP_MST))
6627                 intel_ddi_set_vc_payload_alloc(old_crtc_state, false);
6628
6629         if (!transcoder_is_dsi(cpu_transcoder))
6630                 intel_ddi_disable_transcoder_func(old_crtc_state);
6631
6632         intel_dsc_disable(old_crtc_state);
6633
6634         if (INTEL_GEN(dev_priv) >= 9)
6635                 skylake_scaler_disable(intel_crtc);
6636         else
6637                 ironlake_pfit_disable(old_crtc_state);
6638
6639         intel_encoders_post_disable(intel_crtc, old_crtc_state, state);
6640
6641         intel_encoders_post_pll_disable(intel_crtc, old_crtc_state, state);
6642 }
6643
6644 static void i9xx_pfit_enable(const struct intel_crtc_state *crtc_state)
6645 {
6646         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
6647         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
6648
6649         if (!crtc_state->gmch_pfit.control)
6650                 return;
6651
6652         /*
6653          * The panel fitter should only be adjusted whilst the pipe is disabled,
6654          * according to register description and PRM.
6655          */
6656         WARN_ON(I915_READ(PFIT_CONTROL) & PFIT_ENABLE);
6657         assert_pipe_disabled(dev_priv, crtc->pipe);
6658
6659         I915_WRITE(PFIT_PGM_RATIOS, crtc_state->gmch_pfit.pgm_ratios);
6660         I915_WRITE(PFIT_CONTROL, crtc_state->gmch_pfit.control);
6661
6662         /* Border color in case we don't scale up to the full screen. Black by
6663          * default, change to something else for debugging. */
6664         I915_WRITE(BCLRPAT(crtc->pipe), 0);
6665 }
6666
6667 bool intel_phy_is_combo(struct drm_i915_private *dev_priv, enum phy phy)
6668 {
6669         if (phy == PHY_NONE)
6670                 return false;
6671
6672         if (IS_ELKHARTLAKE(dev_priv))
6673                 return phy <= PHY_C;
6674
6675         if (INTEL_GEN(dev_priv) >= 11)
6676                 return phy <= PHY_B;
6677
6678         return false;
6679 }
6680
6681 bool intel_phy_is_tc(struct drm_i915_private *dev_priv, enum phy phy)
6682 {
6683         if (INTEL_GEN(dev_priv) >= 12)
6684                 return phy >= PHY_D && phy <= PHY_I;
6685
6686         if (INTEL_GEN(dev_priv) >= 11 && !IS_ELKHARTLAKE(dev_priv))
6687                 return phy >= PHY_C && phy <= PHY_F;
6688
6689         return false;
6690 }
6691
6692 enum phy intel_port_to_phy(struct drm_i915_private *i915, enum port port)
6693 {
6694         if (IS_ELKHARTLAKE(i915) && port == PORT_D)
6695                 return PHY_A;
6696
6697         return (enum phy)port;
6698 }
6699
6700 enum tc_port intel_port_to_tc(struct drm_i915_private *dev_priv, enum port port)
6701 {
6702         if (!intel_phy_is_tc(dev_priv, intel_port_to_phy(dev_priv, port)))
6703                 return PORT_TC_NONE;
6704
6705         if (INTEL_GEN(dev_priv) >= 12)
6706                 return port - PORT_D;
6707
6708         return port - PORT_C;
6709 }
6710
6711 enum intel_display_power_domain intel_port_to_power_domain(enum port port)
6712 {
6713         switch (port) {
6714         case PORT_A:
6715                 return POWER_DOMAIN_PORT_DDI_A_LANES;
6716         case PORT_B:
6717                 return POWER_DOMAIN_PORT_DDI_B_LANES;
6718         case PORT_C:
6719                 return POWER_DOMAIN_PORT_DDI_C_LANES;
6720         case PORT_D:
6721                 return POWER_DOMAIN_PORT_DDI_D_LANES;
6722         case PORT_E:
6723                 return POWER_DOMAIN_PORT_DDI_E_LANES;
6724         case PORT_F:
6725                 return POWER_DOMAIN_PORT_DDI_F_LANES;
6726         default:
6727                 MISSING_CASE(port);
6728                 return POWER_DOMAIN_PORT_OTHER;
6729         }
6730 }
6731
6732 enum intel_display_power_domain
6733 intel_aux_power_domain(struct intel_digital_port *dig_port)
6734 {
6735         struct drm_i915_private *dev_priv = to_i915(dig_port->base.base.dev);
6736         enum phy phy = intel_port_to_phy(dev_priv, dig_port->base.port);
6737
6738         if (intel_phy_is_tc(dev_priv, phy) &&
6739             dig_port->tc_mode == TC_PORT_TBT_ALT) {
6740                 switch (dig_port->aux_ch) {
6741                 case AUX_CH_C:
6742                         return POWER_DOMAIN_AUX_C_TBT;
6743                 case AUX_CH_D:
6744                         return POWER_DOMAIN_AUX_D_TBT;
6745                 case AUX_CH_E:
6746                         return POWER_DOMAIN_AUX_E_TBT;
6747                 case AUX_CH_F:
6748                         return POWER_DOMAIN_AUX_F_TBT;
6749                 default:
6750                         MISSING_CASE(dig_port->aux_ch);
6751                         return POWER_DOMAIN_AUX_C_TBT;
6752                 }
6753         }
6754
6755         switch (dig_port->aux_ch) {
6756         case AUX_CH_A:
6757                 return POWER_DOMAIN_AUX_A;
6758         case AUX_CH_B:
6759                 return POWER_DOMAIN_AUX_B;
6760         case AUX_CH_C:
6761                 return POWER_DOMAIN_AUX_C;
6762         case AUX_CH_D:
6763                 return POWER_DOMAIN_AUX_D;
6764         case AUX_CH_E:
6765                 return POWER_DOMAIN_AUX_E;
6766         case AUX_CH_F:
6767                 return POWER_DOMAIN_AUX_F;
6768         default:
6769                 MISSING_CASE(dig_port->aux_ch);
6770                 return POWER_DOMAIN_AUX_A;
6771         }
6772 }
6773
6774 static u64 get_crtc_power_domains(struct intel_crtc_state *crtc_state)
6775 {
6776         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
6777         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
6778         struct drm_encoder *encoder;
6779         enum pipe pipe = crtc->pipe;
6780         u64 mask;
6781         enum transcoder transcoder = crtc_state->cpu_transcoder;
6782
6783         if (!crtc_state->base.active)
6784                 return 0;
6785
6786         mask = BIT_ULL(POWER_DOMAIN_PIPE(pipe));
6787         mask |= BIT_ULL(POWER_DOMAIN_TRANSCODER(transcoder));
6788         if (crtc_state->pch_pfit.enabled ||
6789             crtc_state->pch_pfit.force_thru)
6790                 mask |= BIT_ULL(POWER_DOMAIN_PIPE_PANEL_FITTER(pipe));
6791
6792         drm_for_each_encoder_mask(encoder, &dev_priv->drm,
6793                                   crtc_state->base.encoder_mask) {
6794                 struct intel_encoder *intel_encoder = to_intel_encoder(encoder);
6795
6796                 mask |= BIT_ULL(intel_encoder->power_domain);
6797         }
6798
6799         if (HAS_DDI(dev_priv) && crtc_state->has_audio)
6800                 mask |= BIT_ULL(POWER_DOMAIN_AUDIO);
6801
6802         if (crtc_state->shared_dpll)
6803                 mask |= BIT_ULL(POWER_DOMAIN_DISPLAY_CORE);
6804
6805         return mask;
6806 }
6807
6808 static u64
6809 modeset_get_crtc_power_domains(struct intel_crtc_state *crtc_state)
6810 {
6811         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
6812         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
6813         enum intel_display_power_domain domain;
6814         u64 domains, new_domains, old_domains;
6815
6816         old_domains = crtc->enabled_power_domains;
6817         crtc->enabled_power_domains = new_domains =
6818                 get_crtc_power_domains(crtc_state);
6819
6820         domains = new_domains & ~old_domains;
6821
6822         for_each_power_domain(domain, domains)
6823                 intel_display_power_get(dev_priv, domain);
6824
6825         return old_domains & ~new_domains;
6826 }
6827
6828 static void modeset_put_power_domains(struct drm_i915_private *dev_priv,
6829                                       u64 domains)
6830 {
6831         enum intel_display_power_domain domain;
6832
6833         for_each_power_domain(domain, domains)
6834                 intel_display_power_put_unchecked(dev_priv, domain);
6835 }
6836
6837 static void valleyview_crtc_enable(struct intel_crtc_state *pipe_config,
6838                                    struct intel_atomic_state *state)
6839 {
6840         struct drm_crtc *crtc = pipe_config->base.crtc;
6841         struct drm_device *dev = crtc->dev;
6842         struct drm_i915_private *dev_priv = to_i915(dev);
6843         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
6844         enum pipe pipe = intel_crtc->pipe;
6845
6846         if (WARN_ON(intel_crtc->active))
6847                 return;
6848
6849         if (intel_crtc_has_dp_encoder(pipe_config))
6850                 intel_dp_set_m_n(pipe_config, M1_N1);
6851
6852         intel_set_pipe_timings(pipe_config);
6853         intel_set_pipe_src_size(pipe_config);
6854
6855         if (IS_CHERRYVIEW(dev_priv) && pipe == PIPE_B) {
6856                 I915_WRITE(CHV_BLEND(pipe), CHV_BLEND_LEGACY);
6857                 I915_WRITE(CHV_CANVAS(pipe), 0);
6858         }
6859
6860         i9xx_set_pipeconf(pipe_config);
6861
6862         intel_crtc->active = true;
6863
6864         intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
6865
6866         intel_encoders_pre_pll_enable(intel_crtc, pipe_config, state);
6867
6868         if (IS_CHERRYVIEW(dev_priv)) {
6869                 chv_prepare_pll(intel_crtc, pipe_config);
6870                 chv_enable_pll(intel_crtc, pipe_config);
6871         } else {
6872                 vlv_prepare_pll(intel_crtc, pipe_config);
6873                 vlv_enable_pll(intel_crtc, pipe_config);
6874         }
6875
6876         intel_encoders_pre_enable(intel_crtc, pipe_config, state);
6877
6878         i9xx_pfit_enable(pipe_config);
6879
6880         intel_color_load_luts(pipe_config);
6881         intel_color_commit(pipe_config);
6882         /* update DSPCNTR to configure gamma for pipe bottom color */
6883         intel_disable_primary_plane(pipe_config);
6884
6885         dev_priv->display.initial_watermarks(state, pipe_config);
6886         intel_enable_pipe(pipe_config);
6887
6888         assert_vblank_disabled(crtc);
6889         intel_crtc_vblank_on(pipe_config);
6890
6891         intel_encoders_enable(intel_crtc, pipe_config, state);
6892 }
6893
6894 static void i9xx_set_pll_dividers(const struct intel_crtc_state *crtc_state)
6895 {
6896         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
6897         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
6898
6899         I915_WRITE(FP0(crtc->pipe), crtc_state->dpll_hw_state.fp0);
6900         I915_WRITE(FP1(crtc->pipe), crtc_state->dpll_hw_state.fp1);
6901 }
6902
6903 static void i9xx_crtc_enable(struct intel_crtc_state *pipe_config,
6904                              struct intel_atomic_state *state)
6905 {
6906         struct drm_crtc *crtc = pipe_config->base.crtc;
6907         struct drm_device *dev = crtc->dev;
6908         struct drm_i915_private *dev_priv = to_i915(dev);
6909         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
6910         enum pipe pipe = intel_crtc->pipe;
6911
6912         if (WARN_ON(intel_crtc->active))
6913                 return;
6914
6915         i9xx_set_pll_dividers(pipe_config);
6916
6917         if (intel_crtc_has_dp_encoder(pipe_config))
6918                 intel_dp_set_m_n(pipe_config, M1_N1);
6919
6920         intel_set_pipe_timings(pipe_config);
6921         intel_set_pipe_src_size(pipe_config);
6922
6923         i9xx_set_pipeconf(pipe_config);
6924
6925         intel_crtc->active = true;
6926
6927         if (!IS_GEN(dev_priv, 2))
6928                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
6929
6930         intel_encoders_pre_enable(intel_crtc, pipe_config, state);
6931
6932         i9xx_enable_pll(intel_crtc, pipe_config);
6933
6934         i9xx_pfit_enable(pipe_config);
6935
6936         intel_color_load_luts(pipe_config);
6937         intel_color_commit(pipe_config);
6938         /* update DSPCNTR to configure gamma for pipe bottom color */
6939         intel_disable_primary_plane(pipe_config);
6940
6941         if (dev_priv->display.initial_watermarks != NULL)
6942                 dev_priv->display.initial_watermarks(state,
6943                                                      pipe_config);
6944         else
6945                 intel_update_watermarks(intel_crtc);
6946         intel_enable_pipe(pipe_config);
6947
6948         assert_vblank_disabled(crtc);
6949         intel_crtc_vblank_on(pipe_config);
6950
6951         intel_encoders_enable(intel_crtc, pipe_config, state);
6952 }
6953
6954 static void i9xx_pfit_disable(const struct intel_crtc_state *old_crtc_state)
6955 {
6956         struct intel_crtc *crtc = to_intel_crtc(old_crtc_state->base.crtc);
6957         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
6958
6959         if (!old_crtc_state->gmch_pfit.control)
6960                 return;
6961
6962         assert_pipe_disabled(dev_priv, crtc->pipe);
6963
6964         DRM_DEBUG_KMS("disabling pfit, current: 0x%08x\n",
6965                       I915_READ(PFIT_CONTROL));
6966         I915_WRITE(PFIT_CONTROL, 0);
6967 }
6968
6969 static void i9xx_crtc_disable(struct intel_crtc_state *old_crtc_state,
6970                               struct intel_atomic_state *state)
6971 {
6972         struct drm_crtc *crtc = old_crtc_state->base.crtc;
6973         struct drm_device *dev = crtc->dev;
6974         struct drm_i915_private *dev_priv = to_i915(dev);
6975         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
6976         enum pipe pipe = intel_crtc->pipe;
6977
6978         /*
6979          * On gen2 planes are double buffered but the pipe isn't, so we must
6980          * wait for planes to fully turn off before disabling the pipe.
6981          */
6982         if (IS_GEN(dev_priv, 2))
6983                 intel_wait_for_vblank(dev_priv, pipe);
6984
6985         intel_encoders_disable(intel_crtc, old_crtc_state, state);
6986
6987         drm_crtc_vblank_off(crtc);
6988         assert_vblank_disabled(crtc);
6989
6990         intel_disable_pipe(old_crtc_state);
6991
6992         i9xx_pfit_disable(old_crtc_state);
6993
6994         intel_encoders_post_disable(intel_crtc, old_crtc_state, state);
6995
6996         if (!intel_crtc_has_type(old_crtc_state, INTEL_OUTPUT_DSI)) {
6997                 if (IS_CHERRYVIEW(dev_priv))
6998                         chv_disable_pll(dev_priv, pipe);
6999                 else if (IS_VALLEYVIEW(dev_priv))
7000                         vlv_disable_pll(dev_priv, pipe);
7001                 else
7002                         i9xx_disable_pll(old_crtc_state);
7003         }
7004
7005         intel_encoders_post_pll_disable(intel_crtc, old_crtc_state, state);
7006
7007         if (!IS_GEN(dev_priv, 2))
7008                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
7009
7010         if (!dev_priv->display.initial_watermarks)
7011                 intel_update_watermarks(intel_crtc);
7012
7013         /* clock the pipe down to 640x480@60 to potentially save power */
7014         if (IS_I830(dev_priv))
7015                 i830_enable_pipe(dev_priv, pipe);
7016 }
7017
7018 static void intel_crtc_disable_noatomic(struct drm_crtc *crtc,
7019                                         struct drm_modeset_acquire_ctx *ctx)
7020 {
7021         struct intel_encoder *encoder;
7022         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
7023         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
7024         struct intel_bw_state *bw_state =
7025                 to_intel_bw_state(dev_priv->bw_obj.state);
7026         enum intel_display_power_domain domain;
7027         struct intel_plane *plane;
7028         u64 domains;
7029         struct drm_atomic_state *state;
7030         struct intel_crtc_state *crtc_state;
7031         int ret;
7032
7033         if (!intel_crtc->active)
7034                 return;
7035
7036         for_each_intel_plane_on_crtc(&dev_priv->drm, intel_crtc, plane) {
7037                 const struct intel_plane_state *plane_state =
7038                         to_intel_plane_state(plane->base.state);
7039
7040                 if (plane_state->base.visible)
7041                         intel_plane_disable_noatomic(intel_crtc, plane);
7042         }
7043
7044         state = drm_atomic_state_alloc(crtc->dev);
7045         if (!state) {
7046                 DRM_DEBUG_KMS("failed to disable [CRTC:%d:%s], out of memory",
7047                               crtc->base.id, crtc->name);
7048                 return;
7049         }
7050
7051         state->acquire_ctx = ctx;
7052
7053         /* Everything's already locked, -EDEADLK can't happen. */
7054         crtc_state = intel_atomic_get_crtc_state(state, intel_crtc);
7055         ret = drm_atomic_add_affected_connectors(state, crtc);
7056
7057         WARN_ON(IS_ERR(crtc_state) || ret);
7058
7059         dev_priv->display.crtc_disable(crtc_state, to_intel_atomic_state(state));
7060
7061         drm_atomic_state_put(state);
7062
7063         DRM_DEBUG_KMS("[CRTC:%d:%s] hw state adjusted, was enabled, now disabled\n",
7064                       crtc->base.id, crtc->name);
7065
7066         WARN_ON(drm_atomic_set_mode_for_crtc(crtc->state, NULL) < 0);
7067         crtc->state->active = false;
7068         intel_crtc->active = false;
7069         crtc->enabled = false;
7070         crtc->state->connector_mask = 0;
7071         crtc->state->encoder_mask = 0;
7072
7073         for_each_encoder_on_crtc(crtc->dev, crtc, encoder)
7074                 encoder->base.crtc = NULL;
7075
7076         intel_fbc_disable(intel_crtc);
7077         intel_update_watermarks(intel_crtc);
7078         intel_disable_shared_dpll(to_intel_crtc_state(crtc->state));
7079
7080         domains = intel_crtc->enabled_power_domains;
7081         for_each_power_domain(domain, domains)
7082                 intel_display_power_put_unchecked(dev_priv, domain);
7083         intel_crtc->enabled_power_domains = 0;
7084
7085         dev_priv->active_pipes &= ~BIT(intel_crtc->pipe);
7086         dev_priv->min_cdclk[intel_crtc->pipe] = 0;
7087         dev_priv->min_voltage_level[intel_crtc->pipe] = 0;
7088
7089         bw_state->data_rate[intel_crtc->pipe] = 0;
7090         bw_state->num_active_planes[intel_crtc->pipe] = 0;
7091 }
7092
7093 /*
7094  * turn all crtc's off, but do not adjust state
7095  * This has to be paired with a call to intel_modeset_setup_hw_state.
7096  */
7097 int intel_display_suspend(struct drm_device *dev)
7098 {
7099         struct drm_i915_private *dev_priv = to_i915(dev);
7100         struct drm_atomic_state *state;
7101         int ret;
7102
7103         state = drm_atomic_helper_suspend(dev);
7104         ret = PTR_ERR_OR_ZERO(state);
7105         if (ret)
7106                 DRM_ERROR("Suspending crtc's failed with %i\n", ret);
7107         else
7108                 dev_priv->modeset_restore_state = state;
7109         return ret;
7110 }
7111
7112 void intel_encoder_destroy(struct drm_encoder *encoder)
7113 {
7114         struct intel_encoder *intel_encoder = to_intel_encoder(encoder);
7115
7116         drm_encoder_cleanup(encoder);
7117         kfree(intel_encoder);
7118 }
7119
7120 /* Cross check the actual hw state with our own modeset state tracking (and it's
7121  * internal consistency). */
7122 static void intel_connector_verify_state(struct intel_crtc_state *crtc_state,
7123                                          struct drm_connector_state *conn_state)
7124 {
7125         struct intel_connector *connector = to_intel_connector(conn_state->connector);
7126
7127         DRM_DEBUG_KMS("[CONNECTOR:%d:%s]\n",
7128                       connector->base.base.id,
7129                       connector->base.name);
7130
7131         if (connector->get_hw_state(connector)) {
7132                 struct intel_encoder *encoder = connector->encoder;
7133
7134                 I915_STATE_WARN(!crtc_state,
7135                          "connector enabled without attached crtc\n");
7136
7137                 if (!crtc_state)
7138                         return;
7139
7140                 I915_STATE_WARN(!crtc_state->base.active,
7141                       "connector is active, but attached crtc isn't\n");
7142
7143                 if (!encoder || encoder->type == INTEL_OUTPUT_DP_MST)
7144                         return;
7145
7146                 I915_STATE_WARN(conn_state->best_encoder != &encoder->base,
7147                         "atomic encoder doesn't match attached encoder\n");
7148
7149                 I915_STATE_WARN(conn_state->crtc != encoder->base.crtc,
7150                         "attached encoder crtc differs from connector crtc\n");
7151         } else {
7152                 I915_STATE_WARN(crtc_state && crtc_state->base.active,
7153                         "attached crtc is active, but connector isn't\n");
7154                 I915_STATE_WARN(!crtc_state && conn_state->best_encoder,
7155                         "best encoder set without crtc!\n");
7156         }
7157 }
7158
7159 static int pipe_required_fdi_lanes(struct intel_crtc_state *crtc_state)
7160 {
7161         if (crtc_state->base.enable && crtc_state->has_pch_encoder)
7162                 return crtc_state->fdi_lanes;
7163
7164         return 0;
7165 }
7166
7167 static int ironlake_check_fdi_lanes(struct drm_device *dev, enum pipe pipe,
7168                                      struct intel_crtc_state *pipe_config)
7169 {
7170         struct drm_i915_private *dev_priv = to_i915(dev);
7171         struct drm_atomic_state *state = pipe_config->base.state;
7172         struct intel_crtc *other_crtc;
7173         struct intel_crtc_state *other_crtc_state;
7174
7175         DRM_DEBUG_KMS("checking fdi config on pipe %c, lanes %i\n",
7176                       pipe_name(pipe), pipe_config->fdi_lanes);
7177         if (pipe_config->fdi_lanes > 4) {
7178                 DRM_DEBUG_KMS("invalid fdi lane config on pipe %c: %i lanes\n",
7179                               pipe_name(pipe), pipe_config->fdi_lanes);
7180                 return -EINVAL;
7181         }
7182
7183         if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv)) {
7184                 if (pipe_config->fdi_lanes > 2) {
7185                         DRM_DEBUG_KMS("only 2 lanes on haswell, required: %i lanes\n",
7186                                       pipe_config->fdi_lanes);
7187                         return -EINVAL;
7188                 } else {
7189                         return 0;
7190                 }
7191         }
7192
7193         if (INTEL_INFO(dev_priv)->num_pipes == 2)
7194                 return 0;
7195
7196         /* Ivybridge 3 pipe is really complicated */
7197         switch (pipe) {
7198         case PIPE_A:
7199                 return 0;
7200         case PIPE_B:
7201                 if (pipe_config->fdi_lanes <= 2)
7202                         return 0;
7203
7204                 other_crtc = intel_get_crtc_for_pipe(dev_priv, PIPE_C);
7205                 other_crtc_state =
7206                         intel_atomic_get_crtc_state(state, other_crtc);
7207                 if (IS_ERR(other_crtc_state))
7208                         return PTR_ERR(other_crtc_state);
7209
7210                 if (pipe_required_fdi_lanes(other_crtc_state) > 0) {
7211                         DRM_DEBUG_KMS("invalid shared fdi lane config on pipe %c: %i lanes\n",
7212                                       pipe_name(pipe), pipe_config->fdi_lanes);
7213                         return -EINVAL;
7214                 }
7215                 return 0;
7216         case PIPE_C:
7217                 if (pipe_config->fdi_lanes > 2) {
7218                         DRM_DEBUG_KMS("only 2 lanes on pipe %c: required %i lanes\n",
7219                                       pipe_name(pipe), pipe_config->fdi_lanes);
7220                         return -EINVAL;
7221                 }
7222
7223                 other_crtc = intel_get_crtc_for_pipe(dev_priv, PIPE_B);
7224                 other_crtc_state =
7225                         intel_atomic_get_crtc_state(state, other_crtc);
7226                 if (IS_ERR(other_crtc_state))
7227                         return PTR_ERR(other_crtc_state);
7228
7229                 if (pipe_required_fdi_lanes(other_crtc_state) > 2) {
7230                         DRM_DEBUG_KMS("fdi link B uses too many lanes to enable link C\n");
7231                         return -EINVAL;
7232                 }
7233                 return 0;
7234         default:
7235                 BUG();
7236         }
7237 }
7238
7239 #define RETRY 1
7240 static int ironlake_fdi_compute_config(struct intel_crtc *intel_crtc,
7241                                        struct intel_crtc_state *pipe_config)
7242 {
7243         struct drm_device *dev = intel_crtc->base.dev;
7244         const struct drm_display_mode *adjusted_mode = &pipe_config->base.adjusted_mode;
7245         int lane, link_bw, fdi_dotclock, ret;
7246         bool needs_recompute = false;
7247
7248 retry:
7249         /* FDI is a binary signal running at ~2.7GHz, encoding
7250          * each output octet as 10 bits. The actual frequency
7251          * is stored as a divider into a 100MHz clock, and the
7252          * mode pixel clock is stored in units of 1KHz.
7253          * Hence the bw of each lane in terms of the mode signal
7254          * is:
7255          */
7256         link_bw = intel_fdi_link_freq(to_i915(dev), pipe_config);
7257
7258         fdi_dotclock = adjusted_mode->crtc_clock;
7259
7260         lane = ironlake_get_lanes_required(fdi_dotclock, link_bw,
7261                                            pipe_config->pipe_bpp);
7262
7263         pipe_config->fdi_lanes = lane;
7264
7265         intel_link_compute_m_n(pipe_config->pipe_bpp, lane, fdi_dotclock,
7266                                link_bw, &pipe_config->fdi_m_n, false);
7267
7268         ret = ironlake_check_fdi_lanes(dev, intel_crtc->pipe, pipe_config);
7269         if (ret == -EDEADLK)
7270                 return ret;
7271
7272         if (ret == -EINVAL && pipe_config->pipe_bpp > 6*3) {
7273                 pipe_config->pipe_bpp -= 2*3;
7274                 DRM_DEBUG_KMS("fdi link bw constraint, reducing pipe bpp to %i\n",
7275                               pipe_config->pipe_bpp);
7276                 needs_recompute = true;
7277                 pipe_config->bw_constrained = true;
7278
7279                 goto retry;
7280         }
7281
7282         if (needs_recompute)
7283                 return RETRY;
7284
7285         return ret;
7286 }
7287
7288 bool hsw_crtc_state_ips_capable(const struct intel_crtc_state *crtc_state)
7289 {
7290         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
7291         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
7292
7293         /* IPS only exists on ULT machines and is tied to pipe A. */
7294         if (!hsw_crtc_supports_ips(crtc))
7295                 return false;
7296
7297         if (!i915_modparams.enable_ips)
7298                 return false;
7299
7300         if (crtc_state->pipe_bpp > 24)
7301                 return false;
7302
7303         /*
7304          * We compare against max which means we must take
7305          * the increased cdclk requirement into account when
7306          * calculating the new cdclk.
7307          *
7308          * Should measure whether using a lower cdclk w/o IPS
7309          */
7310         if (IS_BROADWELL(dev_priv) &&
7311             crtc_state->pixel_rate > dev_priv->max_cdclk_freq * 95 / 100)
7312                 return false;
7313
7314         return true;
7315 }
7316
7317 static bool hsw_compute_ips_config(struct intel_crtc_state *crtc_state)
7318 {
7319         struct drm_i915_private *dev_priv =
7320                 to_i915(crtc_state->base.crtc->dev);
7321         struct intel_atomic_state *intel_state =
7322                 to_intel_atomic_state(crtc_state->base.state);
7323
7324         if (!hsw_crtc_state_ips_capable(crtc_state))
7325                 return false;
7326
7327         /*
7328          * When IPS gets enabled, the pipe CRC changes. Since IPS gets
7329          * enabled and disabled dynamically based on package C states,
7330          * user space can't make reliable use of the CRCs, so let's just
7331          * completely disable it.
7332          */
7333         if (crtc_state->crc_enabled)
7334                 return false;
7335
7336         /* IPS should be fine as long as at least one plane is enabled. */
7337         if (!(crtc_state->active_planes & ~BIT(PLANE_CURSOR)))
7338                 return false;
7339
7340         /* pixel rate mustn't exceed 95% of cdclk with IPS on BDW */
7341         if (IS_BROADWELL(dev_priv) &&
7342             crtc_state->pixel_rate > intel_state->cdclk.logical.cdclk * 95 / 100)
7343                 return false;
7344
7345         return true;
7346 }
7347
7348 static bool intel_crtc_supports_double_wide(const struct intel_crtc *crtc)
7349 {
7350         const struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
7351
7352         /* GDG double wide on either pipe, otherwise pipe A only */
7353         return INTEL_GEN(dev_priv) < 4 &&
7354                 (crtc->pipe == PIPE_A || IS_I915G(dev_priv));
7355 }
7356
7357 static u32 ilk_pipe_pixel_rate(const struct intel_crtc_state *pipe_config)
7358 {
7359         u32 pixel_rate;
7360
7361         pixel_rate = pipe_config->base.adjusted_mode.crtc_clock;
7362
7363         /*
7364          * We only use IF-ID interlacing. If we ever use
7365          * PF-ID we'll need to adjust the pixel_rate here.
7366          */
7367
7368         if (pipe_config->pch_pfit.enabled) {
7369                 u64 pipe_w, pipe_h, pfit_w, pfit_h;
7370                 u32 pfit_size = pipe_config->pch_pfit.size;
7371
7372                 pipe_w = pipe_config->pipe_src_w;
7373                 pipe_h = pipe_config->pipe_src_h;
7374
7375                 pfit_w = (pfit_size >> 16) & 0xFFFF;
7376                 pfit_h = pfit_size & 0xFFFF;
7377                 if (pipe_w < pfit_w)
7378                         pipe_w = pfit_w;
7379                 if (pipe_h < pfit_h)
7380                         pipe_h = pfit_h;
7381
7382                 if (WARN_ON(!pfit_w || !pfit_h))
7383                         return pixel_rate;
7384
7385                 pixel_rate = div_u64(mul_u32_u32(pixel_rate, pipe_w * pipe_h),
7386                                      pfit_w * pfit_h);
7387         }
7388
7389         return pixel_rate;
7390 }
7391
7392 static void intel_crtc_compute_pixel_rate(struct intel_crtc_state *crtc_state)
7393 {
7394         struct drm_i915_private *dev_priv = to_i915(crtc_state->base.crtc->dev);
7395
7396         if (HAS_GMCH(dev_priv))
7397                 /* FIXME calculate proper pipe pixel rate for GMCH pfit */
7398                 crtc_state->pixel_rate =
7399                         crtc_state->base.adjusted_mode.crtc_clock;
7400         else
7401                 crtc_state->pixel_rate =
7402                         ilk_pipe_pixel_rate(crtc_state);
7403 }
7404
7405 static int intel_crtc_compute_config(struct intel_crtc *crtc,
7406                                      struct intel_crtc_state *pipe_config)
7407 {
7408         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
7409         const struct drm_display_mode *adjusted_mode = &pipe_config->base.adjusted_mode;
7410         int clock_limit = dev_priv->max_dotclk_freq;
7411
7412         if (INTEL_GEN(dev_priv) < 4) {
7413                 clock_limit = dev_priv->max_cdclk_freq * 9 / 10;
7414
7415                 /*
7416                  * Enable double wide mode when the dot clock
7417                  * is > 90% of the (display) core speed.
7418                  */
7419                 if (intel_crtc_supports_double_wide(crtc) &&
7420                     adjusted_mode->crtc_clock > clock_limit) {
7421                         clock_limit = dev_priv->max_dotclk_freq;
7422                         pipe_config->double_wide = true;
7423                 }
7424         }
7425
7426         if (adjusted_mode->crtc_clock > clock_limit) {
7427                 DRM_DEBUG_KMS("requested pixel clock (%d kHz) too high (max: %d kHz, double wide: %s)\n",
7428                               adjusted_mode->crtc_clock, clock_limit,
7429                               yesno(pipe_config->double_wide));
7430                 return -EINVAL;
7431         }
7432
7433         if ((pipe_config->output_format == INTEL_OUTPUT_FORMAT_YCBCR420 ||
7434              pipe_config->output_format == INTEL_OUTPUT_FORMAT_YCBCR444) &&
7435              pipe_config->base.ctm) {
7436                 /*
7437                  * There is only one pipe CSC unit per pipe, and we need that
7438                  * for output conversion from RGB->YCBCR. So if CTM is already
7439                  * applied we can't support YCBCR420 output.
7440                  */
7441                 DRM_DEBUG_KMS("YCBCR420 and CTM together are not possible\n");
7442                 return -EINVAL;
7443         }
7444
7445         /*
7446          * Pipe horizontal size must be even in:
7447          * - DVO ganged mode
7448          * - LVDS dual channel mode
7449          * - Double wide pipe
7450          */
7451         if (pipe_config->pipe_src_w & 1) {
7452                 if (pipe_config->double_wide) {
7453                         DRM_DEBUG_KMS("Odd pipe source width not supported with double wide pipe\n");
7454                         return -EINVAL;
7455                 }
7456
7457                 if (intel_crtc_has_type(pipe_config, INTEL_OUTPUT_LVDS) &&
7458                     intel_is_dual_link_lvds(dev_priv)) {
7459                         DRM_DEBUG_KMS("Odd pipe source width not supported with dual link LVDS\n");
7460                         return -EINVAL;
7461                 }
7462         }
7463
7464         /* Cantiga+ cannot handle modes with a hsync front porch of 0.
7465          * WaPruneModeWithIncorrectHsyncOffset:ctg,elk,ilk,snb,ivb,vlv,hsw.
7466          */
7467         if ((INTEL_GEN(dev_priv) > 4 || IS_G4X(dev_priv)) &&
7468                 adjusted_mode->crtc_hsync_start == adjusted_mode->crtc_hdisplay)
7469                 return -EINVAL;
7470
7471         intel_crtc_compute_pixel_rate(pipe_config);
7472
7473         if (pipe_config->has_pch_encoder)
7474                 return ironlake_fdi_compute_config(crtc, pipe_config);
7475
7476         return 0;
7477 }
7478
7479 static void
7480 intel_reduce_m_n_ratio(u32 *num, u32 *den)
7481 {
7482         while (*num > DATA_LINK_M_N_MASK ||
7483                *den > DATA_LINK_M_N_MASK) {
7484                 *num >>= 1;
7485                 *den >>= 1;
7486         }
7487 }
7488
7489 static void compute_m_n(unsigned int m, unsigned int n,
7490                         u32 *ret_m, u32 *ret_n,
7491                         bool constant_n)
7492 {
7493         /*
7494          * Several DP dongles in particular seem to be fussy about
7495          * too large link M/N values. Give N value as 0x8000 that
7496          * should be acceptable by specific devices. 0x8000 is the
7497          * specified fixed N value for asynchronous clock mode,
7498          * which the devices expect also in synchronous clock mode.
7499          */
7500         if (constant_n)
7501                 *ret_n = 0x8000;
7502         else
7503                 *ret_n = min_t(unsigned int, roundup_pow_of_two(n), DATA_LINK_N_MAX);
7504
7505         *ret_m = div_u64(mul_u32_u32(m, *ret_n), n);
7506         intel_reduce_m_n_ratio(ret_m, ret_n);
7507 }
7508
7509 void
7510 intel_link_compute_m_n(u16 bits_per_pixel, int nlanes,
7511                        int pixel_clock, int link_clock,
7512                        struct intel_link_m_n *m_n,
7513                        bool constant_n)
7514 {
7515         m_n->tu = 64;
7516
7517         compute_m_n(bits_per_pixel * pixel_clock,
7518                     link_clock * nlanes * 8,
7519                     &m_n->gmch_m, &m_n->gmch_n,
7520                     constant_n);
7521
7522         compute_m_n(pixel_clock, link_clock,
7523                     &m_n->link_m, &m_n->link_n,
7524                     constant_n);
7525 }
7526
7527 static inline bool intel_panel_use_ssc(struct drm_i915_private *dev_priv)
7528 {
7529         if (i915_modparams.panel_use_ssc >= 0)
7530                 return i915_modparams.panel_use_ssc != 0;
7531         return dev_priv->vbt.lvds_use_ssc
7532                 && !(dev_priv->quirks & QUIRK_LVDS_SSC_DISABLE);
7533 }
7534
7535 static u32 pnv_dpll_compute_fp(struct dpll *dpll)
7536 {
7537         return (1 << dpll->n) << 16 | dpll->m2;
7538 }
7539
7540 static u32 i9xx_dpll_compute_fp(struct dpll *dpll)
7541 {
7542         return dpll->n << 16 | dpll->m1 << 8 | dpll->m2;
7543 }
7544
7545 static void i9xx_update_pll_dividers(struct intel_crtc *crtc,
7546                                      struct intel_crtc_state *crtc_state,
7547                                      struct dpll *reduced_clock)
7548 {
7549         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
7550         u32 fp, fp2 = 0;
7551
7552         if (IS_PINEVIEW(dev_priv)) {
7553                 fp = pnv_dpll_compute_fp(&crtc_state->dpll);
7554                 if (reduced_clock)
7555                         fp2 = pnv_dpll_compute_fp(reduced_clock);
7556         } else {
7557                 fp = i9xx_dpll_compute_fp(&crtc_state->dpll);
7558                 if (reduced_clock)
7559                         fp2 = i9xx_dpll_compute_fp(reduced_clock);
7560         }
7561
7562         crtc_state->dpll_hw_state.fp0 = fp;
7563
7564         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS) &&
7565             reduced_clock) {
7566                 crtc_state->dpll_hw_state.fp1 = fp2;
7567         } else {
7568                 crtc_state->dpll_hw_state.fp1 = fp;
7569         }
7570 }
7571
7572 static void vlv_pllb_recal_opamp(struct drm_i915_private *dev_priv, enum pipe
7573                 pipe)
7574 {
7575         u32 reg_val;
7576
7577         /*
7578          * PLLB opamp always calibrates to max value of 0x3f, force enable it
7579          * and set it to a reasonable value instead.
7580          */
7581         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW9(1));
7582         reg_val &= 0xffffff00;
7583         reg_val |= 0x00000030;
7584         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW9(1), reg_val);
7585
7586         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_REF_DW13);
7587         reg_val &= 0x00ffffff;
7588         reg_val |= 0x8c000000;
7589         vlv_dpio_write(dev_priv, pipe, VLV_REF_DW13, reg_val);
7590
7591         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW9(1));
7592         reg_val &= 0xffffff00;
7593         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW9(1), reg_val);
7594
7595         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_REF_DW13);
7596         reg_val &= 0x00ffffff;
7597         reg_val |= 0xb0000000;
7598         vlv_dpio_write(dev_priv, pipe, VLV_REF_DW13, reg_val);
7599 }
7600
7601 static void intel_pch_transcoder_set_m_n(const struct intel_crtc_state *crtc_state,
7602                                          const struct intel_link_m_n *m_n)
7603 {
7604         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
7605         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
7606         enum pipe pipe = crtc->pipe;
7607
7608         I915_WRITE(PCH_TRANS_DATA_M1(pipe), TU_SIZE(m_n->tu) | m_n->gmch_m);
7609         I915_WRITE(PCH_TRANS_DATA_N1(pipe), m_n->gmch_n);
7610         I915_WRITE(PCH_TRANS_LINK_M1(pipe), m_n->link_m);
7611         I915_WRITE(PCH_TRANS_LINK_N1(pipe), m_n->link_n);
7612 }
7613
7614 static bool transcoder_has_m2_n2(struct drm_i915_private *dev_priv,
7615                                  enum transcoder transcoder)
7616 {
7617         if (IS_HASWELL(dev_priv))
7618                 return transcoder == TRANSCODER_EDP;
7619
7620         /*
7621          * Strictly speaking some registers are available before
7622          * gen7, but we only support DRRS on gen7+
7623          */
7624         return IS_GEN(dev_priv, 7) || IS_CHERRYVIEW(dev_priv);
7625 }
7626
7627 static void intel_cpu_transcoder_set_m_n(const struct intel_crtc_state *crtc_state,
7628                                          const struct intel_link_m_n *m_n,
7629                                          const struct intel_link_m_n *m2_n2)
7630 {
7631         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
7632         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
7633         enum pipe pipe = crtc->pipe;
7634         enum transcoder transcoder = crtc_state->cpu_transcoder;
7635
7636         if (INTEL_GEN(dev_priv) >= 5) {
7637                 I915_WRITE(PIPE_DATA_M1(transcoder), TU_SIZE(m_n->tu) | m_n->gmch_m);
7638                 I915_WRITE(PIPE_DATA_N1(transcoder), m_n->gmch_n);
7639                 I915_WRITE(PIPE_LINK_M1(transcoder), m_n->link_m);
7640                 I915_WRITE(PIPE_LINK_N1(transcoder), m_n->link_n);
7641                 /*
7642                  *  M2_N2 registers are set only if DRRS is supported
7643                  * (to make sure the registers are not unnecessarily accessed).
7644                  */
7645                 if (m2_n2 && crtc_state->has_drrs &&
7646                     transcoder_has_m2_n2(dev_priv, transcoder)) {
7647                         I915_WRITE(PIPE_DATA_M2(transcoder),
7648                                         TU_SIZE(m2_n2->tu) | m2_n2->gmch_m);
7649                         I915_WRITE(PIPE_DATA_N2(transcoder), m2_n2->gmch_n);
7650                         I915_WRITE(PIPE_LINK_M2(transcoder), m2_n2->link_m);
7651                         I915_WRITE(PIPE_LINK_N2(transcoder), m2_n2->link_n);
7652                 }
7653         } else {
7654                 I915_WRITE(PIPE_DATA_M_G4X(pipe), TU_SIZE(m_n->tu) | m_n->gmch_m);
7655                 I915_WRITE(PIPE_DATA_N_G4X(pipe), m_n->gmch_n);
7656                 I915_WRITE(PIPE_LINK_M_G4X(pipe), m_n->link_m);
7657                 I915_WRITE(PIPE_LINK_N_G4X(pipe), m_n->link_n);
7658         }
7659 }
7660
7661 void intel_dp_set_m_n(const struct intel_crtc_state *crtc_state, enum link_m_n_set m_n)
7662 {
7663         const struct intel_link_m_n *dp_m_n, *dp_m2_n2 = NULL;
7664
7665         if (m_n == M1_N1) {
7666                 dp_m_n = &crtc_state->dp_m_n;
7667                 dp_m2_n2 = &crtc_state->dp_m2_n2;
7668         } else if (m_n == M2_N2) {
7669
7670                 /*
7671                  * M2_N2 registers are not supported. Hence m2_n2 divider value
7672                  * needs to be programmed into M1_N1.
7673                  */
7674                 dp_m_n = &crtc_state->dp_m2_n2;
7675         } else {
7676                 DRM_ERROR("Unsupported divider value\n");
7677                 return;
7678         }
7679
7680         if (crtc_state->has_pch_encoder)
7681                 intel_pch_transcoder_set_m_n(crtc_state, &crtc_state->dp_m_n);
7682         else
7683                 intel_cpu_transcoder_set_m_n(crtc_state, dp_m_n, dp_m2_n2);
7684 }
7685
7686 static void vlv_compute_dpll(struct intel_crtc *crtc,
7687                              struct intel_crtc_state *pipe_config)
7688 {
7689         pipe_config->dpll_hw_state.dpll = DPLL_INTEGRATED_REF_CLK_VLV |
7690                 DPLL_REF_CLK_ENABLE_VLV | DPLL_VGA_MODE_DIS;
7691         if (crtc->pipe != PIPE_A)
7692                 pipe_config->dpll_hw_state.dpll |= DPLL_INTEGRATED_CRI_CLK_VLV;
7693
7694         /* DPLL not used with DSI, but still need the rest set up */
7695         if (!intel_crtc_has_type(pipe_config, INTEL_OUTPUT_DSI))
7696                 pipe_config->dpll_hw_state.dpll |= DPLL_VCO_ENABLE |
7697                         DPLL_EXT_BUFFER_ENABLE_VLV;
7698
7699         pipe_config->dpll_hw_state.dpll_md =
7700                 (pipe_config->pixel_multiplier - 1) << DPLL_MD_UDI_MULTIPLIER_SHIFT;
7701 }
7702
7703 static void chv_compute_dpll(struct intel_crtc *crtc,
7704                              struct intel_crtc_state *pipe_config)
7705 {
7706         pipe_config->dpll_hw_state.dpll = DPLL_SSC_REF_CLK_CHV |
7707                 DPLL_REF_CLK_ENABLE_VLV | DPLL_VGA_MODE_DIS;
7708         if (crtc->pipe != PIPE_A)
7709                 pipe_config->dpll_hw_state.dpll |= DPLL_INTEGRATED_CRI_CLK_VLV;
7710
7711         /* DPLL not used with DSI, but still need the rest set up */
7712         if (!intel_crtc_has_type(pipe_config, INTEL_OUTPUT_DSI))
7713                 pipe_config->dpll_hw_state.dpll |= DPLL_VCO_ENABLE;
7714
7715         pipe_config->dpll_hw_state.dpll_md =
7716                 (pipe_config->pixel_multiplier - 1) << DPLL_MD_UDI_MULTIPLIER_SHIFT;
7717 }
7718
7719 static void vlv_prepare_pll(struct intel_crtc *crtc,
7720                             const struct intel_crtc_state *pipe_config)
7721 {
7722         struct drm_device *dev = crtc->base.dev;
7723         struct drm_i915_private *dev_priv = to_i915(dev);
7724         enum pipe pipe = crtc->pipe;
7725         u32 mdiv;
7726         u32 bestn, bestm1, bestm2, bestp1, bestp2;
7727         u32 coreclk, reg_val;
7728
7729         /* Enable Refclk */
7730         I915_WRITE(DPLL(pipe),
7731                    pipe_config->dpll_hw_state.dpll &
7732                    ~(DPLL_VCO_ENABLE | DPLL_EXT_BUFFER_ENABLE_VLV));
7733
7734         /* No need to actually set up the DPLL with DSI */
7735         if ((pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE) == 0)
7736                 return;
7737
7738         vlv_dpio_get(dev_priv);
7739
7740         bestn = pipe_config->dpll.n;
7741         bestm1 = pipe_config->dpll.m1;
7742         bestm2 = pipe_config->dpll.m2;
7743         bestp1 = pipe_config->dpll.p1;
7744         bestp2 = pipe_config->dpll.p2;
7745
7746         /* See eDP HDMI DPIO driver vbios notes doc */
7747
7748         /* PLL B needs special handling */
7749         if (pipe == PIPE_B)
7750                 vlv_pllb_recal_opamp(dev_priv, pipe);
7751
7752         /* Set up Tx target for periodic Rcomp update */
7753         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW9_BCAST, 0x0100000f);
7754
7755         /* Disable target IRef on PLL */
7756         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW8(pipe));
7757         reg_val &= 0x00ffffff;
7758         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW8(pipe), reg_val);
7759
7760         /* Disable fast lock */
7761         vlv_dpio_write(dev_priv, pipe, VLV_CMN_DW0, 0x610);
7762
7763         /* Set idtafcrecal before PLL is enabled */
7764         mdiv = ((bestm1 << DPIO_M1DIV_SHIFT) | (bestm2 & DPIO_M2DIV_MASK));
7765         mdiv |= ((bestp1 << DPIO_P1_SHIFT) | (bestp2 << DPIO_P2_SHIFT));
7766         mdiv |= ((bestn << DPIO_N_SHIFT));
7767         mdiv |= (1 << DPIO_K_SHIFT);
7768
7769         /*
7770          * Post divider depends on pixel clock rate, DAC vs digital (and LVDS,
7771          * but we don't support that).
7772          * Note: don't use the DAC post divider as it seems unstable.
7773          */
7774         mdiv |= (DPIO_POST_DIV_HDMIDP << DPIO_POST_DIV_SHIFT);
7775         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW3(pipe), mdiv);
7776
7777         mdiv |= DPIO_ENABLE_CALIBRATION;
7778         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW3(pipe), mdiv);
7779
7780         /* Set HBR and RBR LPF coefficients */
7781         if (pipe_config->port_clock == 162000 ||
7782             intel_crtc_has_type(pipe_config, INTEL_OUTPUT_ANALOG) ||
7783             intel_crtc_has_type(pipe_config, INTEL_OUTPUT_HDMI))
7784                 vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW10(pipe),
7785                                  0x009f0003);
7786         else
7787                 vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW10(pipe),
7788                                  0x00d0000f);
7789
7790         if (intel_crtc_has_dp_encoder(pipe_config)) {
7791                 /* Use SSC source */
7792                 if (pipe == PIPE_A)
7793                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
7794                                          0x0df40000);
7795                 else
7796                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
7797                                          0x0df70000);
7798         } else { /* HDMI or VGA */
7799                 /* Use bend source */
7800                 if (pipe == PIPE_A)
7801                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
7802                                          0x0df70000);
7803                 else
7804                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
7805                                          0x0df40000);
7806         }
7807
7808         coreclk = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW7(pipe));
7809         coreclk = (coreclk & 0x0000ff00) | 0x01c00000;
7810         if (intel_crtc_has_dp_encoder(pipe_config))
7811                 coreclk |= 0x01000000;
7812         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW7(pipe), coreclk);
7813
7814         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW11(pipe), 0x87871000);
7815
7816         vlv_dpio_put(dev_priv);
7817 }
7818
7819 static void chv_prepare_pll(struct intel_crtc *crtc,
7820                             const struct intel_crtc_state *pipe_config)
7821 {
7822         struct drm_device *dev = crtc->base.dev;
7823         struct drm_i915_private *dev_priv = to_i915(dev);
7824         enum pipe pipe = crtc->pipe;
7825         enum dpio_channel port = vlv_pipe_to_channel(pipe);
7826         u32 loopfilter, tribuf_calcntr;
7827         u32 bestn, bestm1, bestm2, bestp1, bestp2, bestm2_frac;
7828         u32 dpio_val;
7829         int vco;
7830
7831         /* Enable Refclk and SSC */
7832         I915_WRITE(DPLL(pipe),
7833                    pipe_config->dpll_hw_state.dpll & ~DPLL_VCO_ENABLE);
7834
7835         /* No need to actually set up the DPLL with DSI */
7836         if ((pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE) == 0)
7837                 return;
7838
7839         bestn = pipe_config->dpll.n;
7840         bestm2_frac = pipe_config->dpll.m2 & 0x3fffff;
7841         bestm1 = pipe_config->dpll.m1;
7842         bestm2 = pipe_config->dpll.m2 >> 22;
7843         bestp1 = pipe_config->dpll.p1;
7844         bestp2 = pipe_config->dpll.p2;
7845         vco = pipe_config->dpll.vco;
7846         dpio_val = 0;
7847         loopfilter = 0;
7848
7849         vlv_dpio_get(dev_priv);
7850
7851         /* p1 and p2 divider */
7852         vlv_dpio_write(dev_priv, pipe, CHV_CMN_DW13(port),
7853                         5 << DPIO_CHV_S1_DIV_SHIFT |
7854                         bestp1 << DPIO_CHV_P1_DIV_SHIFT |
7855                         bestp2 << DPIO_CHV_P2_DIV_SHIFT |
7856                         1 << DPIO_CHV_K_DIV_SHIFT);
7857
7858         /* Feedback post-divider - m2 */
7859         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW0(port), bestm2);
7860
7861         /* Feedback refclk divider - n and m1 */
7862         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW1(port),
7863                         DPIO_CHV_M1_DIV_BY_2 |
7864                         1 << DPIO_CHV_N_DIV_SHIFT);
7865
7866         /* M2 fraction division */
7867         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW2(port), bestm2_frac);
7868
7869         /* M2 fraction division enable */
7870         dpio_val = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW3(port));
7871         dpio_val &= ~(DPIO_CHV_FEEDFWD_GAIN_MASK | DPIO_CHV_FRAC_DIV_EN);
7872         dpio_val |= (2 << DPIO_CHV_FEEDFWD_GAIN_SHIFT);
7873         if (bestm2_frac)
7874                 dpio_val |= DPIO_CHV_FRAC_DIV_EN;
7875         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW3(port), dpio_val);
7876
7877         /* Program digital lock detect threshold */
7878         dpio_val = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW9(port));
7879         dpio_val &= ~(DPIO_CHV_INT_LOCK_THRESHOLD_MASK |
7880                                         DPIO_CHV_INT_LOCK_THRESHOLD_SEL_COARSE);
7881         dpio_val |= (0x5 << DPIO_CHV_INT_LOCK_THRESHOLD_SHIFT);
7882         if (!bestm2_frac)
7883                 dpio_val |= DPIO_CHV_INT_LOCK_THRESHOLD_SEL_COARSE;
7884         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW9(port), dpio_val);
7885
7886         /* Loop filter */
7887         if (vco == 5400000) {
7888                 loopfilter |= (0x3 << DPIO_CHV_PROP_COEFF_SHIFT);
7889                 loopfilter |= (0x8 << DPIO_CHV_INT_COEFF_SHIFT);
7890                 loopfilter |= (0x1 << DPIO_CHV_GAIN_CTRL_SHIFT);
7891                 tribuf_calcntr = 0x9;
7892         } else if (vco <= 6200000) {
7893                 loopfilter |= (0x5 << DPIO_CHV_PROP_COEFF_SHIFT);
7894                 loopfilter |= (0xB << DPIO_CHV_INT_COEFF_SHIFT);
7895                 loopfilter |= (0x3 << DPIO_CHV_GAIN_CTRL_SHIFT);
7896                 tribuf_calcntr = 0x9;
7897         } else if (vco <= 6480000) {
7898                 loopfilter |= (0x4 << DPIO_CHV_PROP_COEFF_SHIFT);
7899                 loopfilter |= (0x9 << DPIO_CHV_INT_COEFF_SHIFT);
7900                 loopfilter |= (0x3 << DPIO_CHV_GAIN_CTRL_SHIFT);
7901                 tribuf_calcntr = 0x8;
7902         } else {
7903                 /* Not supported. Apply the same limits as in the max case */
7904                 loopfilter |= (0x4 << DPIO_CHV_PROP_COEFF_SHIFT);
7905                 loopfilter |= (0x9 << DPIO_CHV_INT_COEFF_SHIFT);
7906                 loopfilter |= (0x3 << DPIO_CHV_GAIN_CTRL_SHIFT);
7907                 tribuf_calcntr = 0;
7908         }
7909         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW6(port), loopfilter);
7910
7911         dpio_val = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW8(port));
7912         dpio_val &= ~DPIO_CHV_TDC_TARGET_CNT_MASK;
7913         dpio_val |= (tribuf_calcntr << DPIO_CHV_TDC_TARGET_CNT_SHIFT);
7914         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW8(port), dpio_val);
7915
7916         /* AFC Recal */
7917         vlv_dpio_write(dev_priv, pipe, CHV_CMN_DW14(port),
7918                         vlv_dpio_read(dev_priv, pipe, CHV_CMN_DW14(port)) |
7919                         DPIO_AFC_RECAL);
7920
7921         vlv_dpio_put(dev_priv);
7922 }
7923
7924 /**
7925  * vlv_force_pll_on - forcibly enable just the PLL
7926  * @dev_priv: i915 private structure
7927  * @pipe: pipe PLL to enable
7928  * @dpll: PLL configuration
7929  *
7930  * Enable the PLL for @pipe using the supplied @dpll config. To be used
7931  * in cases where we need the PLL enabled even when @pipe is not going to
7932  * be enabled.
7933  */
7934 int vlv_force_pll_on(struct drm_i915_private *dev_priv, enum pipe pipe,
7935                      const struct dpll *dpll)
7936 {
7937         struct intel_crtc *crtc = intel_get_crtc_for_pipe(dev_priv, pipe);
7938         struct intel_crtc_state *pipe_config;
7939
7940         pipe_config = kzalloc(sizeof(*pipe_config), GFP_KERNEL);
7941         if (!pipe_config)
7942                 return -ENOMEM;
7943
7944         pipe_config->base.crtc = &crtc->base;
7945         pipe_config->pixel_multiplier = 1;
7946         pipe_config->dpll = *dpll;
7947
7948         if (IS_CHERRYVIEW(dev_priv)) {
7949                 chv_compute_dpll(crtc, pipe_config);
7950                 chv_prepare_pll(crtc, pipe_config);
7951                 chv_enable_pll(crtc, pipe_config);
7952         } else {
7953                 vlv_compute_dpll(crtc, pipe_config);
7954                 vlv_prepare_pll(crtc, pipe_config);
7955                 vlv_enable_pll(crtc, pipe_config);
7956         }
7957
7958         kfree(pipe_config);
7959
7960         return 0;
7961 }
7962
7963 /**
7964  * vlv_force_pll_off - forcibly disable just the PLL
7965  * @dev_priv: i915 private structure
7966  * @pipe: pipe PLL to disable
7967  *
7968  * Disable the PLL for @pipe. To be used in cases where we need
7969  * the PLL enabled even when @pipe is not going to be enabled.
7970  */
7971 void vlv_force_pll_off(struct drm_i915_private *dev_priv, enum pipe pipe)
7972 {
7973         if (IS_CHERRYVIEW(dev_priv))
7974                 chv_disable_pll(dev_priv, pipe);
7975         else
7976                 vlv_disable_pll(dev_priv, pipe);
7977 }
7978
7979 static void i9xx_compute_dpll(struct intel_crtc *crtc,
7980                               struct intel_crtc_state *crtc_state,
7981                               struct dpll *reduced_clock)
7982 {
7983         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
7984         u32 dpll;
7985         struct dpll *clock = &crtc_state->dpll;
7986
7987         i9xx_update_pll_dividers(crtc, crtc_state, reduced_clock);
7988
7989         dpll = DPLL_VGA_MODE_DIS;
7990
7991         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS))
7992                 dpll |= DPLLB_MODE_LVDS;
7993         else
7994                 dpll |= DPLLB_MODE_DAC_SERIAL;
7995
7996         if (IS_I945G(dev_priv) || IS_I945GM(dev_priv) ||
7997             IS_G33(dev_priv) || IS_PINEVIEW(dev_priv)) {
7998                 dpll |= (crtc_state->pixel_multiplier - 1)
7999                         << SDVO_MULTIPLIER_SHIFT_HIRES;
8000         }
8001
8002         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_SDVO) ||
8003             intel_crtc_has_type(crtc_state, INTEL_OUTPUT_HDMI))
8004                 dpll |= DPLL_SDVO_HIGH_SPEED;
8005
8006         if (intel_crtc_has_dp_encoder(crtc_state))
8007                 dpll |= DPLL_SDVO_HIGH_SPEED;
8008
8009         /* compute bitmask from p1 value */
8010         if (IS_PINEVIEW(dev_priv))
8011                 dpll |= (1 << (clock->p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT_PINEVIEW;
8012         else {
8013                 dpll |= (1 << (clock->p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT;
8014                 if (IS_G4X(dev_priv) && reduced_clock)
8015                         dpll |= (1 << (reduced_clock->p1 - 1)) << DPLL_FPA1_P1_POST_DIV_SHIFT;
8016         }
8017         switch (clock->p2) {
8018         case 5:
8019                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_5;
8020                 break;
8021         case 7:
8022                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_7;
8023                 break;
8024         case 10:
8025                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_10;
8026                 break;
8027         case 14:
8028                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_14;
8029                 break;
8030         }
8031         if (INTEL_GEN(dev_priv) >= 4)
8032                 dpll |= (6 << PLL_LOAD_PULSE_PHASE_SHIFT);
8033
8034         if (crtc_state->sdvo_tv_clock)
8035                 dpll |= PLL_REF_INPUT_TVCLKINBC;
8036         else if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS) &&
8037                  intel_panel_use_ssc(dev_priv))
8038                 dpll |= PLLB_REF_INPUT_SPREADSPECTRUMIN;
8039         else
8040                 dpll |= PLL_REF_INPUT_DREFCLK;
8041
8042         dpll |= DPLL_VCO_ENABLE;
8043         crtc_state->dpll_hw_state.dpll = dpll;
8044
8045         if (INTEL_GEN(dev_priv) >= 4) {
8046                 u32 dpll_md = (crtc_state->pixel_multiplier - 1)
8047                         << DPLL_MD_UDI_MULTIPLIER_SHIFT;
8048                 crtc_state->dpll_hw_state.dpll_md = dpll_md;
8049         }
8050 }
8051
8052 static void i8xx_compute_dpll(struct intel_crtc *crtc,
8053                               struct intel_crtc_state *crtc_state,
8054                               struct dpll *reduced_clock)
8055 {
8056         struct drm_device *dev = crtc->base.dev;
8057         struct drm_i915_private *dev_priv = to_i915(dev);
8058         u32 dpll;
8059         struct dpll *clock = &crtc_state->dpll;
8060
8061         i9xx_update_pll_dividers(crtc, crtc_state, reduced_clock);
8062
8063         dpll = DPLL_VGA_MODE_DIS;
8064
8065         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
8066                 dpll |= (1 << (clock->p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT;
8067         } else {
8068                 if (clock->p1 == 2)
8069                         dpll |= PLL_P1_DIVIDE_BY_TWO;
8070                 else
8071                         dpll |= (clock->p1 - 2) << DPLL_FPA01_P1_POST_DIV_SHIFT;
8072                 if (clock->p2 == 4)
8073                         dpll |= PLL_P2_DIVIDE_BY_4;
8074         }
8075
8076         /*
8077          * Bspec:
8078          * "[Almador Errata}: For the correct operation of the muxed DVO pins
8079          *  (GDEVSELB/I2Cdata, GIRDBY/I2CClk) and (GFRAMEB/DVI_Data,
8080          *  GTRDYB/DVI_Clk): Bit 31 (DPLL VCO Enable) and Bit 30 (2X Clock
8081          *  Enable) must be set to “1” in both the DPLL A Control Register
8082          *  (06014h-06017h) and DPLL B Control Register (06018h-0601Bh)."
8083          *
8084          * For simplicity We simply keep both bits always enabled in
8085          * both DPLLS. The spec says we should disable the DVO 2X clock
8086          * when not needed, but this seems to work fine in practice.
8087          */
8088         if (IS_I830(dev_priv) ||
8089             intel_crtc_has_type(crtc_state, INTEL_OUTPUT_DVO))
8090                 dpll |= DPLL_DVO_2X_MODE;
8091
8092         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS) &&
8093             intel_panel_use_ssc(dev_priv))
8094                 dpll |= PLLB_REF_INPUT_SPREADSPECTRUMIN;
8095         else
8096                 dpll |= PLL_REF_INPUT_DREFCLK;
8097
8098         dpll |= DPLL_VCO_ENABLE;
8099         crtc_state->dpll_hw_state.dpll = dpll;
8100 }
8101
8102 static void intel_set_pipe_timings(const struct intel_crtc_state *crtc_state)
8103 {
8104         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
8105         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
8106         enum pipe pipe = crtc->pipe;
8107         enum transcoder cpu_transcoder = crtc_state->cpu_transcoder;
8108         const struct drm_display_mode *adjusted_mode = &crtc_state->base.adjusted_mode;
8109         u32 crtc_vtotal, crtc_vblank_end;
8110         int vsyncshift = 0;
8111
8112         /* We need to be careful not to changed the adjusted mode, for otherwise
8113          * the hw state checker will get angry at the mismatch. */
8114         crtc_vtotal = adjusted_mode->crtc_vtotal;
8115         crtc_vblank_end = adjusted_mode->crtc_vblank_end;
8116
8117         if (adjusted_mode->flags & DRM_MODE_FLAG_INTERLACE) {
8118                 /* the chip adds 2 halflines automatically */
8119                 crtc_vtotal -= 1;
8120                 crtc_vblank_end -= 1;
8121
8122                 if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_SDVO))
8123                         vsyncshift = (adjusted_mode->crtc_htotal - 1) / 2;
8124                 else
8125                         vsyncshift = adjusted_mode->crtc_hsync_start -
8126                                 adjusted_mode->crtc_htotal / 2;
8127                 if (vsyncshift < 0)
8128                         vsyncshift += adjusted_mode->crtc_htotal;
8129         }
8130
8131         if (INTEL_GEN(dev_priv) > 3)
8132                 I915_WRITE(VSYNCSHIFT(cpu_transcoder), vsyncshift);
8133
8134         I915_WRITE(HTOTAL(cpu_transcoder),
8135                    (adjusted_mode->crtc_hdisplay - 1) |
8136                    ((adjusted_mode->crtc_htotal - 1) << 16));
8137         I915_WRITE(HBLANK(cpu_transcoder),
8138                    (adjusted_mode->crtc_hblank_start - 1) |
8139                    ((adjusted_mode->crtc_hblank_end - 1) << 16));
8140         I915_WRITE(HSYNC(cpu_transcoder),
8141                    (adjusted_mode->crtc_hsync_start - 1) |
8142                    ((adjusted_mode->crtc_hsync_end - 1) << 16));
8143
8144         I915_WRITE(VTOTAL(cpu_transcoder),
8145                    (adjusted_mode->crtc_vdisplay - 1) |
8146                    ((crtc_vtotal - 1) << 16));
8147         I915_WRITE(VBLANK(cpu_transcoder),
8148                    (adjusted_mode->crtc_vblank_start - 1) |
8149                    ((crtc_vblank_end - 1) << 16));
8150         I915_WRITE(VSYNC(cpu_transcoder),
8151                    (adjusted_mode->crtc_vsync_start - 1) |
8152                    ((adjusted_mode->crtc_vsync_end - 1) << 16));
8153
8154         /* Workaround: when the EDP input selection is B, the VTOTAL_B must be
8155          * programmed with the VTOTAL_EDP value. Same for VTOTAL_C. This is
8156          * documented on the DDI_FUNC_CTL register description, EDP Input Select
8157          * bits. */
8158         if (IS_HASWELL(dev_priv) && cpu_transcoder == TRANSCODER_EDP &&
8159             (pipe == PIPE_B || pipe == PIPE_C))
8160                 I915_WRITE(VTOTAL(pipe), I915_READ(VTOTAL(cpu_transcoder)));
8161
8162 }
8163
8164 static void intel_set_pipe_src_size(const struct intel_crtc_state *crtc_state)
8165 {
8166         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
8167         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
8168         enum pipe pipe = crtc->pipe;
8169
8170         /* pipesrc controls the size that is scaled from, which should
8171          * always be the user's requested size.
8172          */
8173         I915_WRITE(PIPESRC(pipe),
8174                    ((crtc_state->pipe_src_w - 1) << 16) |
8175                    (crtc_state->pipe_src_h - 1));
8176 }
8177
8178 static void intel_get_pipe_timings(struct intel_crtc *crtc,
8179                                    struct intel_crtc_state *pipe_config)
8180 {
8181         struct drm_device *dev = crtc->base.dev;
8182         struct drm_i915_private *dev_priv = to_i915(dev);
8183         enum transcoder cpu_transcoder = pipe_config->cpu_transcoder;
8184         u32 tmp;
8185
8186         tmp = I915_READ(HTOTAL(cpu_transcoder));
8187         pipe_config->base.adjusted_mode.crtc_hdisplay = (tmp & 0xffff) + 1;
8188         pipe_config->base.adjusted_mode.crtc_htotal = ((tmp >> 16) & 0xffff) + 1;
8189
8190         if (!transcoder_is_dsi(cpu_transcoder)) {
8191                 tmp = I915_READ(HBLANK(cpu_transcoder));
8192                 pipe_config->base.adjusted_mode.crtc_hblank_start =
8193                                                         (tmp & 0xffff) + 1;
8194                 pipe_config->base.adjusted_mode.crtc_hblank_end =
8195                                                 ((tmp >> 16) & 0xffff) + 1;
8196         }
8197         tmp = I915_READ(HSYNC(cpu_transcoder));
8198         pipe_config->base.adjusted_mode.crtc_hsync_start = (tmp & 0xffff) + 1;
8199         pipe_config->base.adjusted_mode.crtc_hsync_end = ((tmp >> 16) & 0xffff) + 1;
8200
8201         tmp = I915_READ(VTOTAL(cpu_transcoder));
8202         pipe_config->base.adjusted_mode.crtc_vdisplay = (tmp & 0xffff) + 1;
8203         pipe_config->base.adjusted_mode.crtc_vtotal = ((tmp >> 16) & 0xffff) + 1;
8204
8205         if (!transcoder_is_dsi(cpu_transcoder)) {
8206                 tmp = I915_READ(VBLANK(cpu_transcoder));
8207                 pipe_config->base.adjusted_mode.crtc_vblank_start =
8208                                                         (tmp & 0xffff) + 1;
8209                 pipe_config->base.adjusted_mode.crtc_vblank_end =
8210                                                 ((tmp >> 16) & 0xffff) + 1;
8211         }
8212         tmp = I915_READ(VSYNC(cpu_transcoder));
8213         pipe_config->base.adjusted_mode.crtc_vsync_start = (tmp & 0xffff) + 1;
8214         pipe_config->base.adjusted_mode.crtc_vsync_end = ((tmp >> 16) & 0xffff) + 1;
8215
8216         if (I915_READ(PIPECONF(cpu_transcoder)) & PIPECONF_INTERLACE_MASK) {
8217                 pipe_config->base.adjusted_mode.flags |= DRM_MODE_FLAG_INTERLACE;
8218                 pipe_config->base.adjusted_mode.crtc_vtotal += 1;
8219                 pipe_config->base.adjusted_mode.crtc_vblank_end += 1;
8220         }
8221 }
8222
8223 static void intel_get_pipe_src_size(struct intel_crtc *crtc,
8224                                     struct intel_crtc_state *pipe_config)
8225 {
8226         struct drm_device *dev = crtc->base.dev;
8227         struct drm_i915_private *dev_priv = to_i915(dev);
8228         u32 tmp;
8229
8230         tmp = I915_READ(PIPESRC(crtc->pipe));
8231         pipe_config->pipe_src_h = (tmp & 0xffff) + 1;
8232         pipe_config->pipe_src_w = ((tmp >> 16) & 0xffff) + 1;
8233
8234         pipe_config->base.mode.vdisplay = pipe_config->pipe_src_h;
8235         pipe_config->base.mode.hdisplay = pipe_config->pipe_src_w;
8236 }
8237
8238 void intel_mode_from_pipe_config(struct drm_display_mode *mode,
8239                                  struct intel_crtc_state *pipe_config)
8240 {
8241         mode->hdisplay = pipe_config->base.adjusted_mode.crtc_hdisplay;
8242         mode->htotal = pipe_config->base.adjusted_mode.crtc_htotal;
8243         mode->hsync_start = pipe_config->base.adjusted_mode.crtc_hsync_start;
8244         mode->hsync_end = pipe_config->base.adjusted_mode.crtc_hsync_end;
8245
8246         mode->vdisplay = pipe_config->base.adjusted_mode.crtc_vdisplay;
8247         mode->vtotal = pipe_config->base.adjusted_mode.crtc_vtotal;
8248         mode->vsync_start = pipe_config->base.adjusted_mode.crtc_vsync_start;
8249         mode->vsync_end = pipe_config->base.adjusted_mode.crtc_vsync_end;
8250
8251         mode->flags = pipe_config->base.adjusted_mode.flags;
8252         mode->type = DRM_MODE_TYPE_DRIVER;
8253
8254         mode->clock = pipe_config->base.adjusted_mode.crtc_clock;
8255
8256         mode->hsync = drm_mode_hsync(mode);
8257         mode->vrefresh = drm_mode_vrefresh(mode);
8258         drm_mode_set_name(mode);
8259 }
8260
8261 static void i9xx_set_pipeconf(const struct intel_crtc_state *crtc_state)
8262 {
8263         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
8264         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
8265         u32 pipeconf;
8266
8267         pipeconf = 0;
8268
8269         /* we keep both pipes enabled on 830 */
8270         if (IS_I830(dev_priv))
8271                 pipeconf |= I915_READ(PIPECONF(crtc->pipe)) & PIPECONF_ENABLE;
8272
8273         if (crtc_state->double_wide)
8274                 pipeconf |= PIPECONF_DOUBLE_WIDE;
8275
8276         /* only g4x and later have fancy bpc/dither controls */
8277         if (IS_G4X(dev_priv) || IS_VALLEYVIEW(dev_priv) ||
8278             IS_CHERRYVIEW(dev_priv)) {
8279                 /* Bspec claims that we can't use dithering for 30bpp pipes. */
8280                 if (crtc_state->dither && crtc_state->pipe_bpp != 30)
8281                         pipeconf |= PIPECONF_DITHER_EN |
8282                                     PIPECONF_DITHER_TYPE_SP;
8283
8284                 switch (crtc_state->pipe_bpp) {
8285                 case 18:
8286                         pipeconf |= PIPECONF_6BPC;
8287                         break;
8288                 case 24:
8289                         pipeconf |= PIPECONF_8BPC;
8290                         break;
8291                 case 30:
8292                         pipeconf |= PIPECONF_10BPC;
8293                         break;
8294                 default:
8295                         /* Case prevented by intel_choose_pipe_bpp_dither. */
8296                         BUG();
8297                 }
8298         }
8299
8300         if (crtc_state->base.adjusted_mode.flags & DRM_MODE_FLAG_INTERLACE) {
8301                 if (INTEL_GEN(dev_priv) < 4 ||
8302                     intel_crtc_has_type(crtc_state, INTEL_OUTPUT_SDVO))
8303                         pipeconf |= PIPECONF_INTERLACE_W_FIELD_INDICATION;
8304                 else
8305                         pipeconf |= PIPECONF_INTERLACE_W_SYNC_SHIFT;
8306         } else {
8307                 pipeconf |= PIPECONF_PROGRESSIVE;
8308         }
8309
8310         if ((IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv)) &&
8311              crtc_state->limited_color_range)
8312                 pipeconf |= PIPECONF_COLOR_RANGE_SELECT;
8313
8314         pipeconf |= PIPECONF_GAMMA_MODE(crtc_state->gamma_mode);
8315
8316         I915_WRITE(PIPECONF(crtc->pipe), pipeconf);
8317         POSTING_READ(PIPECONF(crtc->pipe));
8318 }
8319
8320 static int i8xx_crtc_compute_clock(struct intel_crtc *crtc,
8321                                    struct intel_crtc_state *crtc_state)
8322 {
8323         struct drm_device *dev = crtc->base.dev;
8324         struct drm_i915_private *dev_priv = to_i915(dev);
8325         const struct intel_limit *limit;
8326         int refclk = 48000;
8327
8328         memset(&crtc_state->dpll_hw_state, 0,
8329                sizeof(crtc_state->dpll_hw_state));
8330
8331         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
8332                 if (intel_panel_use_ssc(dev_priv)) {
8333                         refclk = dev_priv->vbt.lvds_ssc_freq;
8334                         DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n", refclk);
8335                 }
8336
8337                 limit = &intel_limits_i8xx_lvds;
8338         } else if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_DVO)) {
8339                 limit = &intel_limits_i8xx_dvo;
8340         } else {
8341                 limit = &intel_limits_i8xx_dac;
8342         }
8343
8344         if (!crtc_state->clock_set &&
8345             !i9xx_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
8346                                  refclk, NULL, &crtc_state->dpll)) {
8347                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
8348                 return -EINVAL;
8349         }
8350
8351         i8xx_compute_dpll(crtc, crtc_state, NULL);
8352
8353         return 0;
8354 }
8355
8356 static int g4x_crtc_compute_clock(struct intel_crtc *crtc,
8357                                   struct intel_crtc_state *crtc_state)
8358 {
8359         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
8360         const struct intel_limit *limit;
8361         int refclk = 96000;
8362
8363         memset(&crtc_state->dpll_hw_state, 0,
8364                sizeof(crtc_state->dpll_hw_state));
8365
8366         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
8367                 if (intel_panel_use_ssc(dev_priv)) {
8368                         refclk = dev_priv->vbt.lvds_ssc_freq;
8369                         DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n", refclk);
8370                 }
8371
8372                 if (intel_is_dual_link_lvds(dev_priv))
8373                         limit = &intel_limits_g4x_dual_channel_lvds;
8374                 else
8375                         limit = &intel_limits_g4x_single_channel_lvds;
8376         } else if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_HDMI) ||
8377                    intel_crtc_has_type(crtc_state, INTEL_OUTPUT_ANALOG)) {
8378                 limit = &intel_limits_g4x_hdmi;
8379         } else if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_SDVO)) {
8380                 limit = &intel_limits_g4x_sdvo;
8381         } else {
8382                 /* The option is for other outputs */
8383                 limit = &intel_limits_i9xx_sdvo;
8384         }
8385
8386         if (!crtc_state->clock_set &&
8387             !g4x_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
8388                                 refclk, NULL, &crtc_state->dpll)) {
8389                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
8390                 return -EINVAL;
8391         }
8392
8393         i9xx_compute_dpll(crtc, crtc_state, NULL);
8394
8395         return 0;
8396 }
8397
8398 static int pnv_crtc_compute_clock(struct intel_crtc *crtc,
8399                                   struct intel_crtc_state *crtc_state)
8400 {
8401         struct drm_device *dev = crtc->base.dev;
8402         struct drm_i915_private *dev_priv = to_i915(dev);
8403         const struct intel_limit *limit;
8404         int refclk = 96000;
8405
8406         memset(&crtc_state->dpll_hw_state, 0,
8407                sizeof(crtc_state->dpll_hw_state));
8408
8409         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
8410                 if (intel_panel_use_ssc(dev_priv)) {
8411                         refclk = dev_priv->vbt.lvds_ssc_freq;
8412                         DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n", refclk);
8413                 }
8414
8415                 limit = &intel_limits_pineview_lvds;
8416         } else {
8417                 limit = &intel_limits_pineview_sdvo;
8418         }
8419
8420         if (!crtc_state->clock_set &&
8421             !pnv_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
8422                                 refclk, NULL, &crtc_state->dpll)) {
8423                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
8424                 return -EINVAL;
8425         }
8426
8427         i9xx_compute_dpll(crtc, crtc_state, NULL);
8428
8429         return 0;
8430 }
8431
8432 static int i9xx_crtc_compute_clock(struct intel_crtc *crtc,
8433                                    struct intel_crtc_state *crtc_state)
8434 {
8435         struct drm_device *dev = crtc->base.dev;
8436         struct drm_i915_private *dev_priv = to_i915(dev);
8437         const struct intel_limit *limit;
8438         int refclk = 96000;
8439
8440         memset(&crtc_state->dpll_hw_state, 0,
8441                sizeof(crtc_state->dpll_hw_state));
8442
8443         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
8444                 if (intel_panel_use_ssc(dev_priv)) {
8445                         refclk = dev_priv->vbt.lvds_ssc_freq;
8446                         DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n", refclk);
8447                 }
8448
8449                 limit = &intel_limits_i9xx_lvds;
8450         } else {
8451                 limit = &intel_limits_i9xx_sdvo;
8452         }
8453
8454         if (!crtc_state->clock_set &&
8455             !i9xx_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
8456                                  refclk, NULL, &crtc_state->dpll)) {
8457                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
8458                 return -EINVAL;
8459         }
8460
8461         i9xx_compute_dpll(crtc, crtc_state, NULL);
8462
8463         return 0;
8464 }
8465
8466 static int chv_crtc_compute_clock(struct intel_crtc *crtc,
8467                                   struct intel_crtc_state *crtc_state)
8468 {
8469         int refclk = 100000;
8470         const struct intel_limit *limit = &intel_limits_chv;
8471
8472         memset(&crtc_state->dpll_hw_state, 0,
8473                sizeof(crtc_state->dpll_hw_state));
8474
8475         if (!crtc_state->clock_set &&
8476             !chv_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
8477                                 refclk, NULL, &crtc_state->dpll)) {
8478                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
8479                 return -EINVAL;
8480         }
8481
8482         chv_compute_dpll(crtc, crtc_state);
8483
8484         return 0;
8485 }
8486
8487 static int vlv_crtc_compute_clock(struct intel_crtc *crtc,
8488                                   struct intel_crtc_state *crtc_state)
8489 {
8490         int refclk = 100000;
8491         const struct intel_limit *limit = &intel_limits_vlv;
8492
8493         memset(&crtc_state->dpll_hw_state, 0,
8494                sizeof(crtc_state->dpll_hw_state));
8495
8496         if (!crtc_state->clock_set &&
8497             !vlv_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
8498                                 refclk, NULL, &crtc_state->dpll)) {
8499                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
8500                 return -EINVAL;
8501         }
8502
8503         vlv_compute_dpll(crtc, crtc_state);
8504
8505         return 0;
8506 }
8507
8508 static bool i9xx_has_pfit(struct drm_i915_private *dev_priv)
8509 {
8510         if (IS_I830(dev_priv))
8511                 return false;
8512
8513         return INTEL_GEN(dev_priv) >= 4 ||
8514                 IS_PINEVIEW(dev_priv) || IS_MOBILE(dev_priv);
8515 }
8516
8517 static void i9xx_get_pfit_config(struct intel_crtc *crtc,
8518                                  struct intel_crtc_state *pipe_config)
8519 {
8520         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
8521         u32 tmp;
8522
8523         if (!i9xx_has_pfit(dev_priv))
8524                 return;
8525
8526         tmp = I915_READ(PFIT_CONTROL);
8527         if (!(tmp & PFIT_ENABLE))
8528                 return;
8529
8530         /* Check whether the pfit is attached to our pipe. */
8531         if (INTEL_GEN(dev_priv) < 4) {
8532                 if (crtc->pipe != PIPE_B)
8533                         return;
8534         } else {
8535                 if ((tmp & PFIT_PIPE_MASK) != (crtc->pipe << PFIT_PIPE_SHIFT))
8536                         return;
8537         }
8538
8539         pipe_config->gmch_pfit.control = tmp;
8540         pipe_config->gmch_pfit.pgm_ratios = I915_READ(PFIT_PGM_RATIOS);
8541 }
8542
8543 static void vlv_crtc_clock_get(struct intel_crtc *crtc,
8544                                struct intel_crtc_state *pipe_config)
8545 {
8546         struct drm_device *dev = crtc->base.dev;
8547         struct drm_i915_private *dev_priv = to_i915(dev);
8548         enum pipe pipe = crtc->pipe;
8549         struct dpll clock;
8550         u32 mdiv;
8551         int refclk = 100000;
8552
8553         /* In case of DSI, DPLL will not be used */
8554         if ((pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE) == 0)
8555                 return;
8556
8557         vlv_dpio_get(dev_priv);
8558         mdiv = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW3(pipe));
8559         vlv_dpio_put(dev_priv);
8560
8561         clock.m1 = (mdiv >> DPIO_M1DIV_SHIFT) & 7;
8562         clock.m2 = mdiv & DPIO_M2DIV_MASK;
8563         clock.n = (mdiv >> DPIO_N_SHIFT) & 0xf;
8564         clock.p1 = (mdiv >> DPIO_P1_SHIFT) & 7;
8565         clock.p2 = (mdiv >> DPIO_P2_SHIFT) & 0x1f;
8566
8567         pipe_config->port_clock = vlv_calc_dpll_params(refclk, &clock);
8568 }
8569
8570 static void
8571 i9xx_get_initial_plane_config(struct intel_crtc *crtc,
8572                               struct intel_initial_plane_config *plane_config)
8573 {
8574         struct drm_device *dev = crtc->base.dev;
8575         struct drm_i915_private *dev_priv = to_i915(dev);
8576         struct intel_plane *plane = to_intel_plane(crtc->base.primary);
8577         enum i9xx_plane_id i9xx_plane = plane->i9xx_plane;
8578         enum pipe pipe;
8579         u32 val, base, offset;
8580         int fourcc, pixel_format;
8581         unsigned int aligned_height;
8582         struct drm_framebuffer *fb;
8583         struct intel_framebuffer *intel_fb;
8584
8585         if (!plane->get_hw_state(plane, &pipe))
8586                 return;
8587
8588         WARN_ON(pipe != crtc->pipe);
8589
8590         intel_fb = kzalloc(sizeof(*intel_fb), GFP_KERNEL);
8591         if (!intel_fb) {
8592                 DRM_DEBUG_KMS("failed to alloc fb\n");
8593                 return;
8594         }
8595
8596         fb = &intel_fb->base;
8597
8598         fb->dev = dev;
8599
8600         val = I915_READ(DSPCNTR(i9xx_plane));
8601
8602         if (INTEL_GEN(dev_priv) >= 4) {
8603                 if (val & DISPPLANE_TILED) {
8604                         plane_config->tiling = I915_TILING_X;
8605                         fb->modifier = I915_FORMAT_MOD_X_TILED;
8606                 }
8607
8608                 if (val & DISPPLANE_ROTATE_180)
8609                         plane_config->rotation = DRM_MODE_ROTATE_180;
8610         }
8611
8612         if (IS_CHERRYVIEW(dev_priv) && pipe == PIPE_B &&
8613             val & DISPPLANE_MIRROR)
8614                 plane_config->rotation |= DRM_MODE_REFLECT_X;
8615
8616         pixel_format = val & DISPPLANE_PIXFORMAT_MASK;
8617         fourcc = i9xx_format_to_fourcc(pixel_format);
8618         fb->format = drm_format_info(fourcc);
8619
8620         if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv)) {
8621                 offset = I915_READ(DSPOFFSET(i9xx_plane));
8622                 base = I915_READ(DSPSURF(i9xx_plane)) & 0xfffff000;
8623         } else if (INTEL_GEN(dev_priv) >= 4) {
8624                 if (plane_config->tiling)
8625                         offset = I915_READ(DSPTILEOFF(i9xx_plane));
8626                 else
8627                         offset = I915_READ(DSPLINOFF(i9xx_plane));
8628                 base = I915_READ(DSPSURF(i9xx_plane)) & 0xfffff000;
8629         } else {
8630                 base = I915_READ(DSPADDR(i9xx_plane));
8631         }
8632         plane_config->base = base;
8633
8634         val = I915_READ(PIPESRC(pipe));
8635         fb->width = ((val >> 16) & 0xfff) + 1;
8636         fb->height = ((val >> 0) & 0xfff) + 1;
8637
8638         val = I915_READ(DSPSTRIDE(i9xx_plane));
8639         fb->pitches[0] = val & 0xffffffc0;
8640
8641         aligned_height = intel_fb_align_height(fb, 0, fb->height);
8642
8643         plane_config->size = fb->pitches[0] * aligned_height;
8644
8645         DRM_DEBUG_KMS("%s/%s with fb: size=%dx%d@%d, offset=%x, pitch %d, size 0x%x\n",
8646                       crtc->base.name, plane->base.name, fb->width, fb->height,
8647                       fb->format->cpp[0] * 8, base, fb->pitches[0],
8648                       plane_config->size);
8649
8650         plane_config->fb = intel_fb;
8651 }
8652
8653 static void chv_crtc_clock_get(struct intel_crtc *crtc,
8654                                struct intel_crtc_state *pipe_config)
8655 {
8656         struct drm_device *dev = crtc->base.dev;
8657         struct drm_i915_private *dev_priv = to_i915(dev);
8658         enum pipe pipe = crtc->pipe;
8659         enum dpio_channel port = vlv_pipe_to_channel(pipe);
8660         struct dpll clock;
8661         u32 cmn_dw13, pll_dw0, pll_dw1, pll_dw2, pll_dw3;
8662         int refclk = 100000;
8663
8664         /* In case of DSI, DPLL will not be used */
8665         if ((pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE) == 0)
8666                 return;
8667
8668         vlv_dpio_get(dev_priv);
8669         cmn_dw13 = vlv_dpio_read(dev_priv, pipe, CHV_CMN_DW13(port));
8670         pll_dw0 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW0(port));
8671         pll_dw1 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW1(port));
8672         pll_dw2 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW2(port));
8673         pll_dw3 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW3(port));
8674         vlv_dpio_put(dev_priv);
8675
8676         clock.m1 = (pll_dw1 & 0x7) == DPIO_CHV_M1_DIV_BY_2 ? 2 : 0;
8677         clock.m2 = (pll_dw0 & 0xff) << 22;
8678         if (pll_dw3 & DPIO_CHV_FRAC_DIV_EN)
8679                 clock.m2 |= pll_dw2 & 0x3fffff;
8680         clock.n = (pll_dw1 >> DPIO_CHV_N_DIV_SHIFT) & 0xf;
8681         clock.p1 = (cmn_dw13 >> DPIO_CHV_P1_DIV_SHIFT) & 0x7;
8682         clock.p2 = (cmn_dw13 >> DPIO_CHV_P2_DIV_SHIFT) & 0x1f;
8683
8684         pipe_config->port_clock = chv_calc_dpll_params(refclk, &clock);
8685 }
8686
8687 static void intel_get_crtc_ycbcr_config(struct intel_crtc *crtc,
8688                                         struct intel_crtc_state *pipe_config)
8689 {
8690         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
8691         enum intel_output_format output = INTEL_OUTPUT_FORMAT_RGB;
8692
8693         pipe_config->lspcon_downsampling = false;
8694
8695         if (IS_BROADWELL(dev_priv) || INTEL_GEN(dev_priv) >= 9) {
8696                 u32 tmp = I915_READ(PIPEMISC(crtc->pipe));
8697
8698                 if (tmp & PIPEMISC_OUTPUT_COLORSPACE_YUV) {
8699                         bool ycbcr420_enabled = tmp & PIPEMISC_YUV420_ENABLE;
8700                         bool blend = tmp & PIPEMISC_YUV420_MODE_FULL_BLEND;
8701
8702                         if (ycbcr420_enabled) {
8703                                 /* We support 4:2:0 in full blend mode only */
8704                                 if (!blend)
8705                                         output = INTEL_OUTPUT_FORMAT_INVALID;
8706                                 else if (!(IS_GEMINILAKE(dev_priv) ||
8707                                            INTEL_GEN(dev_priv) >= 10))
8708                                         output = INTEL_OUTPUT_FORMAT_INVALID;
8709                                 else
8710                                         output = INTEL_OUTPUT_FORMAT_YCBCR420;
8711                         } else {
8712                                 /*
8713                                  * Currently there is no interface defined to
8714                                  * check user preference between RGB/YCBCR444
8715                                  * or YCBCR420. So the only possible case for
8716                                  * YCBCR444 usage is driving YCBCR420 output
8717                                  * with LSPCON, when pipe is configured for
8718                                  * YCBCR444 output and LSPCON takes care of
8719                                  * downsampling it.
8720                                  */
8721                                 pipe_config->lspcon_downsampling = true;
8722                                 output = INTEL_OUTPUT_FORMAT_YCBCR444;
8723                         }
8724                 }
8725         }
8726
8727         pipe_config->output_format = output;
8728 }
8729
8730 static void i9xx_get_pipe_color_config(struct intel_crtc_state *crtc_state)
8731 {
8732         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
8733         struct intel_plane *plane = to_intel_plane(crtc->base.primary);
8734         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
8735         enum i9xx_plane_id i9xx_plane = plane->i9xx_plane;
8736         u32 tmp;
8737
8738         tmp = I915_READ(DSPCNTR(i9xx_plane));
8739
8740         if (tmp & DISPPLANE_GAMMA_ENABLE)
8741                 crtc_state->gamma_enable = true;
8742
8743         if (!HAS_GMCH(dev_priv) &&
8744             tmp & DISPPLANE_PIPE_CSC_ENABLE)
8745                 crtc_state->csc_enable = true;
8746 }
8747
8748 static bool i9xx_get_pipe_config(struct intel_crtc *crtc,
8749                                  struct intel_crtc_state *pipe_config)
8750 {
8751         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
8752         enum intel_display_power_domain power_domain;
8753         intel_wakeref_t wakeref;
8754         u32 tmp;
8755         bool ret;
8756
8757         power_domain = POWER_DOMAIN_PIPE(crtc->pipe);
8758         wakeref = intel_display_power_get_if_enabled(dev_priv, power_domain);
8759         if (!wakeref)
8760                 return false;
8761
8762         pipe_config->output_format = INTEL_OUTPUT_FORMAT_RGB;
8763         pipe_config->cpu_transcoder = (enum transcoder) crtc->pipe;
8764         pipe_config->shared_dpll = NULL;
8765
8766         ret = false;
8767
8768         tmp = I915_READ(PIPECONF(crtc->pipe));
8769         if (!(tmp & PIPECONF_ENABLE))
8770                 goto out;
8771
8772         if (IS_G4X(dev_priv) || IS_VALLEYVIEW(dev_priv) ||
8773             IS_CHERRYVIEW(dev_priv)) {
8774                 switch (tmp & PIPECONF_BPC_MASK) {
8775                 case PIPECONF_6BPC:
8776                         pipe_config->pipe_bpp = 18;
8777                         break;
8778                 case PIPECONF_8BPC:
8779                         pipe_config->pipe_bpp = 24;
8780                         break;
8781                 case PIPECONF_10BPC:
8782                         pipe_config->pipe_bpp = 30;
8783                         break;
8784                 default:
8785                         break;
8786                 }
8787         }
8788
8789         if ((IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv)) &&
8790             (tmp & PIPECONF_COLOR_RANGE_SELECT))
8791                 pipe_config->limited_color_range = true;
8792
8793         pipe_config->gamma_mode = (tmp & PIPECONF_GAMMA_MODE_MASK_I9XX) >>
8794                 PIPECONF_GAMMA_MODE_SHIFT;
8795
8796         if (IS_CHERRYVIEW(dev_priv))
8797                 pipe_config->cgm_mode = I915_READ(CGM_PIPE_MODE(crtc->pipe));
8798
8799         i9xx_get_pipe_color_config(pipe_config);
8800         intel_color_get_config(pipe_config);
8801
8802         if (INTEL_GEN(dev_priv) < 4)
8803                 pipe_config->double_wide = tmp & PIPECONF_DOUBLE_WIDE;
8804
8805         intel_get_pipe_timings(crtc, pipe_config);
8806         intel_get_pipe_src_size(crtc, pipe_config);
8807
8808         i9xx_get_pfit_config(crtc, pipe_config);
8809
8810         if (INTEL_GEN(dev_priv) >= 4) {
8811                 /* No way to read it out on pipes B and C */
8812                 if (IS_CHERRYVIEW(dev_priv) && crtc->pipe != PIPE_A)
8813                         tmp = dev_priv->chv_dpll_md[crtc->pipe];
8814                 else
8815                         tmp = I915_READ(DPLL_MD(crtc->pipe));
8816                 pipe_config->pixel_multiplier =
8817                         ((tmp & DPLL_MD_UDI_MULTIPLIER_MASK)
8818                          >> DPLL_MD_UDI_MULTIPLIER_SHIFT) + 1;
8819                 pipe_config->dpll_hw_state.dpll_md = tmp;
8820         } else if (IS_I945G(dev_priv) || IS_I945GM(dev_priv) ||
8821                    IS_G33(dev_priv) || IS_PINEVIEW(dev_priv)) {
8822                 tmp = I915_READ(DPLL(crtc->pipe));
8823                 pipe_config->pixel_multiplier =
8824                         ((tmp & SDVO_MULTIPLIER_MASK)
8825                          >> SDVO_MULTIPLIER_SHIFT_HIRES) + 1;
8826         } else {
8827                 /* Note that on i915G/GM the pixel multiplier is in the sdvo
8828                  * port and will be fixed up in the encoder->get_config
8829                  * function. */
8830                 pipe_config->pixel_multiplier = 1;
8831         }
8832         pipe_config->dpll_hw_state.dpll = I915_READ(DPLL(crtc->pipe));
8833         if (!IS_VALLEYVIEW(dev_priv) && !IS_CHERRYVIEW(dev_priv)) {
8834                 pipe_config->dpll_hw_state.fp0 = I915_READ(FP0(crtc->pipe));
8835                 pipe_config->dpll_hw_state.fp1 = I915_READ(FP1(crtc->pipe));
8836         } else {
8837                 /* Mask out read-only status bits. */
8838                 pipe_config->dpll_hw_state.dpll &= ~(DPLL_LOCK_VLV |
8839                                                      DPLL_PORTC_READY_MASK |
8840                                                      DPLL_PORTB_READY_MASK);
8841         }
8842
8843         if (IS_CHERRYVIEW(dev_priv))
8844                 chv_crtc_clock_get(crtc, pipe_config);
8845         else if (IS_VALLEYVIEW(dev_priv))
8846                 vlv_crtc_clock_get(crtc, pipe_config);
8847         else
8848                 i9xx_crtc_clock_get(crtc, pipe_config);
8849
8850         /*
8851          * Normally the dotclock is filled in by the encoder .get_config()
8852          * but in case the pipe is enabled w/o any ports we need a sane
8853          * default.
8854          */
8855         pipe_config->base.adjusted_mode.crtc_clock =
8856                 pipe_config->port_clock / pipe_config->pixel_multiplier;
8857
8858         ret = true;
8859
8860 out:
8861         intel_display_power_put(dev_priv, power_domain, wakeref);
8862
8863         return ret;
8864 }
8865
8866 static void ironlake_init_pch_refclk(struct drm_i915_private *dev_priv)
8867 {
8868         struct intel_encoder *encoder;
8869         int i;
8870         u32 val, final;
8871         bool has_lvds = false;
8872         bool has_cpu_edp = false;
8873         bool has_panel = false;
8874         bool has_ck505 = false;
8875         bool can_ssc = false;
8876         bool using_ssc_source = false;
8877
8878         /* We need to take the global config into account */
8879         for_each_intel_encoder(&dev_priv->drm, encoder) {
8880                 switch (encoder->type) {
8881                 case INTEL_OUTPUT_LVDS:
8882                         has_panel = true;
8883                         has_lvds = true;
8884                         break;
8885                 case INTEL_OUTPUT_EDP:
8886                         has_panel = true;
8887                         if (encoder->port == PORT_A)
8888                                 has_cpu_edp = true;
8889                         break;
8890                 default:
8891                         break;
8892                 }
8893         }
8894
8895         if (HAS_PCH_IBX(dev_priv)) {
8896                 has_ck505 = dev_priv->vbt.display_clock_mode;
8897                 can_ssc = has_ck505;
8898         } else {
8899                 has_ck505 = false;
8900                 can_ssc = true;
8901         }
8902
8903         /* Check if any DPLLs are using the SSC source */
8904         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
8905                 u32 temp = I915_READ(PCH_DPLL(i));
8906
8907                 if (!(temp & DPLL_VCO_ENABLE))
8908                         continue;
8909
8910                 if ((temp & PLL_REF_INPUT_MASK) ==
8911                     PLLB_REF_INPUT_SPREADSPECTRUMIN) {
8912                         using_ssc_source = true;
8913                         break;
8914                 }
8915         }
8916
8917         DRM_DEBUG_KMS("has_panel %d has_lvds %d has_ck505 %d using_ssc_source %d\n",
8918                       has_panel, has_lvds, has_ck505, using_ssc_source);
8919
8920         /* Ironlake: try to setup display ref clock before DPLL
8921          * enabling. This is only under driver's control after
8922          * PCH B stepping, previous chipset stepping should be
8923          * ignoring this setting.
8924          */
8925         val = I915_READ(PCH_DREF_CONTROL);
8926
8927         /* As we must carefully and slowly disable/enable each source in turn,
8928          * compute the final state we want first and check if we need to
8929          * make any changes at all.
8930          */
8931         final = val;
8932         final &= ~DREF_NONSPREAD_SOURCE_MASK;
8933         if (has_ck505)
8934                 final |= DREF_NONSPREAD_CK505_ENABLE;
8935         else
8936                 final |= DREF_NONSPREAD_SOURCE_ENABLE;
8937
8938         final &= ~DREF_SSC_SOURCE_MASK;
8939         final &= ~DREF_CPU_SOURCE_OUTPUT_MASK;
8940         final &= ~DREF_SSC1_ENABLE;
8941
8942         if (has_panel) {
8943                 final |= DREF_SSC_SOURCE_ENABLE;
8944
8945                 if (intel_panel_use_ssc(dev_priv) && can_ssc)
8946                         final |= DREF_SSC1_ENABLE;
8947
8948                 if (has_cpu_edp) {
8949                         if (intel_panel_use_ssc(dev_priv) && can_ssc)
8950                                 final |= DREF_CPU_SOURCE_OUTPUT_DOWNSPREAD;
8951                         else
8952                                 final |= DREF_CPU_SOURCE_OUTPUT_NONSPREAD;
8953                 } else
8954                         final |= DREF_CPU_SOURCE_OUTPUT_DISABLE;
8955         } else if (using_ssc_source) {
8956                 final |= DREF_SSC_SOURCE_ENABLE;
8957                 final |= DREF_SSC1_ENABLE;
8958         }
8959
8960         if (final == val)
8961                 return;
8962
8963         /* Always enable nonspread source */
8964         val &= ~DREF_NONSPREAD_SOURCE_MASK;
8965
8966         if (has_ck505)
8967                 val |= DREF_NONSPREAD_CK505_ENABLE;
8968         else
8969                 val |= DREF_NONSPREAD_SOURCE_ENABLE;
8970
8971         if (has_panel) {
8972                 val &= ~DREF_SSC_SOURCE_MASK;
8973                 val |= DREF_SSC_SOURCE_ENABLE;
8974
8975                 /* SSC must be turned on before enabling the CPU output  */
8976                 if (intel_panel_use_ssc(dev_priv) && can_ssc) {
8977                         DRM_DEBUG_KMS("Using SSC on panel\n");
8978                         val |= DREF_SSC1_ENABLE;
8979                 } else
8980                         val &= ~DREF_SSC1_ENABLE;
8981
8982                 /* Get SSC going before enabling the outputs */
8983                 I915_WRITE(PCH_DREF_CONTROL, val);
8984                 POSTING_READ(PCH_DREF_CONTROL);
8985                 udelay(200);
8986
8987                 val &= ~DREF_CPU_SOURCE_OUTPUT_MASK;
8988
8989                 /* Enable CPU source on CPU attached eDP */
8990                 if (has_cpu_edp) {
8991                         if (intel_panel_use_ssc(dev_priv) && can_ssc) {
8992                                 DRM_DEBUG_KMS("Using SSC on eDP\n");
8993                                 val |= DREF_CPU_SOURCE_OUTPUT_DOWNSPREAD;
8994                         } else
8995                                 val |= DREF_CPU_SOURCE_OUTPUT_NONSPREAD;
8996                 } else
8997                         val |= DREF_CPU_SOURCE_OUTPUT_DISABLE;
8998
8999                 I915_WRITE(PCH_DREF_CONTROL, val);
9000                 POSTING_READ(PCH_DREF_CONTROL);
9001                 udelay(200);
9002         } else {
9003                 DRM_DEBUG_KMS("Disabling CPU source output\n");
9004
9005                 val &= ~DREF_CPU_SOURCE_OUTPUT_MASK;
9006
9007                 /* Turn off CPU output */
9008                 val |= DREF_CPU_SOURCE_OUTPUT_DISABLE;
9009
9010                 I915_WRITE(PCH_DREF_CONTROL, val);
9011                 POSTING_READ(PCH_DREF_CONTROL);
9012                 udelay(200);
9013
9014                 if (!using_ssc_source) {
9015                         DRM_DEBUG_KMS("Disabling SSC source\n");
9016
9017                         /* Turn off the SSC source */
9018                         val &= ~DREF_SSC_SOURCE_MASK;
9019                         val |= DREF_SSC_SOURCE_DISABLE;
9020
9021                         /* Turn off SSC1 */
9022                         val &= ~DREF_SSC1_ENABLE;
9023
9024                         I915_WRITE(PCH_DREF_CONTROL, val);
9025                         POSTING_READ(PCH_DREF_CONTROL);
9026                         udelay(200);
9027                 }
9028         }
9029
9030         BUG_ON(val != final);
9031 }
9032
9033 static void lpt_reset_fdi_mphy(struct drm_i915_private *dev_priv)
9034 {
9035         u32 tmp;
9036
9037         tmp = I915_READ(SOUTH_CHICKEN2);
9038         tmp |= FDI_MPHY_IOSFSB_RESET_CTL;
9039         I915_WRITE(SOUTH_CHICKEN2, tmp);
9040
9041         if (wait_for_us(I915_READ(SOUTH_CHICKEN2) &
9042                         FDI_MPHY_IOSFSB_RESET_STATUS, 100))
9043                 DRM_ERROR("FDI mPHY reset assert timeout\n");
9044
9045         tmp = I915_READ(SOUTH_CHICKEN2);
9046         tmp &= ~FDI_MPHY_IOSFSB_RESET_CTL;
9047         I915_WRITE(SOUTH_CHICKEN2, tmp);
9048
9049         if (wait_for_us((I915_READ(SOUTH_CHICKEN2) &
9050                          FDI_MPHY_IOSFSB_RESET_STATUS) == 0, 100))
9051                 DRM_ERROR("FDI mPHY reset de-assert timeout\n");
9052 }
9053
9054 /* WaMPhyProgramming:hsw */
9055 static void lpt_program_fdi_mphy(struct drm_i915_private *dev_priv)
9056 {
9057         u32 tmp;
9058
9059         tmp = intel_sbi_read(dev_priv, 0x8008, SBI_MPHY);
9060         tmp &= ~(0xFF << 24);
9061         tmp |= (0x12 << 24);
9062         intel_sbi_write(dev_priv, 0x8008, tmp, SBI_MPHY);
9063
9064         tmp = intel_sbi_read(dev_priv, 0x2008, SBI_MPHY);
9065         tmp |= (1 << 11);
9066         intel_sbi_write(dev_priv, 0x2008, tmp, SBI_MPHY);
9067
9068         tmp = intel_sbi_read(dev_priv, 0x2108, SBI_MPHY);
9069         tmp |= (1 << 11);
9070         intel_sbi_write(dev_priv, 0x2108, tmp, SBI_MPHY);
9071
9072         tmp = intel_sbi_read(dev_priv, 0x206C, SBI_MPHY);
9073         tmp |= (1 << 24) | (1 << 21) | (1 << 18);
9074         intel_sbi_write(dev_priv, 0x206C, tmp, SBI_MPHY);
9075
9076         tmp = intel_sbi_read(dev_priv, 0x216C, SBI_MPHY);
9077         tmp |= (1 << 24) | (1 << 21) | (1 << 18);
9078         intel_sbi_write(dev_priv, 0x216C, tmp, SBI_MPHY);
9079
9080         tmp = intel_sbi_read(dev_priv, 0x2080, SBI_MPHY);
9081         tmp &= ~(7 << 13);
9082         tmp |= (5 << 13);
9083         intel_sbi_write(dev_priv, 0x2080, tmp, SBI_MPHY);
9084
9085         tmp = intel_sbi_read(dev_priv, 0x2180, SBI_MPHY);
9086         tmp &= ~(7 << 13);
9087         tmp |= (5 << 13);
9088         intel_sbi_write(dev_priv, 0x2180, tmp, SBI_MPHY);
9089
9090         tmp = intel_sbi_read(dev_priv, 0x208C, SBI_MPHY);
9091         tmp &= ~0xFF;
9092         tmp |= 0x1C;
9093         intel_sbi_write(dev_priv, 0x208C, tmp, SBI_MPHY);
9094
9095         tmp = intel_sbi_read(dev_priv, 0x218C, SBI_MPHY);
9096         tmp &= ~0xFF;
9097         tmp |= 0x1C;
9098         intel_sbi_write(dev_priv, 0x218C, tmp, SBI_MPHY);
9099
9100         tmp = intel_sbi_read(dev_priv, 0x2098, SBI_MPHY);
9101         tmp &= ~(0xFF << 16);
9102         tmp |= (0x1C << 16);
9103         intel_sbi_write(dev_priv, 0x2098, tmp, SBI_MPHY);
9104
9105         tmp = intel_sbi_read(dev_priv, 0x2198, SBI_MPHY);
9106         tmp &= ~(0xFF << 16);
9107         tmp |= (0x1C << 16);
9108         intel_sbi_write(dev_priv, 0x2198, tmp, SBI_MPHY);
9109
9110         tmp = intel_sbi_read(dev_priv, 0x20C4, SBI_MPHY);
9111         tmp |= (1 << 27);
9112         intel_sbi_write(dev_priv, 0x20C4, tmp, SBI_MPHY);
9113
9114         tmp = intel_sbi_read(dev_priv, 0x21C4, SBI_MPHY);
9115         tmp |= (1 << 27);
9116         intel_sbi_write(dev_priv, 0x21C4, tmp, SBI_MPHY);
9117
9118         tmp = intel_sbi_read(dev_priv, 0x20EC, SBI_MPHY);
9119         tmp &= ~(0xF << 28);
9120         tmp |= (4 << 28);
9121         intel_sbi_write(dev_priv, 0x20EC, tmp, SBI_MPHY);
9122
9123         tmp = intel_sbi_read(dev_priv, 0x21EC, SBI_MPHY);
9124         tmp &= ~(0xF << 28);
9125         tmp |= (4 << 28);
9126         intel_sbi_write(dev_priv, 0x21EC, tmp, SBI_MPHY);
9127 }
9128
9129 /* Implements 3 different sequences from BSpec chapter "Display iCLK
9130  * Programming" based on the parameters passed:
9131  * - Sequence to enable CLKOUT_DP
9132  * - Sequence to enable CLKOUT_DP without spread
9133  * - Sequence to enable CLKOUT_DP for FDI usage and configure PCH FDI I/O
9134  */
9135 static void lpt_enable_clkout_dp(struct drm_i915_private *dev_priv,
9136                                  bool with_spread, bool with_fdi)
9137 {
9138         u32 reg, tmp;
9139
9140         if (WARN(with_fdi && !with_spread, "FDI requires downspread\n"))
9141                 with_spread = true;
9142         if (WARN(HAS_PCH_LPT_LP(dev_priv) &&
9143             with_fdi, "LP PCH doesn't have FDI\n"))
9144                 with_fdi = false;
9145
9146         mutex_lock(&dev_priv->sb_lock);
9147
9148         tmp = intel_sbi_read(dev_priv, SBI_SSCCTL, SBI_ICLK);
9149         tmp &= ~SBI_SSCCTL_DISABLE;
9150         tmp |= SBI_SSCCTL_PATHALT;
9151         intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
9152
9153         udelay(24);
9154
9155         if (with_spread) {
9156                 tmp = intel_sbi_read(dev_priv, SBI_SSCCTL, SBI_ICLK);
9157                 tmp &= ~SBI_SSCCTL_PATHALT;
9158                 intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
9159
9160                 if (with_fdi) {
9161                         lpt_reset_fdi_mphy(dev_priv);
9162                         lpt_program_fdi_mphy(dev_priv);
9163                 }
9164         }
9165
9166         reg = HAS_PCH_LPT_LP(dev_priv) ? SBI_GEN0 : SBI_DBUFF0;
9167         tmp = intel_sbi_read(dev_priv, reg, SBI_ICLK);
9168         tmp |= SBI_GEN0_CFG_BUFFENABLE_DISABLE;
9169         intel_sbi_write(dev_priv, reg, tmp, SBI_ICLK);
9170
9171         mutex_unlock(&dev_priv->sb_lock);
9172 }
9173
9174 /* Sequence to disable CLKOUT_DP */
9175 void lpt_disable_clkout_dp(struct drm_i915_private *dev_priv)
9176 {
9177         u32 reg, tmp;
9178
9179         mutex_lock(&dev_priv->sb_lock);
9180
9181         reg = HAS_PCH_LPT_LP(dev_priv) ? SBI_GEN0 : SBI_DBUFF0;
9182         tmp = intel_sbi_read(dev_priv, reg, SBI_ICLK);
9183         tmp &= ~SBI_GEN0_CFG_BUFFENABLE_DISABLE;
9184         intel_sbi_write(dev_priv, reg, tmp, SBI_ICLK);
9185
9186         tmp = intel_sbi_read(dev_priv, SBI_SSCCTL, SBI_ICLK);
9187         if (!(tmp & SBI_SSCCTL_DISABLE)) {
9188                 if (!(tmp & SBI_SSCCTL_PATHALT)) {
9189                         tmp |= SBI_SSCCTL_PATHALT;
9190                         intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
9191                         udelay(32);
9192                 }
9193                 tmp |= SBI_SSCCTL_DISABLE;
9194                 intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
9195         }
9196
9197         mutex_unlock(&dev_priv->sb_lock);
9198 }
9199
9200 #define BEND_IDX(steps) ((50 + (steps)) / 5)
9201
9202 static const u16 sscdivintphase[] = {
9203         [BEND_IDX( 50)] = 0x3B23,
9204         [BEND_IDX( 45)] = 0x3B23,
9205         [BEND_IDX( 40)] = 0x3C23,
9206         [BEND_IDX( 35)] = 0x3C23,
9207         [BEND_IDX( 30)] = 0x3D23,
9208         [BEND_IDX( 25)] = 0x3D23,
9209         [BEND_IDX( 20)] = 0x3E23,
9210         [BEND_IDX( 15)] = 0x3E23,
9211         [BEND_IDX( 10)] = 0x3F23,
9212         [BEND_IDX(  5)] = 0x3F23,
9213         [BEND_IDX(  0)] = 0x0025,
9214         [BEND_IDX( -5)] = 0x0025,
9215         [BEND_IDX(-10)] = 0x0125,
9216         [BEND_IDX(-15)] = 0x0125,
9217         [BEND_IDX(-20)] = 0x0225,
9218         [BEND_IDX(-25)] = 0x0225,
9219         [BEND_IDX(-30)] = 0x0325,
9220         [BEND_IDX(-35)] = 0x0325,
9221         [BEND_IDX(-40)] = 0x0425,
9222         [BEND_IDX(-45)] = 0x0425,
9223         [BEND_IDX(-50)] = 0x0525,
9224 };
9225
9226 /*
9227  * Bend CLKOUT_DP
9228  * steps -50 to 50 inclusive, in steps of 5
9229  * < 0 slow down the clock, > 0 speed up the clock, 0 == no bend (135MHz)
9230  * change in clock period = -(steps / 10) * 5.787 ps
9231  */
9232 static void lpt_bend_clkout_dp(struct drm_i915_private *dev_priv, int steps)
9233 {
9234         u32 tmp;
9235         int idx = BEND_IDX(steps);
9236
9237         if (WARN_ON(steps % 5 != 0))
9238                 return;
9239
9240         if (WARN_ON(idx >= ARRAY_SIZE(sscdivintphase)))
9241                 return;
9242
9243         mutex_lock(&dev_priv->sb_lock);
9244
9245         if (steps % 10 != 0)
9246                 tmp = 0xAAAAAAAB;
9247         else
9248                 tmp = 0x00000000;
9249         intel_sbi_write(dev_priv, SBI_SSCDITHPHASE, tmp, SBI_ICLK);
9250
9251         tmp = intel_sbi_read(dev_priv, SBI_SSCDIVINTPHASE, SBI_ICLK);
9252         tmp &= 0xffff0000;
9253         tmp |= sscdivintphase[idx];
9254         intel_sbi_write(dev_priv, SBI_SSCDIVINTPHASE, tmp, SBI_ICLK);
9255
9256         mutex_unlock(&dev_priv->sb_lock);
9257 }
9258
9259 #undef BEND_IDX
9260
9261 static bool spll_uses_pch_ssc(struct drm_i915_private *dev_priv)
9262 {
9263         u32 fuse_strap = I915_READ(FUSE_STRAP);
9264         u32 ctl = I915_READ(SPLL_CTL);
9265
9266         if ((ctl & SPLL_PLL_ENABLE) == 0)
9267                 return false;
9268
9269         if ((ctl & SPLL_REF_MASK) == SPLL_REF_MUXED_SSC &&
9270             (fuse_strap & HSW_CPU_SSC_ENABLE) == 0)
9271                 return true;
9272
9273         if (IS_BROADWELL(dev_priv) &&
9274             (ctl & SPLL_REF_MASK) == SPLL_REF_PCH_SSC_BDW)
9275                 return true;
9276
9277         return false;
9278 }
9279
9280 static bool wrpll_uses_pch_ssc(struct drm_i915_private *dev_priv,
9281                                enum intel_dpll_id id)
9282 {
9283         u32 fuse_strap = I915_READ(FUSE_STRAP);
9284         u32 ctl = I915_READ(WRPLL_CTL(id));
9285
9286         if ((ctl & WRPLL_PLL_ENABLE) == 0)
9287                 return false;
9288
9289         if ((ctl & WRPLL_REF_MASK) == WRPLL_REF_PCH_SSC)
9290                 return true;
9291
9292         if ((IS_BROADWELL(dev_priv) || IS_HSW_ULT(dev_priv)) &&
9293             (ctl & WRPLL_REF_MASK) == WRPLL_REF_MUXED_SSC_BDW &&
9294             (fuse_strap & HSW_CPU_SSC_ENABLE) == 0)
9295                 return true;
9296
9297         return false;
9298 }
9299
9300 static void lpt_init_pch_refclk(struct drm_i915_private *dev_priv)
9301 {
9302         struct intel_encoder *encoder;
9303         bool pch_ssc_in_use = false;
9304         bool has_fdi = false;
9305
9306         for_each_intel_encoder(&dev_priv->drm, encoder) {
9307                 switch (encoder->type) {
9308                 case INTEL_OUTPUT_ANALOG:
9309                         has_fdi = true;
9310                         break;
9311                 default:
9312                         break;
9313                 }
9314         }
9315
9316         /*
9317          * The BIOS may have decided to use the PCH SSC
9318          * reference so we must not disable it until the
9319          * relevant PLLs have stopped relying on it. We'll
9320          * just leave the PCH SSC reference enabled in case
9321          * any active PLL is using it. It will get disabled
9322          * after runtime suspend if we don't have FDI.
9323          *
9324          * TODO: Move the whole reference clock handling
9325          * to the modeset sequence proper so that we can
9326          * actually enable/disable/reconfigure these things
9327          * safely. To do that we need to introduce a real
9328          * clock hierarchy. That would also allow us to do
9329          * clock bending finally.
9330          */
9331         if (spll_uses_pch_ssc(dev_priv)) {
9332                 DRM_DEBUG_KMS("SPLL using PCH SSC\n");
9333                 pch_ssc_in_use = true;
9334         }
9335
9336         if (wrpll_uses_pch_ssc(dev_priv, DPLL_ID_WRPLL1)) {
9337                 DRM_DEBUG_KMS("WRPLL1 using PCH SSC\n");
9338                 pch_ssc_in_use = true;
9339         }
9340
9341         if (wrpll_uses_pch_ssc(dev_priv, DPLL_ID_WRPLL2)) {
9342                 DRM_DEBUG_KMS("WRPLL2 using PCH SSC\n");
9343                 pch_ssc_in_use = true;
9344         }
9345
9346         if (pch_ssc_in_use)
9347                 return;
9348
9349         if (has_fdi) {
9350                 lpt_bend_clkout_dp(dev_priv, 0);
9351                 lpt_enable_clkout_dp(dev_priv, true, true);
9352         } else {
9353                 lpt_disable_clkout_dp(dev_priv);
9354         }
9355 }
9356
9357 /*
9358  * Initialize reference clocks when the driver loads
9359  */
9360 void intel_init_pch_refclk(struct drm_i915_private *dev_priv)
9361 {
9362         if (HAS_PCH_IBX(dev_priv) || HAS_PCH_CPT(dev_priv))
9363                 ironlake_init_pch_refclk(dev_priv);
9364         else if (HAS_PCH_LPT(dev_priv))
9365                 lpt_init_pch_refclk(dev_priv);
9366 }
9367
9368 static void ironlake_set_pipeconf(const struct intel_crtc_state *crtc_state)
9369 {
9370         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
9371         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
9372         enum pipe pipe = crtc->pipe;
9373         u32 val;
9374
9375         val = 0;
9376
9377         switch (crtc_state->pipe_bpp) {
9378         case 18:
9379                 val |= PIPECONF_6BPC;
9380                 break;
9381         case 24:
9382                 val |= PIPECONF_8BPC;
9383                 break;
9384         case 30:
9385                 val |= PIPECONF_10BPC;
9386                 break;
9387         case 36:
9388                 val |= PIPECONF_12BPC;
9389                 break;
9390         default:
9391                 /* Case prevented by intel_choose_pipe_bpp_dither. */
9392                 BUG();
9393         }
9394
9395         if (crtc_state->dither)
9396                 val |= (PIPECONF_DITHER_EN | PIPECONF_DITHER_TYPE_SP);
9397
9398         if (crtc_state->base.adjusted_mode.flags & DRM_MODE_FLAG_INTERLACE)
9399                 val |= PIPECONF_INTERLACED_ILK;
9400         else
9401                 val |= PIPECONF_PROGRESSIVE;
9402
9403         if (crtc_state->limited_color_range)
9404                 val |= PIPECONF_COLOR_RANGE_SELECT;
9405
9406         val |= PIPECONF_GAMMA_MODE(crtc_state->gamma_mode);
9407
9408         I915_WRITE(PIPECONF(pipe), val);
9409         POSTING_READ(PIPECONF(pipe));
9410 }
9411
9412 static void haswell_set_pipeconf(const struct intel_crtc_state *crtc_state)
9413 {
9414         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
9415         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
9416         enum transcoder cpu_transcoder = crtc_state->cpu_transcoder;
9417         u32 val = 0;
9418
9419         if (IS_HASWELL(dev_priv) && crtc_state->dither)
9420                 val |= (PIPECONF_DITHER_EN | PIPECONF_DITHER_TYPE_SP);
9421
9422         if (crtc_state->base.adjusted_mode.flags & DRM_MODE_FLAG_INTERLACE)
9423                 val |= PIPECONF_INTERLACED_ILK;
9424         else
9425                 val |= PIPECONF_PROGRESSIVE;
9426
9427         I915_WRITE(PIPECONF(cpu_transcoder), val);
9428         POSTING_READ(PIPECONF(cpu_transcoder));
9429 }
9430
9431 static void bdw_set_pipemisc(const struct intel_crtc_state *crtc_state)
9432 {
9433         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
9434         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
9435         u32 val = 0;
9436
9437         switch (crtc_state->pipe_bpp) {
9438         case 18:
9439                 val |= PIPEMISC_DITHER_6_BPC;
9440                 break;
9441         case 24:
9442                 val |= PIPEMISC_DITHER_8_BPC;
9443                 break;
9444         case 30:
9445                 val |= PIPEMISC_DITHER_10_BPC;
9446                 break;
9447         case 36:
9448                 val |= PIPEMISC_DITHER_12_BPC;
9449                 break;
9450         default:
9451                 MISSING_CASE(crtc_state->pipe_bpp);
9452                 break;
9453         }
9454
9455         if (crtc_state->dither)
9456                 val |= PIPEMISC_DITHER_ENABLE | PIPEMISC_DITHER_TYPE_SP;
9457
9458         if (crtc_state->output_format == INTEL_OUTPUT_FORMAT_YCBCR420 ||
9459             crtc_state->output_format == INTEL_OUTPUT_FORMAT_YCBCR444)
9460                 val |= PIPEMISC_OUTPUT_COLORSPACE_YUV;
9461
9462         if (crtc_state->output_format == INTEL_OUTPUT_FORMAT_YCBCR420)
9463                 val |= PIPEMISC_YUV420_ENABLE |
9464                         PIPEMISC_YUV420_MODE_FULL_BLEND;
9465
9466         if (INTEL_GEN(dev_priv) >= 11 &&
9467             (crtc_state->active_planes & ~(icl_hdr_plane_mask() |
9468                                            BIT(PLANE_CURSOR))) == 0)
9469                 val |= PIPEMISC_HDR_MODE_PRECISION;
9470
9471         I915_WRITE(PIPEMISC(crtc->pipe), val);
9472 }
9473
9474 int bdw_get_pipemisc_bpp(struct intel_crtc *crtc)
9475 {
9476         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
9477         u32 tmp;
9478
9479         tmp = I915_READ(PIPEMISC(crtc->pipe));
9480
9481         switch (tmp & PIPEMISC_DITHER_BPC_MASK) {
9482         case PIPEMISC_DITHER_6_BPC:
9483                 return 18;
9484         case PIPEMISC_DITHER_8_BPC:
9485                 return 24;
9486         case PIPEMISC_DITHER_10_BPC:
9487                 return 30;
9488         case PIPEMISC_DITHER_12_BPC:
9489                 return 36;
9490         default:
9491                 MISSING_CASE(tmp);
9492                 return 0;
9493         }
9494 }
9495
9496 int ironlake_get_lanes_required(int target_clock, int link_bw, int bpp)
9497 {
9498         /*
9499          * Account for spread spectrum to avoid
9500          * oversubscribing the link. Max center spread
9501          * is 2.5%; use 5% for safety's sake.
9502          */
9503         u32 bps = target_clock * bpp * 21 / 20;
9504         return DIV_ROUND_UP(bps, link_bw * 8);
9505 }
9506
9507 static bool ironlake_needs_fb_cb_tune(struct dpll *dpll, int factor)
9508 {
9509         return i9xx_dpll_compute_m(dpll) < factor * dpll->n;
9510 }
9511
9512 static void ironlake_compute_dpll(struct intel_crtc *crtc,
9513                                   struct intel_crtc_state *crtc_state,
9514                                   struct dpll *reduced_clock)
9515 {
9516         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
9517         u32 dpll, fp, fp2;
9518         int factor;
9519
9520         /* Enable autotuning of the PLL clock (if permissible) */
9521         factor = 21;
9522         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
9523                 if ((intel_panel_use_ssc(dev_priv) &&
9524                      dev_priv->vbt.lvds_ssc_freq == 100000) ||
9525                     (HAS_PCH_IBX(dev_priv) &&
9526                      intel_is_dual_link_lvds(dev_priv)))
9527                         factor = 25;
9528         } else if (crtc_state->sdvo_tv_clock) {
9529                 factor = 20;
9530         }
9531
9532         fp = i9xx_dpll_compute_fp(&crtc_state->dpll);
9533
9534         if (ironlake_needs_fb_cb_tune(&crtc_state->dpll, factor))
9535                 fp |= FP_CB_TUNE;
9536
9537         if (reduced_clock) {
9538                 fp2 = i9xx_dpll_compute_fp(reduced_clock);
9539
9540                 if (reduced_clock->m < factor * reduced_clock->n)
9541                         fp2 |= FP_CB_TUNE;
9542         } else {
9543                 fp2 = fp;
9544         }
9545
9546         dpll = 0;
9547
9548         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS))
9549                 dpll |= DPLLB_MODE_LVDS;
9550         else
9551                 dpll |= DPLLB_MODE_DAC_SERIAL;
9552
9553         dpll |= (crtc_state->pixel_multiplier - 1)
9554                 << PLL_REF_SDVO_HDMI_MULTIPLIER_SHIFT;
9555
9556         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_SDVO) ||
9557             intel_crtc_has_type(crtc_state, INTEL_OUTPUT_HDMI))
9558                 dpll |= DPLL_SDVO_HIGH_SPEED;
9559
9560         if (intel_crtc_has_dp_encoder(crtc_state))
9561                 dpll |= DPLL_SDVO_HIGH_SPEED;
9562
9563         /*
9564          * The high speed IO clock is only really required for
9565          * SDVO/HDMI/DP, but we also enable it for CRT to make it
9566          * possible to share the DPLL between CRT and HDMI. Enabling
9567          * the clock needlessly does no real harm, except use up a
9568          * bit of power potentially.
9569          *
9570          * We'll limit this to IVB with 3 pipes, since it has only two
9571          * DPLLs and so DPLL sharing is the only way to get three pipes
9572          * driving PCH ports at the same time. On SNB we could do this,
9573          * and potentially avoid enabling the second DPLL, but it's not
9574          * clear if it''s a win or loss power wise. No point in doing
9575          * this on ILK at all since it has a fixed DPLL<->pipe mapping.
9576          */
9577         if (INTEL_INFO(dev_priv)->num_pipes == 3 &&
9578             intel_crtc_has_type(crtc_state, INTEL_OUTPUT_ANALOG))
9579                 dpll |= DPLL_SDVO_HIGH_SPEED;
9580
9581         /* compute bitmask from p1 value */
9582         dpll |= (1 << (crtc_state->dpll.p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT;
9583         /* also FPA1 */
9584         dpll |= (1 << (crtc_state->dpll.p1 - 1)) << DPLL_FPA1_P1_POST_DIV_SHIFT;
9585
9586         switch (crtc_state->dpll.p2) {
9587         case 5:
9588                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_5;
9589                 break;
9590         case 7:
9591                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_7;
9592                 break;
9593         case 10:
9594                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_10;
9595                 break;
9596         case 14:
9597                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_14;
9598                 break;
9599         }
9600
9601         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS) &&
9602             intel_panel_use_ssc(dev_priv))
9603                 dpll |= PLLB_REF_INPUT_SPREADSPECTRUMIN;
9604         else
9605                 dpll |= PLL_REF_INPUT_DREFCLK;
9606
9607         dpll |= DPLL_VCO_ENABLE;
9608
9609         crtc_state->dpll_hw_state.dpll = dpll;
9610         crtc_state->dpll_hw_state.fp0 = fp;
9611         crtc_state->dpll_hw_state.fp1 = fp2;
9612 }
9613
9614 static int ironlake_crtc_compute_clock(struct intel_crtc *crtc,
9615                                        struct intel_crtc_state *crtc_state)
9616 {
9617         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
9618         struct intel_atomic_state *state =
9619                 to_intel_atomic_state(crtc_state->base.state);
9620         const struct intel_limit *limit;
9621         int refclk = 120000;
9622
9623         memset(&crtc_state->dpll_hw_state, 0,
9624                sizeof(crtc_state->dpll_hw_state));
9625
9626         /* CPU eDP is the only output that doesn't need a PCH PLL of its own. */
9627         if (!crtc_state->has_pch_encoder)
9628                 return 0;
9629
9630         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
9631                 if (intel_panel_use_ssc(dev_priv)) {
9632                         DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n",
9633                                       dev_priv->vbt.lvds_ssc_freq);
9634                         refclk = dev_priv->vbt.lvds_ssc_freq;
9635                 }
9636
9637                 if (intel_is_dual_link_lvds(dev_priv)) {
9638                         if (refclk == 100000)
9639                                 limit = &intel_limits_ironlake_dual_lvds_100m;
9640                         else
9641                                 limit = &intel_limits_ironlake_dual_lvds;
9642                 } else {
9643                         if (refclk == 100000)
9644                                 limit = &intel_limits_ironlake_single_lvds_100m;
9645                         else
9646                                 limit = &intel_limits_ironlake_single_lvds;
9647                 }
9648         } else {
9649                 limit = &intel_limits_ironlake_dac;
9650         }
9651
9652         if (!crtc_state->clock_set &&
9653             !g4x_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
9654                                 refclk, NULL, &crtc_state->dpll)) {
9655                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
9656                 return -EINVAL;
9657         }
9658
9659         ironlake_compute_dpll(crtc, crtc_state, NULL);
9660
9661         if (!intel_reserve_shared_dplls(state, crtc, NULL)) {
9662                 DRM_DEBUG_KMS("failed to find PLL for pipe %c\n",
9663                               pipe_name(crtc->pipe));
9664                 return -EINVAL;
9665         }
9666
9667         return 0;
9668 }
9669
9670 static void intel_pch_transcoder_get_m_n(struct intel_crtc *crtc,
9671                                          struct intel_link_m_n *m_n)
9672 {
9673         struct drm_device *dev = crtc->base.dev;
9674         struct drm_i915_private *dev_priv = to_i915(dev);
9675         enum pipe pipe = crtc->pipe;
9676
9677         m_n->link_m = I915_READ(PCH_TRANS_LINK_M1(pipe));
9678         m_n->link_n = I915_READ(PCH_TRANS_LINK_N1(pipe));
9679         m_n->gmch_m = I915_READ(PCH_TRANS_DATA_M1(pipe))
9680                 & ~TU_SIZE_MASK;
9681         m_n->gmch_n = I915_READ(PCH_TRANS_DATA_N1(pipe));
9682         m_n->tu = ((I915_READ(PCH_TRANS_DATA_M1(pipe))
9683                     & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
9684 }
9685
9686 static void intel_cpu_transcoder_get_m_n(struct intel_crtc *crtc,
9687                                          enum transcoder transcoder,
9688                                          struct intel_link_m_n *m_n,
9689                                          struct intel_link_m_n *m2_n2)
9690 {
9691         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
9692         enum pipe pipe = crtc->pipe;
9693
9694         if (INTEL_GEN(dev_priv) >= 5) {
9695                 m_n->link_m = I915_READ(PIPE_LINK_M1(transcoder));
9696                 m_n->link_n = I915_READ(PIPE_LINK_N1(transcoder));
9697                 m_n->gmch_m = I915_READ(PIPE_DATA_M1(transcoder))
9698                         & ~TU_SIZE_MASK;
9699                 m_n->gmch_n = I915_READ(PIPE_DATA_N1(transcoder));
9700                 m_n->tu = ((I915_READ(PIPE_DATA_M1(transcoder))
9701                             & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
9702
9703                 if (m2_n2 && transcoder_has_m2_n2(dev_priv, transcoder)) {
9704                         m2_n2->link_m = I915_READ(PIPE_LINK_M2(transcoder));
9705                         m2_n2->link_n = I915_READ(PIPE_LINK_N2(transcoder));
9706                         m2_n2->gmch_m = I915_READ(PIPE_DATA_M2(transcoder))
9707                                         & ~TU_SIZE_MASK;
9708                         m2_n2->gmch_n = I915_READ(PIPE_DATA_N2(transcoder));
9709                         m2_n2->tu = ((I915_READ(PIPE_DATA_M2(transcoder))
9710                                         & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
9711                 }
9712         } else {
9713                 m_n->link_m = I915_READ(PIPE_LINK_M_G4X(pipe));
9714                 m_n->link_n = I915_READ(PIPE_LINK_N_G4X(pipe));
9715                 m_n->gmch_m = I915_READ(PIPE_DATA_M_G4X(pipe))
9716                         & ~TU_SIZE_MASK;
9717                 m_n->gmch_n = I915_READ(PIPE_DATA_N_G4X(pipe));
9718                 m_n->tu = ((I915_READ(PIPE_DATA_M_G4X(pipe))
9719                             & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
9720         }
9721 }
9722
9723 void intel_dp_get_m_n(struct intel_crtc *crtc,
9724                       struct intel_crtc_state *pipe_config)
9725 {
9726         if (pipe_config->has_pch_encoder)
9727                 intel_pch_transcoder_get_m_n(crtc, &pipe_config->dp_m_n);
9728         else
9729                 intel_cpu_transcoder_get_m_n(crtc, pipe_config->cpu_transcoder,
9730                                              &pipe_config->dp_m_n,
9731                                              &pipe_config->dp_m2_n2);
9732 }
9733
9734 static void ironlake_get_fdi_m_n_config(struct intel_crtc *crtc,
9735                                         struct intel_crtc_state *pipe_config)
9736 {
9737         intel_cpu_transcoder_get_m_n(crtc, pipe_config->cpu_transcoder,
9738                                      &pipe_config->fdi_m_n, NULL);
9739 }
9740
9741 static void skylake_get_pfit_config(struct intel_crtc *crtc,
9742                                     struct intel_crtc_state *pipe_config)
9743 {
9744         struct drm_device *dev = crtc->base.dev;
9745         struct drm_i915_private *dev_priv = to_i915(dev);
9746         struct intel_crtc_scaler_state *scaler_state = &pipe_config->scaler_state;
9747         u32 ps_ctrl = 0;
9748         int id = -1;
9749         int i;
9750
9751         /* find scaler attached to this pipe */
9752         for (i = 0; i < crtc->num_scalers; i++) {
9753                 ps_ctrl = I915_READ(SKL_PS_CTRL(crtc->pipe, i));
9754                 if (ps_ctrl & PS_SCALER_EN && !(ps_ctrl & PS_PLANE_SEL_MASK)) {
9755                         id = i;
9756                         pipe_config->pch_pfit.enabled = true;
9757                         pipe_config->pch_pfit.pos = I915_READ(SKL_PS_WIN_POS(crtc->pipe, i));
9758                         pipe_config->pch_pfit.size = I915_READ(SKL_PS_WIN_SZ(crtc->pipe, i));
9759                         scaler_state->scalers[i].in_use = true;
9760                         break;
9761                 }
9762         }
9763
9764         scaler_state->scaler_id = id;
9765         if (id >= 0) {
9766                 scaler_state->scaler_users |= (1 << SKL_CRTC_INDEX);
9767         } else {
9768                 scaler_state->scaler_users &= ~(1 << SKL_CRTC_INDEX);
9769         }
9770 }
9771
9772 static void
9773 skylake_get_initial_plane_config(struct intel_crtc *crtc,
9774                                  struct intel_initial_plane_config *plane_config)
9775 {
9776         struct drm_device *dev = crtc->base.dev;
9777         struct drm_i915_private *dev_priv = to_i915(dev);
9778         struct intel_plane *plane = to_intel_plane(crtc->base.primary);
9779         enum plane_id plane_id = plane->id;
9780         enum pipe pipe;
9781         u32 val, base, offset, stride_mult, tiling, alpha;
9782         int fourcc, pixel_format;
9783         unsigned int aligned_height;
9784         struct drm_framebuffer *fb;
9785         struct intel_framebuffer *intel_fb;
9786
9787         if (!plane->get_hw_state(plane, &pipe))
9788                 return;
9789
9790         WARN_ON(pipe != crtc->pipe);
9791
9792         intel_fb = kzalloc(sizeof(*intel_fb), GFP_KERNEL);
9793         if (!intel_fb) {
9794                 DRM_DEBUG_KMS("failed to alloc fb\n");
9795                 return;
9796         }
9797
9798         fb = &intel_fb->base;
9799
9800         fb->dev = dev;
9801
9802         val = I915_READ(PLANE_CTL(pipe, plane_id));
9803
9804         if (INTEL_GEN(dev_priv) >= 11)
9805                 pixel_format = val & ICL_PLANE_CTL_FORMAT_MASK;
9806         else
9807                 pixel_format = val & PLANE_CTL_FORMAT_MASK;
9808
9809         if (INTEL_GEN(dev_priv) >= 10 || IS_GEMINILAKE(dev_priv)) {
9810                 alpha = I915_READ(PLANE_COLOR_CTL(pipe, plane_id));
9811                 alpha &= PLANE_COLOR_ALPHA_MASK;
9812         } else {
9813                 alpha = val & PLANE_CTL_ALPHA_MASK;
9814         }
9815
9816         fourcc = skl_format_to_fourcc(pixel_format,
9817                                       val & PLANE_CTL_ORDER_RGBX, alpha);
9818         fb->format = drm_format_info(fourcc);
9819
9820         tiling = val & PLANE_CTL_TILED_MASK;
9821         switch (tiling) {
9822         case PLANE_CTL_TILED_LINEAR:
9823                 fb->modifier = DRM_FORMAT_MOD_LINEAR;
9824                 break;
9825         case PLANE_CTL_TILED_X:
9826                 plane_config->tiling = I915_TILING_X;
9827                 fb->modifier = I915_FORMAT_MOD_X_TILED;
9828                 break;
9829         case PLANE_CTL_TILED_Y:
9830                 plane_config->tiling = I915_TILING_Y;
9831                 if (val & PLANE_CTL_RENDER_DECOMPRESSION_ENABLE)
9832                         fb->modifier = I915_FORMAT_MOD_Y_TILED_CCS;
9833                 else
9834                         fb->modifier = I915_FORMAT_MOD_Y_TILED;
9835                 break;
9836         case PLANE_CTL_TILED_YF:
9837                 if (val & PLANE_CTL_RENDER_DECOMPRESSION_ENABLE)
9838                         fb->modifier = I915_FORMAT_MOD_Yf_TILED_CCS;
9839                 else
9840                         fb->modifier = I915_FORMAT_MOD_Yf_TILED;
9841                 break;
9842         default:
9843                 MISSING_CASE(tiling);
9844                 goto error;
9845         }
9846
9847         /*
9848          * DRM_MODE_ROTATE_ is counter clockwise to stay compatible with Xrandr
9849          * while i915 HW rotation is clockwise, thats why this swapping.
9850          */
9851         switch (val & PLANE_CTL_ROTATE_MASK) {
9852         case PLANE_CTL_ROTATE_0:
9853                 plane_config->rotation = DRM_MODE_ROTATE_0;
9854                 break;
9855         case PLANE_CTL_ROTATE_90:
9856                 plane_config->rotation = DRM_MODE_ROTATE_270;
9857                 break;
9858         case PLANE_CTL_ROTATE_180:
9859                 plane_config->rotation = DRM_MODE_ROTATE_180;
9860                 break;
9861         case PLANE_CTL_ROTATE_270:
9862                 plane_config->rotation = DRM_MODE_ROTATE_90;
9863                 break;
9864         }
9865
9866         if (INTEL_GEN(dev_priv) >= 10 &&
9867             val & PLANE_CTL_FLIP_HORIZONTAL)
9868                 plane_config->rotation |= DRM_MODE_REFLECT_X;
9869
9870         base = I915_READ(PLANE_SURF(pipe, plane_id)) & 0xfffff000;
9871         plane_config->base = base;
9872
9873         offset = I915_READ(PLANE_OFFSET(pipe, plane_id));
9874
9875         val = I915_READ(PLANE_SIZE(pipe, plane_id));
9876         fb->height = ((val >> 16) & 0xfff) + 1;
9877         fb->width = ((val >> 0) & 0x1fff) + 1;
9878
9879         val = I915_READ(PLANE_STRIDE(pipe, plane_id));
9880         stride_mult = skl_plane_stride_mult(fb, 0, DRM_MODE_ROTATE_0);
9881         fb->pitches[0] = (val & 0x3ff) * stride_mult;
9882
9883         aligned_height = intel_fb_align_height(fb, 0, fb->height);
9884
9885         plane_config->size = fb->pitches[0] * aligned_height;
9886
9887         DRM_DEBUG_KMS("%s/%s with fb: size=%dx%d@%d, offset=%x, pitch %d, size 0x%x\n",
9888                       crtc->base.name, plane->base.name, fb->width, fb->height,
9889                       fb->format->cpp[0] * 8, base, fb->pitches[0],
9890                       plane_config->size);
9891
9892         plane_config->fb = intel_fb;
9893         return;
9894
9895 error:
9896         kfree(intel_fb);
9897 }
9898
9899 static void ironlake_get_pfit_config(struct intel_crtc *crtc,
9900                                      struct intel_crtc_state *pipe_config)
9901 {
9902         struct drm_device *dev = crtc->base.dev;
9903         struct drm_i915_private *dev_priv = to_i915(dev);
9904         u32 tmp;
9905
9906         tmp = I915_READ(PF_CTL(crtc->pipe));
9907
9908         if (tmp & PF_ENABLE) {
9909                 pipe_config->pch_pfit.enabled = true;
9910                 pipe_config->pch_pfit.pos = I915_READ(PF_WIN_POS(crtc->pipe));
9911                 pipe_config->pch_pfit.size = I915_READ(PF_WIN_SZ(crtc->pipe));
9912
9913                 /* We currently do not free assignements of panel fitters on
9914                  * ivb/hsw (since we don't use the higher upscaling modes which
9915                  * differentiates them) so just WARN about this case for now. */
9916                 if (IS_GEN(dev_priv, 7)) {
9917                         WARN_ON((tmp & PF_PIPE_SEL_MASK_IVB) !=
9918                                 PF_PIPE_SEL_IVB(crtc->pipe));
9919                 }
9920         }
9921 }
9922
9923 static bool ironlake_get_pipe_config(struct intel_crtc *crtc,
9924                                      struct intel_crtc_state *pipe_config)
9925 {
9926         struct drm_device *dev = crtc->base.dev;
9927         struct drm_i915_private *dev_priv = to_i915(dev);
9928         enum intel_display_power_domain power_domain;
9929         intel_wakeref_t wakeref;
9930         u32 tmp;
9931         bool ret;
9932
9933         power_domain = POWER_DOMAIN_PIPE(crtc->pipe);
9934         wakeref = intel_display_power_get_if_enabled(dev_priv, power_domain);
9935         if (!wakeref)
9936                 return false;
9937
9938         pipe_config->output_format = INTEL_OUTPUT_FORMAT_RGB;
9939         pipe_config->cpu_transcoder = (enum transcoder) crtc->pipe;
9940         pipe_config->shared_dpll = NULL;
9941
9942         ret = false;
9943         tmp = I915_READ(PIPECONF(crtc->pipe));
9944         if (!(tmp & PIPECONF_ENABLE))
9945                 goto out;
9946
9947         switch (tmp & PIPECONF_BPC_MASK) {
9948         case PIPECONF_6BPC:
9949                 pipe_config->pipe_bpp = 18;
9950                 break;
9951         case PIPECONF_8BPC:
9952                 pipe_config->pipe_bpp = 24;
9953                 break;
9954         case PIPECONF_10BPC:
9955                 pipe_config->pipe_bpp = 30;
9956                 break;
9957         case PIPECONF_12BPC:
9958                 pipe_config->pipe_bpp = 36;
9959                 break;
9960         default:
9961                 break;
9962         }
9963
9964         if (tmp & PIPECONF_COLOR_RANGE_SELECT)
9965                 pipe_config->limited_color_range = true;
9966
9967         pipe_config->gamma_mode = (tmp & PIPECONF_GAMMA_MODE_MASK_ILK) >>
9968                 PIPECONF_GAMMA_MODE_SHIFT;
9969
9970         pipe_config->csc_mode = I915_READ(PIPE_CSC_MODE(crtc->pipe));
9971
9972         i9xx_get_pipe_color_config(pipe_config);
9973         intel_color_get_config(pipe_config);
9974
9975         if (I915_READ(PCH_TRANSCONF(crtc->pipe)) & TRANS_ENABLE) {
9976                 struct intel_shared_dpll *pll;
9977                 enum intel_dpll_id pll_id;
9978
9979                 pipe_config->has_pch_encoder = true;
9980
9981                 tmp = I915_READ(FDI_RX_CTL(crtc->pipe));
9982                 pipe_config->fdi_lanes = ((FDI_DP_PORT_WIDTH_MASK & tmp) >>
9983                                           FDI_DP_PORT_WIDTH_SHIFT) + 1;
9984
9985                 ironlake_get_fdi_m_n_config(crtc, pipe_config);
9986
9987                 if (HAS_PCH_IBX(dev_priv)) {
9988                         /*
9989                          * The pipe->pch transcoder and pch transcoder->pll
9990                          * mapping is fixed.
9991                          */
9992                         pll_id = (enum intel_dpll_id) crtc->pipe;
9993                 } else {
9994                         tmp = I915_READ(PCH_DPLL_SEL);
9995                         if (tmp & TRANS_DPLLB_SEL(crtc->pipe))
9996                                 pll_id = DPLL_ID_PCH_PLL_B;
9997                         else
9998                                 pll_id= DPLL_ID_PCH_PLL_A;
9999                 }
10000
10001                 pipe_config->shared_dpll =
10002                         intel_get_shared_dpll_by_id(dev_priv, pll_id);
10003                 pll = pipe_config->shared_dpll;
10004
10005                 WARN_ON(!pll->info->funcs->get_hw_state(dev_priv, pll,
10006                                                 &pipe_config->dpll_hw_state));
10007
10008                 tmp = pipe_config->dpll_hw_state.dpll;
10009                 pipe_config->pixel_multiplier =
10010                         ((tmp & PLL_REF_SDVO_HDMI_MULTIPLIER_MASK)
10011                          >> PLL_REF_SDVO_HDMI_MULTIPLIER_SHIFT) + 1;
10012
10013                 ironlake_pch_clock_get(crtc, pipe_config);
10014         } else {
10015                 pipe_config->pixel_multiplier = 1;
10016         }
10017
10018         intel_get_pipe_timings(crtc, pipe_config);
10019         intel_get_pipe_src_size(crtc, pipe_config);
10020
10021         ironlake_get_pfit_config(crtc, pipe_config);
10022
10023         ret = true;
10024
10025 out:
10026         intel_display_power_put(dev_priv, power_domain, wakeref);
10027
10028         return ret;
10029 }
10030 static int haswell_crtc_compute_clock(struct intel_crtc *crtc,
10031                                       struct intel_crtc_state *crtc_state)
10032 {
10033         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
10034         struct intel_atomic_state *state =
10035                 to_intel_atomic_state(crtc_state->base.state);
10036
10037         if (!intel_crtc_has_type(crtc_state, INTEL_OUTPUT_DSI) ||
10038             INTEL_GEN(dev_priv) >= 11) {
10039                 struct intel_encoder *encoder =
10040                         intel_get_crtc_new_encoder(state, crtc_state);
10041
10042                 if (!intel_reserve_shared_dplls(state, crtc, encoder)) {
10043                         DRM_DEBUG_KMS("failed to find PLL for pipe %c\n",
10044                                       pipe_name(crtc->pipe));
10045                         return -EINVAL;
10046                 }
10047         }
10048
10049         return 0;
10050 }
10051
10052 static void cannonlake_get_ddi_pll(struct drm_i915_private *dev_priv,
10053                                    enum port port,
10054                                    struct intel_crtc_state *pipe_config)
10055 {
10056         enum intel_dpll_id id;
10057         u32 temp;
10058
10059         temp = I915_READ(DPCLKA_CFGCR0) & DPCLKA_CFGCR0_DDI_CLK_SEL_MASK(port);
10060         id = temp >> DPCLKA_CFGCR0_DDI_CLK_SEL_SHIFT(port);
10061
10062         if (WARN_ON(id < SKL_DPLL0 || id > SKL_DPLL2))
10063                 return;
10064
10065         pipe_config->shared_dpll = intel_get_shared_dpll_by_id(dev_priv, id);
10066 }
10067
10068 static void icelake_get_ddi_pll(struct drm_i915_private *dev_priv,
10069                                 enum port port,
10070                                 struct intel_crtc_state *pipe_config)
10071 {
10072         enum phy phy = intel_port_to_phy(dev_priv, port);
10073         enum icl_port_dpll_id port_dpll_id;
10074         enum intel_dpll_id id;
10075         u32 temp;
10076
10077         if (intel_phy_is_combo(dev_priv, phy)) {
10078                 temp = I915_READ(ICL_DPCLKA_CFGCR0) &
10079                         ICL_DPCLKA_CFGCR0_DDI_CLK_SEL_MASK(phy);
10080                 id = temp >> ICL_DPCLKA_CFGCR0_DDI_CLK_SEL_SHIFT(phy);
10081                 port_dpll_id = ICL_PORT_DPLL_DEFAULT;
10082         } else if (intel_phy_is_tc(dev_priv, phy)) {
10083                 u32 clk_sel = I915_READ(DDI_CLK_SEL(port)) & DDI_CLK_SEL_MASK;
10084
10085                 if (clk_sel == DDI_CLK_SEL_MG) {
10086                         id = icl_tc_port_to_pll_id(intel_port_to_tc(dev_priv,
10087                                                                     port));
10088                         port_dpll_id = ICL_PORT_DPLL_MG_PHY;
10089                 } else {
10090                         WARN_ON(clk_sel < DDI_CLK_SEL_TBT_162);
10091                         id = DPLL_ID_ICL_TBTPLL;
10092                         port_dpll_id = ICL_PORT_DPLL_DEFAULT;
10093                 }
10094         } else {
10095                 WARN(1, "Invalid port %x\n", port);
10096                 return;
10097         }
10098
10099         pipe_config->icl_port_dplls[port_dpll_id].pll =
10100                 intel_get_shared_dpll_by_id(dev_priv, id);
10101
10102         icl_set_active_port_dpll(pipe_config, port_dpll_id);
10103 }
10104
10105 static void bxt_get_ddi_pll(struct drm_i915_private *dev_priv,
10106                                 enum port port,
10107                                 struct intel_crtc_state *pipe_config)
10108 {
10109         enum intel_dpll_id id;
10110
10111         switch (port) {
10112         case PORT_A:
10113                 id = DPLL_ID_SKL_DPLL0;
10114                 break;
10115         case PORT_B:
10116                 id = DPLL_ID_SKL_DPLL1;
10117                 break;
10118         case PORT_C:
10119                 id = DPLL_ID_SKL_DPLL2;
10120                 break;
10121         default:
10122                 DRM_ERROR("Incorrect port type\n");
10123                 return;
10124         }
10125
10126         pipe_config->shared_dpll = intel_get_shared_dpll_by_id(dev_priv, id);
10127 }
10128
10129 static void skylake_get_ddi_pll(struct drm_i915_private *dev_priv,
10130                                 enum port port,
10131                                 struct intel_crtc_state *pipe_config)
10132 {
10133         enum intel_dpll_id id;
10134         u32 temp;
10135
10136         temp = I915_READ(DPLL_CTRL2) & DPLL_CTRL2_DDI_CLK_SEL_MASK(port);
10137         id = temp >> (port * 3 + 1);
10138
10139         if (WARN_ON(id < SKL_DPLL0 || id > SKL_DPLL3))
10140                 return;
10141
10142         pipe_config->shared_dpll = intel_get_shared_dpll_by_id(dev_priv, id);
10143 }
10144
10145 static void haswell_get_ddi_pll(struct drm_i915_private *dev_priv,
10146                                 enum port port,
10147                                 struct intel_crtc_state *pipe_config)
10148 {
10149         enum intel_dpll_id id;
10150         u32 ddi_pll_sel = I915_READ(PORT_CLK_SEL(port));
10151
10152         switch (ddi_pll_sel) {
10153         case PORT_CLK_SEL_WRPLL1:
10154                 id = DPLL_ID_WRPLL1;
10155                 break;
10156         case PORT_CLK_SEL_WRPLL2:
10157                 id = DPLL_ID_WRPLL2;
10158                 break;
10159         case PORT_CLK_SEL_SPLL:
10160                 id = DPLL_ID_SPLL;
10161                 break;
10162         case PORT_CLK_SEL_LCPLL_810:
10163                 id = DPLL_ID_LCPLL_810;
10164                 break;
10165         case PORT_CLK_SEL_LCPLL_1350:
10166                 id = DPLL_ID_LCPLL_1350;
10167                 break;
10168         case PORT_CLK_SEL_LCPLL_2700:
10169                 id = DPLL_ID_LCPLL_2700;
10170                 break;
10171         default:
10172                 MISSING_CASE(ddi_pll_sel);
10173                 /* fall through */
10174         case PORT_CLK_SEL_NONE:
10175                 return;
10176         }
10177
10178         pipe_config->shared_dpll = intel_get_shared_dpll_by_id(dev_priv, id);
10179 }
10180
10181 static bool hsw_get_transcoder_state(struct intel_crtc *crtc,
10182                                      struct intel_crtc_state *pipe_config,
10183                                      u64 *power_domain_mask,
10184                                      intel_wakeref_t *wakerefs)
10185 {
10186         struct drm_device *dev = crtc->base.dev;
10187         struct drm_i915_private *dev_priv = to_i915(dev);
10188         enum intel_display_power_domain power_domain;
10189         unsigned long panel_transcoder_mask = 0;
10190         unsigned long enabled_panel_transcoders = 0;
10191         enum transcoder panel_transcoder;
10192         intel_wakeref_t wf;
10193         u32 tmp;
10194
10195         if (INTEL_GEN(dev_priv) >= 11)
10196                 panel_transcoder_mask |=
10197                         BIT(TRANSCODER_DSI_0) | BIT(TRANSCODER_DSI_1);
10198
10199         if (HAS_TRANSCODER_EDP(dev_priv))
10200                 panel_transcoder_mask |= BIT(TRANSCODER_EDP);
10201
10202         /*
10203          * The pipe->transcoder mapping is fixed with the exception of the eDP
10204          * and DSI transcoders handled below.
10205          */
10206         pipe_config->cpu_transcoder = (enum transcoder) crtc->pipe;
10207
10208         /*
10209          * XXX: Do intel_display_power_get_if_enabled before reading this (for
10210          * consistency and less surprising code; it's in always on power).
10211          */
10212         for_each_set_bit(panel_transcoder,
10213                          &panel_transcoder_mask,
10214                          ARRAY_SIZE(INTEL_INFO(dev_priv)->trans_offsets)) {
10215                 bool force_thru = false;
10216                 enum pipe trans_pipe;
10217
10218                 tmp = I915_READ(TRANS_DDI_FUNC_CTL(panel_transcoder));
10219                 if (!(tmp & TRANS_DDI_FUNC_ENABLE))
10220                         continue;
10221
10222                 /*
10223                  * Log all enabled ones, only use the first one.
10224                  *
10225                  * FIXME: This won't work for two separate DSI displays.
10226                  */
10227                 enabled_panel_transcoders |= BIT(panel_transcoder);
10228                 if (enabled_panel_transcoders != BIT(panel_transcoder))
10229                         continue;
10230
10231                 switch (tmp & TRANS_DDI_EDP_INPUT_MASK) {
10232                 default:
10233                         WARN(1, "unknown pipe linked to transcoder %s\n",
10234                              transcoder_name(panel_transcoder));
10235                         /* fall through */
10236                 case TRANS_DDI_EDP_INPUT_A_ONOFF:
10237                         force_thru = true;
10238                         /* fall through */
10239                 case TRANS_DDI_EDP_INPUT_A_ON:
10240                         trans_pipe = PIPE_A;
10241                         break;
10242                 case TRANS_DDI_EDP_INPUT_B_ONOFF:
10243                         trans_pipe = PIPE_B;
10244                         break;
10245                 case TRANS_DDI_EDP_INPUT_C_ONOFF:
10246                         trans_pipe = PIPE_C;
10247                         break;
10248                 }
10249
10250                 if (trans_pipe == crtc->pipe) {
10251                         pipe_config->cpu_transcoder = panel_transcoder;
10252                         pipe_config->pch_pfit.force_thru = force_thru;
10253                 }
10254         }
10255
10256         /*
10257          * Valid combos: none, eDP, DSI0, DSI1, DSI0+DSI1
10258          */
10259         WARN_ON((enabled_panel_transcoders & BIT(TRANSCODER_EDP)) &&
10260                 enabled_panel_transcoders != BIT(TRANSCODER_EDP));
10261
10262         power_domain = POWER_DOMAIN_TRANSCODER(pipe_config->cpu_transcoder);
10263         WARN_ON(*power_domain_mask & BIT_ULL(power_domain));
10264
10265         wf = intel_display_power_get_if_enabled(dev_priv, power_domain);
10266         if (!wf)
10267                 return false;
10268
10269         wakerefs[power_domain] = wf;
10270         *power_domain_mask |= BIT_ULL(power_domain);
10271
10272         tmp = I915_READ(PIPECONF(pipe_config->cpu_transcoder));
10273
10274         return tmp & PIPECONF_ENABLE;
10275 }
10276
10277 static bool bxt_get_dsi_transcoder_state(struct intel_crtc *crtc,
10278                                          struct intel_crtc_state *pipe_config,
10279                                          u64 *power_domain_mask,
10280                                          intel_wakeref_t *wakerefs)
10281 {
10282         struct drm_device *dev = crtc->base.dev;
10283         struct drm_i915_private *dev_priv = to_i915(dev);
10284         enum intel_display_power_domain power_domain;
10285         enum transcoder cpu_transcoder;
10286         intel_wakeref_t wf;
10287         enum port port;
10288         u32 tmp;
10289
10290         for_each_port_masked(port, BIT(PORT_A) | BIT(PORT_C)) {
10291                 if (port == PORT_A)
10292                         cpu_transcoder = TRANSCODER_DSI_A;
10293                 else
10294                         cpu_transcoder = TRANSCODER_DSI_C;
10295
10296                 power_domain = POWER_DOMAIN_TRANSCODER(cpu_transcoder);
10297                 WARN_ON(*power_domain_mask & BIT_ULL(power_domain));
10298
10299                 wf = intel_display_power_get_if_enabled(dev_priv, power_domain);
10300                 if (!wf)
10301                         continue;
10302
10303                 wakerefs[power_domain] = wf;
10304                 *power_domain_mask |= BIT_ULL(power_domain);
10305
10306                 /*
10307                  * The PLL needs to be enabled with a valid divider
10308                  * configuration, otherwise accessing DSI registers will hang
10309                  * the machine. See BSpec North Display Engine
10310                  * registers/MIPI[BXT]. We can break out here early, since we
10311                  * need the same DSI PLL to be enabled for both DSI ports.
10312                  */
10313                 if (!bxt_dsi_pll_is_enabled(dev_priv))
10314                         break;
10315
10316                 /* XXX: this works for video mode only */
10317                 tmp = I915_READ(BXT_MIPI_PORT_CTRL(port));
10318                 if (!(tmp & DPI_ENABLE))
10319                         continue;
10320
10321                 tmp = I915_READ(MIPI_CTRL(port));
10322                 if ((tmp & BXT_PIPE_SELECT_MASK) != BXT_PIPE_SELECT(crtc->pipe))
10323                         continue;
10324
10325                 pipe_config->cpu_transcoder = cpu_transcoder;
10326                 break;
10327         }
10328
10329         return transcoder_is_dsi(pipe_config->cpu_transcoder);
10330 }
10331
10332 static void haswell_get_ddi_port_state(struct intel_crtc *crtc,
10333                                        struct intel_crtc_state *pipe_config)
10334 {
10335         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
10336         struct intel_shared_dpll *pll;
10337         enum port port;
10338         u32 tmp;
10339
10340         tmp = I915_READ(TRANS_DDI_FUNC_CTL(pipe_config->cpu_transcoder));
10341
10342         if (INTEL_GEN(dev_priv) >= 12)
10343                 port = TGL_TRANS_DDI_FUNC_CTL_VAL_TO_PORT(tmp);
10344         else
10345                 port = TRANS_DDI_FUNC_CTL_VAL_TO_PORT(tmp);
10346
10347         if (INTEL_GEN(dev_priv) >= 11)
10348                 icelake_get_ddi_pll(dev_priv, port, pipe_config);
10349         else if (IS_CANNONLAKE(dev_priv))
10350                 cannonlake_get_ddi_pll(dev_priv, port, pipe_config);
10351         else if (IS_GEN9_BC(dev_priv))
10352                 skylake_get_ddi_pll(dev_priv, port, pipe_config);
10353         else if (IS_GEN9_LP(dev_priv))
10354                 bxt_get_ddi_pll(dev_priv, port, pipe_config);
10355         else
10356                 haswell_get_ddi_pll(dev_priv, port, pipe_config);
10357
10358         pll = pipe_config->shared_dpll;
10359         if (pll) {
10360                 WARN_ON(!pll->info->funcs->get_hw_state(dev_priv, pll,
10361                                                 &pipe_config->dpll_hw_state));
10362         }
10363
10364         /*
10365          * Haswell has only FDI/PCH transcoder A. It is which is connected to
10366          * DDI E. So just check whether this pipe is wired to DDI E and whether
10367          * the PCH transcoder is on.
10368          */
10369         if (INTEL_GEN(dev_priv) < 9 &&
10370             (port == PORT_E) && I915_READ(LPT_TRANSCONF) & TRANS_ENABLE) {
10371                 pipe_config->has_pch_encoder = true;
10372
10373                 tmp = I915_READ(FDI_RX_CTL(PIPE_A));
10374                 pipe_config->fdi_lanes = ((FDI_DP_PORT_WIDTH_MASK & tmp) >>
10375                                           FDI_DP_PORT_WIDTH_SHIFT) + 1;
10376
10377                 ironlake_get_fdi_m_n_config(crtc, pipe_config);
10378         }
10379 }
10380
10381 static bool haswell_get_pipe_config(struct intel_crtc *crtc,
10382                                     struct intel_crtc_state *pipe_config)
10383 {
10384         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
10385         intel_wakeref_t wakerefs[POWER_DOMAIN_NUM], wf;
10386         enum intel_display_power_domain power_domain;
10387         u64 power_domain_mask;
10388         bool active;
10389
10390         intel_crtc_init_scalers(crtc, pipe_config);
10391
10392         power_domain = POWER_DOMAIN_PIPE(crtc->pipe);
10393         wf = intel_display_power_get_if_enabled(dev_priv, power_domain);
10394         if (!wf)
10395                 return false;
10396
10397         wakerefs[power_domain] = wf;
10398         power_domain_mask = BIT_ULL(power_domain);
10399
10400         pipe_config->shared_dpll = NULL;
10401
10402         active = hsw_get_transcoder_state(crtc, pipe_config,
10403                                           &power_domain_mask, wakerefs);
10404
10405         if (IS_GEN9_LP(dev_priv) &&
10406             bxt_get_dsi_transcoder_state(crtc, pipe_config,
10407                                          &power_domain_mask, wakerefs)) {
10408                 WARN_ON(active);
10409                 active = true;
10410         }
10411
10412         if (!active)
10413                 goto out;
10414
10415         if (!transcoder_is_dsi(pipe_config->cpu_transcoder) ||
10416             INTEL_GEN(dev_priv) >= 11) {
10417                 haswell_get_ddi_port_state(crtc, pipe_config);
10418                 intel_get_pipe_timings(crtc, pipe_config);
10419         }
10420
10421         intel_get_pipe_src_size(crtc, pipe_config);
10422         intel_get_crtc_ycbcr_config(crtc, pipe_config);
10423
10424         pipe_config->gamma_mode = I915_READ(GAMMA_MODE(crtc->pipe));
10425
10426         pipe_config->csc_mode = I915_READ(PIPE_CSC_MODE(crtc->pipe));
10427
10428         if (INTEL_GEN(dev_priv) >= 9) {
10429                 u32 tmp = I915_READ(SKL_BOTTOM_COLOR(crtc->pipe));
10430
10431                 if (tmp & SKL_BOTTOM_COLOR_GAMMA_ENABLE)
10432                         pipe_config->gamma_enable = true;
10433
10434                 if (tmp & SKL_BOTTOM_COLOR_CSC_ENABLE)
10435                         pipe_config->csc_enable = true;
10436         } else {
10437                 i9xx_get_pipe_color_config(pipe_config);
10438         }
10439
10440         intel_color_get_config(pipe_config);
10441
10442         power_domain = POWER_DOMAIN_PIPE_PANEL_FITTER(crtc->pipe);
10443         WARN_ON(power_domain_mask & BIT_ULL(power_domain));
10444
10445         wf = intel_display_power_get_if_enabled(dev_priv, power_domain);
10446         if (wf) {
10447                 wakerefs[power_domain] = wf;
10448                 power_domain_mask |= BIT_ULL(power_domain);
10449
10450                 if (INTEL_GEN(dev_priv) >= 9)
10451                         skylake_get_pfit_config(crtc, pipe_config);
10452                 else
10453                         ironlake_get_pfit_config(crtc, pipe_config);
10454         }
10455
10456         if (hsw_crtc_supports_ips(crtc)) {
10457                 if (IS_HASWELL(dev_priv))
10458                         pipe_config->ips_enabled = I915_READ(IPS_CTL) & IPS_ENABLE;
10459                 else {
10460                         /*
10461                          * We cannot readout IPS state on broadwell, set to
10462                          * true so we can set it to a defined state on first
10463                          * commit.
10464                          */
10465                         pipe_config->ips_enabled = true;
10466                 }
10467         }
10468
10469         if (pipe_config->cpu_transcoder != TRANSCODER_EDP &&
10470             !transcoder_is_dsi(pipe_config->cpu_transcoder)) {
10471                 pipe_config->pixel_multiplier =
10472                         I915_READ(PIPE_MULT(pipe_config->cpu_transcoder)) + 1;
10473         } else {
10474                 pipe_config->pixel_multiplier = 1;
10475         }
10476
10477 out:
10478         for_each_power_domain(power_domain, power_domain_mask)
10479                 intel_display_power_put(dev_priv,
10480                                         power_domain, wakerefs[power_domain]);
10481
10482         return active;
10483 }
10484
10485 static u32 intel_cursor_base(const struct intel_plane_state *plane_state)
10486 {
10487         struct drm_i915_private *dev_priv =
10488                 to_i915(plane_state->base.plane->dev);
10489         const struct drm_framebuffer *fb = plane_state->base.fb;
10490         const struct drm_i915_gem_object *obj = intel_fb_obj(fb);
10491         u32 base;
10492
10493         if (INTEL_INFO(dev_priv)->display.cursor_needs_physical)
10494                 base = obj->phys_handle->busaddr;
10495         else
10496                 base = intel_plane_ggtt_offset(plane_state);
10497
10498         base += plane_state->color_plane[0].offset;
10499
10500         /* ILK+ do this automagically */
10501         if (HAS_GMCH(dev_priv) &&
10502             plane_state->base.rotation & DRM_MODE_ROTATE_180)
10503                 base += (plane_state->base.crtc_h *
10504                          plane_state->base.crtc_w - 1) * fb->format->cpp[0];
10505
10506         return base;
10507 }
10508
10509 static u32 intel_cursor_position(const struct intel_plane_state *plane_state)
10510 {
10511         int x = plane_state->base.crtc_x;
10512         int y = plane_state->base.crtc_y;
10513         u32 pos = 0;
10514
10515         if (x < 0) {
10516                 pos |= CURSOR_POS_SIGN << CURSOR_X_SHIFT;
10517                 x = -x;
10518         }
10519         pos |= x << CURSOR_X_SHIFT;
10520
10521         if (y < 0) {
10522                 pos |= CURSOR_POS_SIGN << CURSOR_Y_SHIFT;
10523                 y = -y;
10524         }
10525         pos |= y << CURSOR_Y_SHIFT;
10526
10527         return pos;
10528 }
10529
10530 static bool intel_cursor_size_ok(const struct intel_plane_state *plane_state)
10531 {
10532         const struct drm_mode_config *config =
10533                 &plane_state->base.plane->dev->mode_config;
10534         int width = plane_state->base.crtc_w;
10535         int height = plane_state->base.crtc_h;
10536
10537         return width > 0 && width <= config->cursor_width &&
10538                 height > 0 && height <= config->cursor_height;
10539 }
10540
10541 static int intel_cursor_check_surface(struct intel_plane_state *plane_state)
10542 {
10543         int src_x, src_y;
10544         u32 offset;
10545         int ret;
10546
10547         ret = intel_plane_compute_gtt(plane_state);
10548         if (ret)
10549                 return ret;
10550
10551         if (!plane_state->base.visible)
10552                 return 0;
10553
10554         src_x = plane_state->base.src_x >> 16;
10555         src_y = plane_state->base.src_y >> 16;
10556
10557         intel_add_fb_offsets(&src_x, &src_y, plane_state, 0);
10558         offset = intel_plane_compute_aligned_offset(&src_x, &src_y,
10559                                                     plane_state, 0);
10560
10561         if (src_x != 0 || src_y != 0) {
10562                 DRM_DEBUG_KMS("Arbitrary cursor panning not supported\n");
10563                 return -EINVAL;
10564         }
10565
10566         plane_state->color_plane[0].offset = offset;
10567
10568         return 0;
10569 }
10570
10571 static int intel_check_cursor(struct intel_crtc_state *crtc_state,
10572                               struct intel_plane_state *plane_state)
10573 {
10574         const struct drm_framebuffer *fb = plane_state->base.fb;
10575         int ret;
10576
10577         if (fb && fb->modifier != DRM_FORMAT_MOD_LINEAR) {
10578                 DRM_DEBUG_KMS("cursor cannot be tiled\n");
10579                 return -EINVAL;
10580         }
10581
10582         ret = drm_atomic_helper_check_plane_state(&plane_state->base,
10583                                                   &crtc_state->base,
10584                                                   DRM_PLANE_HELPER_NO_SCALING,
10585                                                   DRM_PLANE_HELPER_NO_SCALING,
10586                                                   true, true);
10587         if (ret)
10588                 return ret;
10589
10590         ret = intel_cursor_check_surface(plane_state);
10591         if (ret)
10592                 return ret;
10593
10594         if (!plane_state->base.visible)
10595                 return 0;
10596
10597         ret = intel_plane_check_src_coordinates(plane_state);
10598         if (ret)
10599                 return ret;
10600
10601         return 0;
10602 }
10603
10604 static unsigned int
10605 i845_cursor_max_stride(struct intel_plane *plane,
10606                        u32 pixel_format, u64 modifier,
10607                        unsigned int rotation)
10608 {
10609         return 2048;
10610 }
10611
10612 static u32 i845_cursor_ctl_crtc(const struct intel_crtc_state *crtc_state)
10613 {
10614         u32 cntl = 0;
10615
10616         if (crtc_state->gamma_enable)
10617                 cntl |= CURSOR_GAMMA_ENABLE;
10618
10619         return cntl;
10620 }
10621
10622 static u32 i845_cursor_ctl(const struct intel_crtc_state *crtc_state,
10623                            const struct intel_plane_state *plane_state)
10624 {
10625         return CURSOR_ENABLE |
10626                 CURSOR_FORMAT_ARGB |
10627                 CURSOR_STRIDE(plane_state->color_plane[0].stride);
10628 }
10629
10630 static bool i845_cursor_size_ok(const struct intel_plane_state *plane_state)
10631 {
10632         int width = plane_state->base.crtc_w;
10633
10634         /*
10635          * 845g/865g are only limited by the width of their cursors,
10636          * the height is arbitrary up to the precision of the register.
10637          */
10638         return intel_cursor_size_ok(plane_state) && IS_ALIGNED(width, 64);
10639 }
10640
10641 static int i845_check_cursor(struct intel_crtc_state *crtc_state,
10642                              struct intel_plane_state *plane_state)
10643 {
10644         const struct drm_framebuffer *fb = plane_state->base.fb;
10645         int ret;
10646
10647         ret = intel_check_cursor(crtc_state, plane_state);
10648         if (ret)
10649                 return ret;
10650
10651         /* if we want to turn off the cursor ignore width and height */
10652         if (!fb)
10653                 return 0;
10654
10655         /* Check for which cursor types we support */
10656         if (!i845_cursor_size_ok(plane_state)) {
10657                 DRM_DEBUG("Cursor dimension %dx%d not supported\n",
10658                           plane_state->base.crtc_w,
10659                           plane_state->base.crtc_h);
10660                 return -EINVAL;
10661         }
10662
10663         WARN_ON(plane_state->base.visible &&
10664                 plane_state->color_plane[0].stride != fb->pitches[0]);
10665
10666         switch (fb->pitches[0]) {
10667         case 256:
10668         case 512:
10669         case 1024:
10670         case 2048:
10671                 break;
10672         default:
10673                 DRM_DEBUG_KMS("Invalid cursor stride (%u)\n",
10674                               fb->pitches[0]);
10675                 return -EINVAL;
10676         }
10677
10678         plane_state->ctl = i845_cursor_ctl(crtc_state, plane_state);
10679
10680         return 0;
10681 }
10682
10683 static void i845_update_cursor(struct intel_plane *plane,
10684                                const struct intel_crtc_state *crtc_state,
10685                                const struct intel_plane_state *plane_state)
10686 {
10687         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
10688         u32 cntl = 0, base = 0, pos = 0, size = 0;
10689         unsigned long irqflags;
10690
10691         if (plane_state && plane_state->base.visible) {
10692                 unsigned int width = plane_state->base.crtc_w;
10693                 unsigned int height = plane_state->base.crtc_h;
10694
10695                 cntl = plane_state->ctl |
10696                         i845_cursor_ctl_crtc(crtc_state);
10697
10698                 size = (height << 12) | width;
10699
10700                 base = intel_cursor_base(plane_state);
10701                 pos = intel_cursor_position(plane_state);
10702         }
10703
10704         spin_lock_irqsave(&dev_priv->uncore.lock, irqflags);
10705
10706         /* On these chipsets we can only modify the base/size/stride
10707          * whilst the cursor is disabled.
10708          */
10709         if (plane->cursor.base != base ||
10710             plane->cursor.size != size ||
10711             plane->cursor.cntl != cntl) {
10712                 I915_WRITE_FW(CURCNTR(PIPE_A), 0);
10713                 I915_WRITE_FW(CURBASE(PIPE_A), base);
10714                 I915_WRITE_FW(CURSIZE, size);
10715                 I915_WRITE_FW(CURPOS(PIPE_A), pos);
10716                 I915_WRITE_FW(CURCNTR(PIPE_A), cntl);
10717
10718                 plane->cursor.base = base;
10719                 plane->cursor.size = size;
10720                 plane->cursor.cntl = cntl;
10721         } else {
10722                 I915_WRITE_FW(CURPOS(PIPE_A), pos);
10723         }
10724
10725         spin_unlock_irqrestore(&dev_priv->uncore.lock, irqflags);
10726 }
10727
10728 static void i845_disable_cursor(struct intel_plane *plane,
10729                                 const struct intel_crtc_state *crtc_state)
10730 {
10731         i845_update_cursor(plane, crtc_state, NULL);
10732 }
10733
10734 static bool i845_cursor_get_hw_state(struct intel_plane *plane,
10735                                      enum pipe *pipe)
10736 {
10737         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
10738         enum intel_display_power_domain power_domain;
10739         intel_wakeref_t wakeref;
10740         bool ret;
10741
10742         power_domain = POWER_DOMAIN_PIPE(PIPE_A);
10743         wakeref = intel_display_power_get_if_enabled(dev_priv, power_domain);
10744         if (!wakeref)
10745                 return false;
10746
10747         ret = I915_READ(CURCNTR(PIPE_A)) & CURSOR_ENABLE;
10748
10749         *pipe = PIPE_A;
10750
10751         intel_display_power_put(dev_priv, power_domain, wakeref);
10752
10753         return ret;
10754 }
10755
10756 static unsigned int
10757 i9xx_cursor_max_stride(struct intel_plane *plane,
10758                        u32 pixel_format, u64 modifier,
10759                        unsigned int rotation)
10760 {
10761         return plane->base.dev->mode_config.cursor_width * 4;
10762 }
10763
10764 static u32 i9xx_cursor_ctl_crtc(const struct intel_crtc_state *crtc_state)
10765 {
10766         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
10767         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
10768         u32 cntl = 0;
10769
10770         if (INTEL_GEN(dev_priv) >= 11)
10771                 return cntl;
10772
10773         if (crtc_state->gamma_enable)
10774                 cntl = MCURSOR_GAMMA_ENABLE;
10775
10776         if (crtc_state->csc_enable)
10777                 cntl |= MCURSOR_PIPE_CSC_ENABLE;
10778
10779         if (INTEL_GEN(dev_priv) < 5 && !IS_G4X(dev_priv))
10780                 cntl |= MCURSOR_PIPE_SELECT(crtc->pipe);
10781
10782         return cntl;
10783 }
10784
10785 static u32 i9xx_cursor_ctl(const struct intel_crtc_state *crtc_state,
10786                            const struct intel_plane_state *plane_state)
10787 {
10788         struct drm_i915_private *dev_priv =
10789                 to_i915(plane_state->base.plane->dev);
10790         u32 cntl = 0;
10791
10792         if (IS_GEN(dev_priv, 6) || IS_IVYBRIDGE(dev_priv))
10793                 cntl |= MCURSOR_TRICKLE_FEED_DISABLE;
10794
10795         switch (plane_state->base.crtc_w) {
10796         case 64:
10797                 cntl |= MCURSOR_MODE_64_ARGB_AX;
10798                 break;
10799         case 128:
10800                 cntl |= MCURSOR_MODE_128_ARGB_AX;
10801                 break;
10802         case 256:
10803                 cntl |= MCURSOR_MODE_256_ARGB_AX;
10804                 break;
10805         default:
10806                 MISSING_CASE(plane_state->base.crtc_w);
10807                 return 0;
10808         }
10809
10810         if (plane_state->base.rotation & DRM_MODE_ROTATE_180)
10811                 cntl |= MCURSOR_ROTATE_180;
10812
10813         return cntl;
10814 }
10815
10816 static bool i9xx_cursor_size_ok(const struct intel_plane_state *plane_state)
10817 {
10818         struct drm_i915_private *dev_priv =
10819                 to_i915(plane_state->base.plane->dev);
10820         int width = plane_state->base.crtc_w;
10821         int height = plane_state->base.crtc_h;
10822
10823         if (!intel_cursor_size_ok(plane_state))
10824                 return false;
10825
10826         /* Cursor width is limited to a few power-of-two sizes */
10827         switch (width) {
10828         case 256:
10829         case 128:
10830         case 64:
10831                 break;
10832         default:
10833                 return false;
10834         }
10835
10836         /*
10837          * IVB+ have CUR_FBC_CTL which allows an arbitrary cursor
10838          * height from 8 lines up to the cursor width, when the
10839          * cursor is not rotated. Everything else requires square
10840          * cursors.
10841          */
10842         if (HAS_CUR_FBC(dev_priv) &&
10843             plane_state->base.rotation & DRM_MODE_ROTATE_0) {
10844                 if (height < 8 || height > width)
10845                         return false;
10846         } else {
10847                 if (height != width)
10848                         return false;
10849         }
10850
10851         return true;
10852 }
10853
10854 static int i9xx_check_cursor(struct intel_crtc_state *crtc_state,
10855                              struct intel_plane_state *plane_state)
10856 {
10857         struct intel_plane *plane = to_intel_plane(plane_state->base.plane);
10858         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
10859         const struct drm_framebuffer *fb = plane_state->base.fb;
10860         enum pipe pipe = plane->pipe;
10861         int ret;
10862
10863         ret = intel_check_cursor(crtc_state, plane_state);
10864         if (ret)
10865                 return ret;
10866
10867         /* if we want to turn off the cursor ignore width and height */
10868         if (!fb)
10869                 return 0;
10870
10871         /* Check for which cursor types we support */
10872         if (!i9xx_cursor_size_ok(plane_state)) {
10873                 DRM_DEBUG("Cursor dimension %dx%d not supported\n",
10874                           plane_state->base.crtc_w,
10875                           plane_state->base.crtc_h);
10876                 return -EINVAL;
10877         }
10878
10879         WARN_ON(plane_state->base.visible &&
10880                 plane_state->color_plane[0].stride != fb->pitches[0]);
10881
10882         if (fb->pitches[0] != plane_state->base.crtc_w * fb->format->cpp[0]) {
10883                 DRM_DEBUG_KMS("Invalid cursor stride (%u) (cursor width %d)\n",
10884                               fb->pitches[0], plane_state->base.crtc_w);
10885                 return -EINVAL;
10886         }
10887
10888         /*
10889          * There's something wrong with the cursor on CHV pipe C.
10890          * If it straddles the left edge of the screen then
10891          * moving it away from the edge or disabling it often
10892          * results in a pipe underrun, and often that can lead to
10893          * dead pipe (constant underrun reported, and it scans
10894          * out just a solid color). To recover from that, the
10895          * display power well must be turned off and on again.
10896          * Refuse the put the cursor into that compromised position.
10897          */
10898         if (IS_CHERRYVIEW(dev_priv) && pipe == PIPE_C &&
10899             plane_state->base.visible && plane_state->base.crtc_x < 0) {
10900                 DRM_DEBUG_KMS("CHV cursor C not allowed to straddle the left screen edge\n");
10901                 return -EINVAL;
10902         }
10903
10904         plane_state->ctl = i9xx_cursor_ctl(crtc_state, plane_state);
10905
10906         return 0;
10907 }
10908
10909 static void i9xx_update_cursor(struct intel_plane *plane,
10910                                const struct intel_crtc_state *crtc_state,
10911                                const struct intel_plane_state *plane_state)
10912 {
10913         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
10914         enum pipe pipe = plane->pipe;
10915         u32 cntl = 0, base = 0, pos = 0, fbc_ctl = 0;
10916         unsigned long irqflags;
10917
10918         if (plane_state && plane_state->base.visible) {
10919                 cntl = plane_state->ctl |
10920                         i9xx_cursor_ctl_crtc(crtc_state);
10921
10922                 if (plane_state->base.crtc_h != plane_state->base.crtc_w)
10923                         fbc_ctl = CUR_FBC_CTL_EN | (plane_state->base.crtc_h - 1);
10924
10925                 base = intel_cursor_base(plane_state);
10926                 pos = intel_cursor_position(plane_state);
10927         }
10928
10929         spin_lock_irqsave(&dev_priv->uncore.lock, irqflags);
10930
10931         /*
10932          * On some platforms writing CURCNTR first will also
10933          * cause CURPOS to be armed by the CURBASE write.
10934          * Without the CURCNTR write the CURPOS write would
10935          * arm itself. Thus we always update CURCNTR before
10936          * CURPOS.
10937          *
10938          * On other platforms CURPOS always requires the
10939          * CURBASE write to arm the update. Additonally
10940          * a write to any of the cursor register will cancel
10941          * an already armed cursor update. Thus leaving out
10942          * the CURBASE write after CURPOS could lead to a
10943          * cursor that doesn't appear to move, or even change
10944          * shape. Thus we always write CURBASE.
10945          *
10946          * The other registers are armed by by the CURBASE write
10947          * except when the plane is getting enabled at which time
10948          * the CURCNTR write arms the update.
10949          */
10950
10951         if (INTEL_GEN(dev_priv) >= 9)
10952                 skl_write_cursor_wm(plane, crtc_state);
10953
10954         if (plane->cursor.base != base ||
10955             plane->cursor.size != fbc_ctl ||
10956             plane->cursor.cntl != cntl) {
10957                 if (HAS_CUR_FBC(dev_priv))
10958                         I915_WRITE_FW(CUR_FBC_CTL(pipe), fbc_ctl);
10959                 I915_WRITE_FW(CURCNTR(pipe), cntl);
10960                 I915_WRITE_FW(CURPOS(pipe), pos);
10961                 I915_WRITE_FW(CURBASE(pipe), base);
10962
10963                 plane->cursor.base = base;
10964                 plane->cursor.size = fbc_ctl;
10965                 plane->cursor.cntl = cntl;
10966         } else {
10967                 I915_WRITE_FW(CURPOS(pipe), pos);
10968                 I915_WRITE_FW(CURBASE(pipe), base);
10969         }
10970
10971         spin_unlock_irqrestore(&dev_priv->uncore.lock, irqflags);
10972 }
10973
10974 static void i9xx_disable_cursor(struct intel_plane *plane,
10975                                 const struct intel_crtc_state *crtc_state)
10976 {
10977         i9xx_update_cursor(plane, crtc_state, NULL);
10978 }
10979
10980 static bool i9xx_cursor_get_hw_state(struct intel_plane *plane,
10981                                      enum pipe *pipe)
10982 {
10983         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
10984         enum intel_display_power_domain power_domain;
10985         intel_wakeref_t wakeref;
10986         bool ret;
10987         u32 val;
10988
10989         /*
10990          * Not 100% correct for planes that can move between pipes,
10991          * but that's only the case for gen2-3 which don't have any
10992          * display power wells.
10993          */
10994         power_domain = POWER_DOMAIN_PIPE(plane->pipe);
10995         wakeref = intel_display_power_get_if_enabled(dev_priv, power_domain);
10996         if (!wakeref)
10997                 return false;
10998
10999         val = I915_READ(CURCNTR(plane->pipe));
11000
11001         ret = val & MCURSOR_MODE;
11002
11003         if (INTEL_GEN(dev_priv) >= 5 || IS_G4X(dev_priv))
11004                 *pipe = plane->pipe;
11005         else
11006                 *pipe = (val & MCURSOR_PIPE_SELECT_MASK) >>
11007                         MCURSOR_PIPE_SELECT_SHIFT;
11008
11009         intel_display_power_put(dev_priv, power_domain, wakeref);
11010
11011         return ret;
11012 }
11013
11014 /* VESA 640x480x72Hz mode to set on the pipe */
11015 static const struct drm_display_mode load_detect_mode = {
11016         DRM_MODE("640x480", DRM_MODE_TYPE_DEFAULT, 31500, 640, 664,
11017                  704, 832, 0, 480, 489, 491, 520, 0, DRM_MODE_FLAG_NHSYNC | DRM_MODE_FLAG_NVSYNC),
11018 };
11019
11020 struct drm_framebuffer *
11021 intel_framebuffer_create(struct drm_i915_gem_object *obj,
11022                          struct drm_mode_fb_cmd2 *mode_cmd)
11023 {
11024         struct intel_framebuffer *intel_fb;
11025         int ret;
11026
11027         intel_fb = kzalloc(sizeof(*intel_fb), GFP_KERNEL);
11028         if (!intel_fb)
11029                 return ERR_PTR(-ENOMEM);
11030
11031         ret = intel_framebuffer_init(intel_fb, obj, mode_cmd);
11032         if (ret)
11033                 goto err;
11034
11035         return &intel_fb->base;
11036
11037 err:
11038         kfree(intel_fb);
11039         return ERR_PTR(ret);
11040 }
11041
11042 static int intel_modeset_disable_planes(struct drm_atomic_state *state,
11043                                         struct drm_crtc *crtc)
11044 {
11045         struct drm_plane *plane;
11046         struct drm_plane_state *plane_state;
11047         int ret, i;
11048
11049         ret = drm_atomic_add_affected_planes(state, crtc);
11050         if (ret)
11051                 return ret;
11052
11053         for_each_new_plane_in_state(state, plane, plane_state, i) {
11054                 if (plane_state->crtc != crtc)
11055                         continue;
11056
11057                 ret = drm_atomic_set_crtc_for_plane(plane_state, NULL);
11058                 if (ret)
11059                         return ret;
11060
11061                 drm_atomic_set_fb_for_plane(plane_state, NULL);
11062         }
11063
11064         return 0;
11065 }
11066
11067 int intel_get_load_detect_pipe(struct drm_connector *connector,
11068                                const struct drm_display_mode *mode,
11069                                struct intel_load_detect_pipe *old,
11070                                struct drm_modeset_acquire_ctx *ctx)
11071 {
11072         struct intel_crtc *intel_crtc;
11073         struct intel_encoder *intel_encoder =
11074                 intel_attached_encoder(connector);
11075         struct drm_crtc *possible_crtc;
11076         struct drm_encoder *encoder = &intel_encoder->base;
11077         struct drm_crtc *crtc = NULL;
11078         struct drm_device *dev = encoder->dev;
11079         struct drm_i915_private *dev_priv = to_i915(dev);
11080         struct drm_mode_config *config = &dev->mode_config;
11081         struct drm_atomic_state *state = NULL, *restore_state = NULL;
11082         struct drm_connector_state *connector_state;
11083         struct intel_crtc_state *crtc_state;
11084         int ret, i = -1;
11085
11086         DRM_DEBUG_KMS("[CONNECTOR:%d:%s], [ENCODER:%d:%s]\n",
11087                       connector->base.id, connector->name,
11088                       encoder->base.id, encoder->name);
11089
11090         old->restore_state = NULL;
11091
11092         WARN_ON(!drm_modeset_is_locked(&config->connection_mutex));
11093
11094         /*
11095          * Algorithm gets a little messy:
11096          *
11097          *   - if the connector already has an assigned crtc, use it (but make
11098          *     sure it's on first)
11099          *
11100          *   - try to find the first unused crtc that can drive this connector,
11101          *     and use that if we find one
11102          */
11103
11104         /* See if we already have a CRTC for this connector */
11105         if (connector->state->crtc) {
11106                 crtc = connector->state->crtc;
11107
11108                 ret = drm_modeset_lock(&crtc->mutex, ctx);
11109                 if (ret)
11110                         goto fail;
11111
11112                 /* Make sure the crtc and connector are running */
11113                 goto found;
11114         }
11115
11116         /* Find an unused one (if possible) */
11117         for_each_crtc(dev, possible_crtc) {
11118                 i++;
11119                 if (!(encoder->possible_crtcs & (1 << i)))
11120                         continue;
11121
11122                 ret = drm_modeset_lock(&possible_crtc->mutex, ctx);
11123                 if (ret)
11124                         goto fail;
11125
11126                 if (possible_crtc->state->enable) {
11127                         drm_modeset_unlock(&possible_crtc->mutex);
11128                         continue;
11129                 }
11130
11131                 crtc = possible_crtc;
11132                 break;
11133         }
11134
11135         /*
11136          * If we didn't find an unused CRTC, don't use any.
11137          */
11138         if (!crtc) {
11139                 DRM_DEBUG_KMS("no pipe available for load-detect\n");
11140                 ret = -ENODEV;
11141                 goto fail;
11142         }
11143
11144 found:
11145         intel_crtc = to_intel_crtc(crtc);
11146
11147         state = drm_atomic_state_alloc(dev);
11148         restore_state = drm_atomic_state_alloc(dev);
11149         if (!state || !restore_state) {
11150                 ret = -ENOMEM;
11151                 goto fail;
11152         }
11153
11154         state->acquire_ctx = ctx;
11155         restore_state->acquire_ctx = ctx;
11156
11157         connector_state = drm_atomic_get_connector_state(state, connector);
11158         if (IS_ERR(connector_state)) {
11159                 ret = PTR_ERR(connector_state);
11160                 goto fail;
11161         }
11162
11163         ret = drm_atomic_set_crtc_for_connector(connector_state, crtc);
11164         if (ret)
11165                 goto fail;
11166
11167         crtc_state = intel_atomic_get_crtc_state(state, intel_crtc);
11168         if (IS_ERR(crtc_state)) {
11169                 ret = PTR_ERR(crtc_state);
11170                 goto fail;
11171         }
11172
11173         crtc_state->base.active = crtc_state->base.enable = true;
11174
11175         if (!mode)
11176                 mode = &load_detect_mode;
11177
11178         ret = drm_atomic_set_mode_for_crtc(&crtc_state->base, mode);
11179         if (ret)
11180                 goto fail;
11181
11182         ret = intel_modeset_disable_planes(state, crtc);
11183         if (ret)
11184                 goto fail;
11185
11186         ret = PTR_ERR_OR_ZERO(drm_atomic_get_connector_state(restore_state, connector));
11187         if (!ret)
11188                 ret = PTR_ERR_OR_ZERO(drm_atomic_get_crtc_state(restore_state, crtc));
11189         if (!ret)
11190                 ret = drm_atomic_add_affected_planes(restore_state, crtc);
11191         if (ret) {
11192                 DRM_DEBUG_KMS("Failed to create a copy of old state to restore: %i\n", ret);
11193                 goto fail;
11194         }
11195
11196         ret = drm_atomic_commit(state);
11197         if (ret) {
11198                 DRM_DEBUG_KMS("failed to set mode on load-detect pipe\n");
11199                 goto fail;
11200         }
11201
11202         old->restore_state = restore_state;
11203         drm_atomic_state_put(state);
11204
11205         /* let the connector get through one full cycle before testing */
11206         intel_wait_for_vblank(dev_priv, intel_crtc->pipe);
11207         return true;
11208
11209 fail:
11210         if (state) {
11211                 drm_atomic_state_put(state);
11212                 state = NULL;
11213         }
11214         if (restore_state) {
11215                 drm_atomic_state_put(restore_state);
11216                 restore_state = NULL;
11217         }
11218
11219         if (ret == -EDEADLK)
11220                 return ret;
11221
11222         return false;
11223 }
11224
11225 void intel_release_load_detect_pipe(struct drm_connector *connector,
11226                                     struct intel_load_detect_pipe *old,
11227                                     struct drm_modeset_acquire_ctx *ctx)
11228 {
11229         struct intel_encoder *intel_encoder =
11230                 intel_attached_encoder(connector);
11231         struct drm_encoder *encoder = &intel_encoder->base;
11232         struct drm_atomic_state *state = old->restore_state;
11233         int ret;
11234
11235         DRM_DEBUG_KMS("[CONNECTOR:%d:%s], [ENCODER:%d:%s]\n",
11236                       connector->base.id, connector->name,
11237                       encoder->base.id, encoder->name);
11238
11239         if (!state)
11240                 return;
11241
11242         ret = drm_atomic_helper_commit_duplicated_state(state, ctx);
11243         if (ret)
11244                 DRM_DEBUG_KMS("Couldn't release load detect pipe: %i\n", ret);
11245         drm_atomic_state_put(state);
11246 }
11247
11248 static int i9xx_pll_refclk(struct drm_device *dev,
11249                            const struct intel_crtc_state *pipe_config)
11250 {
11251         struct drm_i915_private *dev_priv = to_i915(dev);
11252         u32 dpll = pipe_config->dpll_hw_state.dpll;
11253
11254         if ((dpll & PLL_REF_INPUT_MASK) == PLLB_REF_INPUT_SPREADSPECTRUMIN)
11255                 return dev_priv->vbt.lvds_ssc_freq;
11256         else if (HAS_PCH_SPLIT(dev_priv))
11257                 return 120000;
11258         else if (!IS_GEN(dev_priv, 2))
11259                 return 96000;
11260         else
11261                 return 48000;
11262 }
11263
11264 /* Returns the clock of the currently programmed mode of the given pipe. */
11265 static void i9xx_crtc_clock_get(struct intel_crtc *crtc,
11266                                 struct intel_crtc_state *pipe_config)
11267 {
11268         struct drm_device *dev = crtc->base.dev;
11269         struct drm_i915_private *dev_priv = to_i915(dev);
11270         enum pipe pipe = crtc->pipe;
11271         u32 dpll = pipe_config->dpll_hw_state.dpll;
11272         u32 fp;
11273         struct dpll clock;
11274         int port_clock;
11275         int refclk = i9xx_pll_refclk(dev, pipe_config);
11276
11277         if ((dpll & DISPLAY_RATE_SELECT_FPA1) == 0)
11278                 fp = pipe_config->dpll_hw_state.fp0;
11279         else
11280                 fp = pipe_config->dpll_hw_state.fp1;
11281
11282         clock.m1 = (fp & FP_M1_DIV_MASK) >> FP_M1_DIV_SHIFT;
11283         if (IS_PINEVIEW(dev_priv)) {
11284                 clock.n = ffs((fp & FP_N_PINEVIEW_DIV_MASK) >> FP_N_DIV_SHIFT) - 1;
11285                 clock.m2 = (fp & FP_M2_PINEVIEW_DIV_MASK) >> FP_M2_DIV_SHIFT;
11286         } else {
11287                 clock.n = (fp & FP_N_DIV_MASK) >> FP_N_DIV_SHIFT;
11288                 clock.m2 = (fp & FP_M2_DIV_MASK) >> FP_M2_DIV_SHIFT;
11289         }
11290
11291         if (!IS_GEN(dev_priv, 2)) {
11292                 if (IS_PINEVIEW(dev_priv))
11293                         clock.p1 = ffs((dpll & DPLL_FPA01_P1_POST_DIV_MASK_PINEVIEW) >>
11294                                 DPLL_FPA01_P1_POST_DIV_SHIFT_PINEVIEW);
11295                 else
11296                         clock.p1 = ffs((dpll & DPLL_FPA01_P1_POST_DIV_MASK) >>
11297                                DPLL_FPA01_P1_POST_DIV_SHIFT);
11298
11299                 switch (dpll & DPLL_MODE_MASK) {
11300                 case DPLLB_MODE_DAC_SERIAL:
11301                         clock.p2 = dpll & DPLL_DAC_SERIAL_P2_CLOCK_DIV_5 ?
11302                                 5 : 10;
11303                         break;
11304                 case DPLLB_MODE_LVDS:
11305                         clock.p2 = dpll & DPLLB_LVDS_P2_CLOCK_DIV_7 ?
11306                                 7 : 14;
11307                         break;
11308                 default:
11309                         DRM_DEBUG_KMS("Unknown DPLL mode %08x in programmed "
11310                                   "mode\n", (int)(dpll & DPLL_MODE_MASK));
11311                         return;
11312                 }
11313
11314                 if (IS_PINEVIEW(dev_priv))
11315                         port_clock = pnv_calc_dpll_params(refclk, &clock);
11316                 else
11317                         port_clock = i9xx_calc_dpll_params(refclk, &clock);
11318         } else {
11319                 u32 lvds = IS_I830(dev_priv) ? 0 : I915_READ(LVDS);
11320                 bool is_lvds = (pipe == 1) && (lvds & LVDS_PORT_EN);
11321
11322                 if (is_lvds) {
11323                         clock.p1 = ffs((dpll & DPLL_FPA01_P1_POST_DIV_MASK_I830_LVDS) >>
11324                                        DPLL_FPA01_P1_POST_DIV_SHIFT);
11325
11326                         if (lvds & LVDS_CLKB_POWER_UP)
11327                                 clock.p2 = 7;
11328                         else
11329                                 clock.p2 = 14;
11330                 } else {
11331                         if (dpll & PLL_P1_DIVIDE_BY_TWO)
11332                                 clock.p1 = 2;
11333                         else {
11334                                 clock.p1 = ((dpll & DPLL_FPA01_P1_POST_DIV_MASK_I830) >>
11335                                             DPLL_FPA01_P1_POST_DIV_SHIFT) + 2;
11336                         }
11337                         if (dpll & PLL_P2_DIVIDE_BY_4)
11338                                 clock.p2 = 4;
11339                         else
11340                                 clock.p2 = 2;
11341                 }
11342
11343                 port_clock = i9xx_calc_dpll_params(refclk, &clock);
11344         }
11345
11346         /*
11347          * This value includes pixel_multiplier. We will use
11348          * port_clock to compute adjusted_mode.crtc_clock in the
11349          * encoder's get_config() function.
11350          */
11351         pipe_config->port_clock = port_clock;
11352 }
11353
11354 int intel_dotclock_calculate(int link_freq,
11355                              const struct intel_link_m_n *m_n)
11356 {
11357         /*
11358          * The calculation for the data clock is:
11359          * pixel_clock = ((m/n)*(link_clock * nr_lanes))/bpp
11360          * But we want to avoid losing precison if possible, so:
11361          * pixel_clock = ((m * link_clock * nr_lanes)/(n*bpp))
11362          *
11363          * and the link clock is simpler:
11364          * link_clock = (m * link_clock) / n
11365          */
11366
11367         if (!m_n->link_n)
11368                 return 0;
11369
11370         return div_u64(mul_u32_u32(m_n->link_m, link_freq), m_n->link_n);
11371 }
11372
11373 static void ironlake_pch_clock_get(struct intel_crtc *crtc,
11374                                    struct intel_crtc_state *pipe_config)
11375 {
11376         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
11377
11378         /* read out port_clock from the DPLL */
11379         i9xx_crtc_clock_get(crtc, pipe_config);
11380
11381         /*
11382          * In case there is an active pipe without active ports,
11383          * we may need some idea for the dotclock anyway.
11384          * Calculate one based on the FDI configuration.
11385          */
11386         pipe_config->base.adjusted_mode.crtc_clock =
11387                 intel_dotclock_calculate(intel_fdi_link_freq(dev_priv, pipe_config),
11388                                          &pipe_config->fdi_m_n);
11389 }
11390
11391 /* Returns the currently programmed mode of the given encoder. */
11392 struct drm_display_mode *
11393 intel_encoder_current_mode(struct intel_encoder *encoder)
11394 {
11395         struct drm_i915_private *dev_priv = to_i915(encoder->base.dev);
11396         struct intel_crtc_state *crtc_state;
11397         struct drm_display_mode *mode;
11398         struct intel_crtc *crtc;
11399         enum pipe pipe;
11400
11401         if (!encoder->get_hw_state(encoder, &pipe))
11402                 return NULL;
11403
11404         crtc = intel_get_crtc_for_pipe(dev_priv, pipe);
11405
11406         mode = kzalloc(sizeof(*mode), GFP_KERNEL);
11407         if (!mode)
11408                 return NULL;
11409
11410         crtc_state = kzalloc(sizeof(*crtc_state), GFP_KERNEL);
11411         if (!crtc_state) {
11412                 kfree(mode);
11413                 return NULL;
11414         }
11415
11416         crtc_state->base.crtc = &crtc->base;
11417
11418         if (!dev_priv->display.get_pipe_config(crtc, crtc_state)) {
11419                 kfree(crtc_state);
11420                 kfree(mode);
11421                 return NULL;
11422         }
11423
11424         encoder->get_config(encoder, crtc_state);
11425
11426         intel_mode_from_pipe_config(mode, crtc_state);
11427
11428         kfree(crtc_state);
11429
11430         return mode;
11431 }
11432
11433 static void intel_crtc_destroy(struct drm_crtc *crtc)
11434 {
11435         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11436
11437         drm_crtc_cleanup(crtc);
11438         kfree(intel_crtc);
11439 }
11440
11441 /**
11442  * intel_wm_need_update - Check whether watermarks need updating
11443  * @cur: current plane state
11444  * @new: new plane state
11445  *
11446  * Check current plane state versus the new one to determine whether
11447  * watermarks need to be recalculated.
11448  *
11449  * Returns true or false.
11450  */
11451 static bool intel_wm_need_update(const struct intel_plane_state *cur,
11452                                  struct intel_plane_state *new)
11453 {
11454         /* Update watermarks on tiling or size changes. */
11455         if (new->base.visible != cur->base.visible)
11456                 return true;
11457
11458         if (!cur->base.fb || !new->base.fb)
11459                 return false;
11460
11461         if (cur->base.fb->modifier != new->base.fb->modifier ||
11462             cur->base.rotation != new->base.rotation ||
11463             drm_rect_width(&new->base.src) != drm_rect_width(&cur->base.src) ||
11464             drm_rect_height(&new->base.src) != drm_rect_height(&cur->base.src) ||
11465             drm_rect_width(&new->base.dst) != drm_rect_width(&cur->base.dst) ||
11466             drm_rect_height(&new->base.dst) != drm_rect_height(&cur->base.dst))
11467                 return true;
11468
11469         return false;
11470 }
11471
11472 static bool needs_scaling(const struct intel_plane_state *state)
11473 {
11474         int src_w = drm_rect_width(&state->base.src) >> 16;
11475         int src_h = drm_rect_height(&state->base.src) >> 16;
11476         int dst_w = drm_rect_width(&state->base.dst);
11477         int dst_h = drm_rect_height(&state->base.dst);
11478
11479         return (src_w != dst_w || src_h != dst_h);
11480 }
11481
11482 int intel_plane_atomic_calc_changes(const struct intel_crtc_state *old_crtc_state,
11483                                     struct intel_crtc_state *crtc_state,
11484                                     const struct intel_plane_state *old_plane_state,
11485                                     struct intel_plane_state *plane_state)
11486 {
11487         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
11488         struct intel_plane *plane = to_intel_plane(plane_state->base.plane);
11489         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
11490         bool mode_changed = needs_modeset(crtc_state);
11491         bool was_crtc_enabled = old_crtc_state->base.active;
11492         bool is_crtc_enabled = crtc_state->base.active;
11493         bool turn_off, turn_on, visible, was_visible;
11494         struct drm_framebuffer *fb = plane_state->base.fb;
11495         int ret;
11496
11497         if (INTEL_GEN(dev_priv) >= 9 && plane->id != PLANE_CURSOR) {
11498                 ret = skl_update_scaler_plane(crtc_state, plane_state);
11499                 if (ret)
11500                         return ret;
11501         }
11502
11503         was_visible = old_plane_state->base.visible;
11504         visible = plane_state->base.visible;
11505
11506         if (!was_crtc_enabled && WARN_ON(was_visible))
11507                 was_visible = false;
11508
11509         /*
11510          * Visibility is calculated as if the crtc was on, but
11511          * after scaler setup everything depends on it being off
11512          * when the crtc isn't active.
11513          *
11514          * FIXME this is wrong for watermarks. Watermarks should also
11515          * be computed as if the pipe would be active. Perhaps move
11516          * per-plane wm computation to the .check_plane() hook, and
11517          * only combine the results from all planes in the current place?
11518          */
11519         if (!is_crtc_enabled) {
11520                 plane_state->base.visible = visible = false;
11521                 crtc_state->active_planes &= ~BIT(plane->id);
11522                 crtc_state->data_rate[plane->id] = 0;
11523         }
11524
11525         if (!was_visible && !visible)
11526                 return 0;
11527
11528         if (fb != old_plane_state->base.fb)
11529                 crtc_state->fb_changed = true;
11530
11531         turn_off = was_visible && (!visible || mode_changed);
11532         turn_on = visible && (!was_visible || mode_changed);
11533
11534         DRM_DEBUG_ATOMIC("[CRTC:%d:%s] has [PLANE:%d:%s] with fb %i\n",
11535                          crtc->base.base.id, crtc->base.name,
11536                          plane->base.base.id, plane->base.name,
11537                          fb ? fb->base.id : -1);
11538
11539         DRM_DEBUG_ATOMIC("[PLANE:%d:%s] visible %i -> %i, off %i, on %i, ms %i\n",
11540                          plane->base.base.id, plane->base.name,
11541                          was_visible, visible,
11542                          turn_off, turn_on, mode_changed);
11543
11544         if (turn_on) {
11545                 if (INTEL_GEN(dev_priv) < 5 && !IS_G4X(dev_priv))
11546                         crtc_state->update_wm_pre = true;
11547
11548                 /* must disable cxsr around plane enable/disable */
11549                 if (plane->id != PLANE_CURSOR)
11550                         crtc_state->disable_cxsr = true;
11551         } else if (turn_off) {
11552                 if (INTEL_GEN(dev_priv) < 5 && !IS_G4X(dev_priv))
11553                         crtc_state->update_wm_post = true;
11554
11555                 /* must disable cxsr around plane enable/disable */
11556                 if (plane->id != PLANE_CURSOR)
11557                         crtc_state->disable_cxsr = true;
11558         } else if (intel_wm_need_update(old_plane_state, plane_state)) {
11559                 if (INTEL_GEN(dev_priv) < 5 && !IS_G4X(dev_priv)) {
11560                         /* FIXME bollocks */
11561                         crtc_state->update_wm_pre = true;
11562                         crtc_state->update_wm_post = true;
11563                 }
11564         }
11565
11566         if (visible || was_visible)
11567                 crtc_state->fb_bits |= plane->frontbuffer_bit;
11568
11569         /*
11570          * ILK/SNB DVSACNTR/Sprite Enable
11571          * IVB SPR_CTL/Sprite Enable
11572          * "When in Self Refresh Big FIFO mode, a write to enable the
11573          *  plane will be internally buffered and delayed while Big FIFO
11574          *  mode is exiting."
11575          *
11576          * Which means that enabling the sprite can take an extra frame
11577          * when we start in big FIFO mode (LP1+). Thus we need to drop
11578          * down to LP0 and wait for vblank in order to make sure the
11579          * sprite gets enabled on the next vblank after the register write.
11580          * Doing otherwise would risk enabling the sprite one frame after
11581          * we've already signalled flip completion. We can resume LP1+
11582          * once the sprite has been enabled.
11583          *
11584          *
11585          * WaCxSRDisabledForSpriteScaling:ivb
11586          * IVB SPR_SCALE/Scaling Enable
11587          * "Low Power watermarks must be disabled for at least one
11588          *  frame before enabling sprite scaling, and kept disabled
11589          *  until sprite scaling is disabled."
11590          *
11591          * ILK/SNB DVSASCALE/Scaling Enable
11592          * "When in Self Refresh Big FIFO mode, scaling enable will be
11593          *  masked off while Big FIFO mode is exiting."
11594          *
11595          * Despite the w/a only being listed for IVB we assume that
11596          * the ILK/SNB note has similar ramifications, hence we apply
11597          * the w/a on all three platforms.
11598          *
11599          * With experimental results seems this is needed also for primary
11600          * plane, not only sprite plane.
11601          */
11602         if (plane->id != PLANE_CURSOR &&
11603             (IS_GEN_RANGE(dev_priv, 5, 6) ||
11604              IS_IVYBRIDGE(dev_priv)) &&
11605             (turn_on || (!needs_scaling(old_plane_state) &&
11606                          needs_scaling(plane_state))))
11607                 crtc_state->disable_lp_wm = true;
11608
11609         return 0;
11610 }
11611
11612 static bool encoders_cloneable(const struct intel_encoder *a,
11613                                const struct intel_encoder *b)
11614 {
11615         /* masks could be asymmetric, so check both ways */
11616         return a == b || (a->cloneable & (1 << b->type) &&
11617                           b->cloneable & (1 << a->type));
11618 }
11619
11620 static bool check_single_encoder_cloning(struct drm_atomic_state *state,
11621                                          struct intel_crtc *crtc,
11622                                          struct intel_encoder *encoder)
11623 {
11624         struct intel_encoder *source_encoder;
11625         struct drm_connector *connector;
11626         struct drm_connector_state *connector_state;
11627         int i;
11628
11629         for_each_new_connector_in_state(state, connector, connector_state, i) {
11630                 if (connector_state->crtc != &crtc->base)
11631                         continue;
11632
11633                 source_encoder =
11634                         to_intel_encoder(connector_state->best_encoder);
11635                 if (!encoders_cloneable(encoder, source_encoder))
11636                         return false;
11637         }
11638
11639         return true;
11640 }
11641
11642 static int icl_add_linked_planes(struct intel_atomic_state *state)
11643 {
11644         struct intel_plane *plane, *linked;
11645         struct intel_plane_state *plane_state, *linked_plane_state;
11646         int i;
11647
11648         for_each_new_intel_plane_in_state(state, plane, plane_state, i) {
11649                 linked = plane_state->linked_plane;
11650
11651                 if (!linked)
11652                         continue;
11653
11654                 linked_plane_state = intel_atomic_get_plane_state(state, linked);
11655                 if (IS_ERR(linked_plane_state))
11656                         return PTR_ERR(linked_plane_state);
11657
11658                 WARN_ON(linked_plane_state->linked_plane != plane);
11659                 WARN_ON(linked_plane_state->slave == plane_state->slave);
11660         }
11661
11662         return 0;
11663 }
11664
11665 static int icl_check_nv12_planes(struct intel_crtc_state *crtc_state)
11666 {
11667         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
11668         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
11669         struct intel_atomic_state *state = to_intel_atomic_state(crtc_state->base.state);
11670         struct intel_plane *plane, *linked;
11671         struct intel_plane_state *plane_state;
11672         int i;
11673
11674         if (INTEL_GEN(dev_priv) < 11)
11675                 return 0;
11676
11677         /*
11678          * Destroy all old plane links and make the slave plane invisible
11679          * in the crtc_state->active_planes mask.
11680          */
11681         for_each_new_intel_plane_in_state(state, plane, plane_state, i) {
11682                 if (plane->pipe != crtc->pipe || !plane_state->linked_plane)
11683                         continue;
11684
11685                 plane_state->linked_plane = NULL;
11686                 if (plane_state->slave && !plane_state->base.visible) {
11687                         crtc_state->active_planes &= ~BIT(plane->id);
11688                         crtc_state->update_planes |= BIT(plane->id);
11689                 }
11690
11691                 plane_state->slave = false;
11692         }
11693
11694         if (!crtc_state->nv12_planes)
11695                 return 0;
11696
11697         for_each_new_intel_plane_in_state(state, plane, plane_state, i) {
11698                 struct intel_plane_state *linked_state = NULL;
11699
11700                 if (plane->pipe != crtc->pipe ||
11701                     !(crtc_state->nv12_planes & BIT(plane->id)))
11702                         continue;
11703
11704                 for_each_intel_plane_on_crtc(&dev_priv->drm, crtc, linked) {
11705                         if (!icl_is_nv12_y_plane(linked->id))
11706                                 continue;
11707
11708                         if (crtc_state->active_planes & BIT(linked->id))
11709                                 continue;
11710
11711                         linked_state = intel_atomic_get_plane_state(state, linked);
11712                         if (IS_ERR(linked_state))
11713                                 return PTR_ERR(linked_state);
11714
11715                         break;
11716                 }
11717
11718                 if (!linked_state) {
11719                         DRM_DEBUG_KMS("Need %d free Y planes for planar YUV\n",
11720                                       hweight8(crtc_state->nv12_planes));
11721
11722                         return -EINVAL;
11723                 }
11724
11725                 plane_state->linked_plane = linked;
11726
11727                 linked_state->slave = true;
11728                 linked_state->linked_plane = plane;
11729                 crtc_state->active_planes |= BIT(linked->id);
11730                 crtc_state->update_planes |= BIT(linked->id);
11731                 DRM_DEBUG_KMS("Using %s as Y plane for %s\n", linked->base.name, plane->base.name);
11732         }
11733
11734         return 0;
11735 }
11736
11737 static bool c8_planes_changed(const struct intel_crtc_state *new_crtc_state)
11738 {
11739         struct intel_crtc *crtc = to_intel_crtc(new_crtc_state->base.crtc);
11740         struct intel_atomic_state *state =
11741                 to_intel_atomic_state(new_crtc_state->base.state);
11742         const struct intel_crtc_state *old_crtc_state =
11743                 intel_atomic_get_old_crtc_state(state, crtc);
11744
11745         return !old_crtc_state->c8_planes != !new_crtc_state->c8_planes;
11746 }
11747
11748 static int intel_crtc_atomic_check(struct drm_crtc *crtc,
11749                                    struct drm_crtc_state *crtc_state)
11750 {
11751         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
11752         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11753         struct intel_crtc_state *pipe_config =
11754                 to_intel_crtc_state(crtc_state);
11755         int ret;
11756         bool mode_changed = needs_modeset(pipe_config);
11757
11758         if (INTEL_GEN(dev_priv) < 5 && !IS_G4X(dev_priv) &&
11759             mode_changed && !crtc_state->active)
11760                 pipe_config->update_wm_post = true;
11761
11762         if (mode_changed && crtc_state->enable &&
11763             dev_priv->display.crtc_compute_clock &&
11764             !WARN_ON(pipe_config->shared_dpll)) {
11765                 ret = dev_priv->display.crtc_compute_clock(intel_crtc,
11766                                                            pipe_config);
11767                 if (ret)
11768                         return ret;
11769         }
11770
11771         /*
11772          * May need to update pipe gamma enable bits
11773          * when C8 planes are getting enabled/disabled.
11774          */
11775         if (c8_planes_changed(pipe_config))
11776                 crtc_state->color_mgmt_changed = true;
11777
11778         if (mode_changed || pipe_config->update_pipe ||
11779             crtc_state->color_mgmt_changed) {
11780                 ret = intel_color_check(pipe_config);
11781                 if (ret)
11782                         return ret;
11783         }
11784
11785         ret = 0;
11786         if (dev_priv->display.compute_pipe_wm) {
11787                 ret = dev_priv->display.compute_pipe_wm(pipe_config);
11788                 if (ret) {
11789                         DRM_DEBUG_KMS("Target pipe watermarks are invalid\n");
11790                         return ret;
11791                 }
11792         }
11793
11794         if (dev_priv->display.compute_intermediate_wm) {
11795                 if (WARN_ON(!dev_priv->display.compute_pipe_wm))
11796                         return 0;
11797
11798                 /*
11799                  * Calculate 'intermediate' watermarks that satisfy both the
11800                  * old state and the new state.  We can program these
11801                  * immediately.
11802                  */
11803                 ret = dev_priv->display.compute_intermediate_wm(pipe_config);
11804                 if (ret) {
11805                         DRM_DEBUG_KMS("No valid intermediate pipe watermarks are possible\n");
11806                         return ret;
11807                 }
11808         }
11809
11810         if (INTEL_GEN(dev_priv) >= 9) {
11811                 if (mode_changed || pipe_config->update_pipe)
11812                         ret = skl_update_scaler_crtc(pipe_config);
11813
11814                 if (!ret)
11815                         ret = icl_check_nv12_planes(pipe_config);
11816                 if (!ret)
11817                         ret = skl_check_pipe_max_pixel_rate(intel_crtc,
11818                                                             pipe_config);
11819                 if (!ret)
11820                         ret = intel_atomic_setup_scalers(dev_priv, intel_crtc,
11821                                                          pipe_config);
11822         }
11823
11824         if (HAS_IPS(dev_priv))
11825                 pipe_config->ips_enabled = hsw_compute_ips_config(pipe_config);
11826
11827         return ret;
11828 }
11829
11830 static const struct drm_crtc_helper_funcs intel_helper_funcs = {
11831         .atomic_check = intel_crtc_atomic_check,
11832 };
11833
11834 static void intel_modeset_update_connector_atomic_state(struct drm_device *dev)
11835 {
11836         struct intel_connector *connector;
11837         struct drm_connector_list_iter conn_iter;
11838
11839         drm_connector_list_iter_begin(dev, &conn_iter);
11840         for_each_intel_connector_iter(connector, &conn_iter) {
11841                 if (connector->base.state->crtc)
11842                         drm_connector_put(&connector->base);
11843
11844                 if (connector->base.encoder) {
11845                         connector->base.state->best_encoder =
11846                                 connector->base.encoder;
11847                         connector->base.state->crtc =
11848                                 connector->base.encoder->crtc;
11849
11850                         drm_connector_get(&connector->base);
11851                 } else {
11852                         connector->base.state->best_encoder = NULL;
11853                         connector->base.state->crtc = NULL;
11854                 }
11855         }
11856         drm_connector_list_iter_end(&conn_iter);
11857 }
11858
11859 static int
11860 compute_sink_pipe_bpp(const struct drm_connector_state *conn_state,
11861                       struct intel_crtc_state *pipe_config)
11862 {
11863         struct drm_connector *connector = conn_state->connector;
11864         const struct drm_display_info *info = &connector->display_info;
11865         int bpp;
11866
11867         switch (conn_state->max_bpc) {
11868         case 6 ... 7:
11869                 bpp = 6 * 3;
11870                 break;
11871         case 8 ... 9:
11872                 bpp = 8 * 3;
11873                 break;
11874         case 10 ... 11:
11875                 bpp = 10 * 3;
11876                 break;
11877         case 12:
11878                 bpp = 12 * 3;
11879                 break;
11880         default:
11881                 return -EINVAL;
11882         }
11883
11884         if (bpp < pipe_config->pipe_bpp) {
11885                 DRM_DEBUG_KMS("[CONNECTOR:%d:%s] Limiting display bpp to %d instead of "
11886                               "EDID bpp %d, requested bpp %d, max platform bpp %d\n",
11887                               connector->base.id, connector->name,
11888                               bpp, 3 * info->bpc, 3 * conn_state->max_requested_bpc,
11889                               pipe_config->pipe_bpp);
11890
11891                 pipe_config->pipe_bpp = bpp;
11892         }
11893
11894         return 0;
11895 }
11896
11897 static int
11898 compute_baseline_pipe_bpp(struct intel_crtc *crtc,
11899                           struct intel_crtc_state *pipe_config)
11900 {
11901         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
11902         struct drm_atomic_state *state = pipe_config->base.state;
11903         struct drm_connector *connector;
11904         struct drm_connector_state *connector_state;
11905         int bpp, i;
11906
11907         if ((IS_G4X(dev_priv) || IS_VALLEYVIEW(dev_priv) ||
11908             IS_CHERRYVIEW(dev_priv)))
11909                 bpp = 10*3;
11910         else if (INTEL_GEN(dev_priv) >= 5)
11911                 bpp = 12*3;
11912         else
11913                 bpp = 8*3;
11914
11915         pipe_config->pipe_bpp = bpp;
11916
11917         /* Clamp display bpp to connector max bpp */
11918         for_each_new_connector_in_state(state, connector, connector_state, i) {
11919                 int ret;
11920
11921                 if (connector_state->crtc != &crtc->base)
11922                         continue;
11923
11924                 ret = compute_sink_pipe_bpp(connector_state, pipe_config);
11925                 if (ret)
11926                         return ret;
11927         }
11928
11929         return 0;
11930 }
11931
11932 static void intel_dump_crtc_timings(const struct drm_display_mode *mode)
11933 {
11934         DRM_DEBUG_KMS("crtc timings: %d %d %d %d %d %d %d %d %d, "
11935                       "type: 0x%x flags: 0x%x\n",
11936                       mode->crtc_clock,
11937                       mode->crtc_hdisplay, mode->crtc_hsync_start,
11938                       mode->crtc_hsync_end, mode->crtc_htotal,
11939                       mode->crtc_vdisplay, mode->crtc_vsync_start,
11940                       mode->crtc_vsync_end, mode->crtc_vtotal,
11941                       mode->type, mode->flags);
11942 }
11943
11944 static inline void
11945 intel_dump_m_n_config(const struct intel_crtc_state *pipe_config,
11946                       const char *id, unsigned int lane_count,
11947                       const struct intel_link_m_n *m_n)
11948 {
11949         DRM_DEBUG_KMS("%s: lanes: %i; gmch_m: %u, gmch_n: %u, link_m: %u, link_n: %u, tu: %u\n",
11950                       id, lane_count,
11951                       m_n->gmch_m, m_n->gmch_n,
11952                       m_n->link_m, m_n->link_n, m_n->tu);
11953 }
11954
11955 static void
11956 intel_dump_infoframe(struct drm_i915_private *dev_priv,
11957                      const union hdmi_infoframe *frame)
11958 {
11959         if ((drm_debug & DRM_UT_KMS) == 0)
11960                 return;
11961
11962         hdmi_infoframe_log(KERN_DEBUG, dev_priv->drm.dev, frame);
11963 }
11964
11965 #define OUTPUT_TYPE(x) [INTEL_OUTPUT_ ## x] = #x
11966
11967 static const char * const output_type_str[] = {
11968         OUTPUT_TYPE(UNUSED),
11969         OUTPUT_TYPE(ANALOG),
11970         OUTPUT_TYPE(DVO),
11971         OUTPUT_TYPE(SDVO),
11972         OUTPUT_TYPE(LVDS),
11973         OUTPUT_TYPE(TVOUT),
11974         OUTPUT_TYPE(HDMI),
11975         OUTPUT_TYPE(DP),
11976         OUTPUT_TYPE(EDP),
11977         OUTPUT_TYPE(DSI),
11978         OUTPUT_TYPE(DDI),
11979         OUTPUT_TYPE(DP_MST),
11980 };
11981
11982 #undef OUTPUT_TYPE
11983
11984 static void snprintf_output_types(char *buf, size_t len,
11985                                   unsigned int output_types)
11986 {
11987         char *str = buf;
11988         int i;
11989
11990         str[0] = '\0';
11991
11992         for (i = 0; i < ARRAY_SIZE(output_type_str); i++) {
11993                 int r;
11994
11995                 if ((output_types & BIT(i)) == 0)
11996                         continue;
11997
11998                 r = snprintf(str, len, "%s%s",
11999                              str != buf ? "," : "", output_type_str[i]);
12000                 if (r >= len)
12001                         break;
12002                 str += r;
12003                 len -= r;
12004
12005                 output_types &= ~BIT(i);
12006         }
12007
12008         WARN_ON_ONCE(output_types != 0);
12009 }
12010
12011 static const char * const output_format_str[] = {
12012         [INTEL_OUTPUT_FORMAT_INVALID] = "Invalid",
12013         [INTEL_OUTPUT_FORMAT_RGB] = "RGB",
12014         [INTEL_OUTPUT_FORMAT_YCBCR420] = "YCBCR4:2:0",
12015         [INTEL_OUTPUT_FORMAT_YCBCR444] = "YCBCR4:4:4",
12016 };
12017
12018 static const char *output_formats(enum intel_output_format format)
12019 {
12020         if (format >= ARRAY_SIZE(output_format_str))
12021                 format = INTEL_OUTPUT_FORMAT_INVALID;
12022         return output_format_str[format];
12023 }
12024
12025 static void intel_dump_plane_state(const struct intel_plane_state *plane_state)
12026 {
12027         struct intel_plane *plane = to_intel_plane(plane_state->base.plane);
12028         const struct drm_framebuffer *fb = plane_state->base.fb;
12029         struct drm_format_name_buf format_name;
12030
12031         if (!fb) {
12032                 DRM_DEBUG_KMS("[PLANE:%d:%s] fb: [NOFB], visible: %s\n",
12033                               plane->base.base.id, plane->base.name,
12034                               yesno(plane_state->base.visible));
12035                 return;
12036         }
12037
12038         DRM_DEBUG_KMS("[PLANE:%d:%s] fb: [FB:%d] %ux%u format = %s, visible: %s\n",
12039                       plane->base.base.id, plane->base.name,
12040                       fb->base.id, fb->width, fb->height,
12041                       drm_get_format_name(fb->format->format, &format_name),
12042                       yesno(plane_state->base.visible));
12043         DRM_DEBUG_KMS("\trotation: 0x%x, scaler: %d\n",
12044                       plane_state->base.rotation, plane_state->scaler_id);
12045         if (plane_state->base.visible)
12046                 DRM_DEBUG_KMS("\tsrc: " DRM_RECT_FP_FMT " dst: " DRM_RECT_FMT "\n",
12047                               DRM_RECT_FP_ARG(&plane_state->base.src),
12048                               DRM_RECT_ARG(&plane_state->base.dst));
12049 }
12050
12051 static void intel_dump_pipe_config(const struct intel_crtc_state *pipe_config,
12052                                    struct intel_atomic_state *state,
12053                                    const char *context)
12054 {
12055         struct intel_crtc *crtc = to_intel_crtc(pipe_config->base.crtc);
12056         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
12057         const struct intel_plane_state *plane_state;
12058         struct intel_plane *plane;
12059         char buf[64];
12060         int i;
12061
12062         DRM_DEBUG_KMS("[CRTC:%d:%s] enable: %s %s\n",
12063                       crtc->base.base.id, crtc->base.name,
12064                       yesno(pipe_config->base.enable), context);
12065
12066         if (!pipe_config->base.enable)
12067                 goto dump_planes;
12068
12069         snprintf_output_types(buf, sizeof(buf), pipe_config->output_types);
12070         DRM_DEBUG_KMS("active: %s, output_types: %s (0x%x), output format: %s\n",
12071                       yesno(pipe_config->base.active),
12072                       buf, pipe_config->output_types,
12073                       output_formats(pipe_config->output_format));
12074
12075         DRM_DEBUG_KMS("cpu_transcoder: %s, pipe bpp: %i, dithering: %i\n",
12076                       transcoder_name(pipe_config->cpu_transcoder),
12077                       pipe_config->pipe_bpp, pipe_config->dither);
12078
12079         if (pipe_config->has_pch_encoder)
12080                 intel_dump_m_n_config(pipe_config, "fdi",
12081                                       pipe_config->fdi_lanes,
12082                                       &pipe_config->fdi_m_n);
12083
12084         if (intel_crtc_has_dp_encoder(pipe_config)) {
12085                 intel_dump_m_n_config(pipe_config, "dp m_n",
12086                                 pipe_config->lane_count, &pipe_config->dp_m_n);
12087                 if (pipe_config->has_drrs)
12088                         intel_dump_m_n_config(pipe_config, "dp m2_n2",
12089                                               pipe_config->lane_count,
12090                                               &pipe_config->dp_m2_n2);
12091         }
12092
12093         DRM_DEBUG_KMS("audio: %i, infoframes: %i, infoframes enabled: 0x%x\n",
12094                       pipe_config->has_audio, pipe_config->has_infoframe,
12095                       pipe_config->infoframes.enable);
12096
12097         if (pipe_config->infoframes.enable &
12098             intel_hdmi_infoframe_enable(HDMI_PACKET_TYPE_GENERAL_CONTROL))
12099                 DRM_DEBUG_KMS("GCP: 0x%x\n", pipe_config->infoframes.gcp);
12100         if (pipe_config->infoframes.enable &
12101             intel_hdmi_infoframe_enable(HDMI_INFOFRAME_TYPE_AVI))
12102                 intel_dump_infoframe(dev_priv, &pipe_config->infoframes.avi);
12103         if (pipe_config->infoframes.enable &
12104             intel_hdmi_infoframe_enable(HDMI_INFOFRAME_TYPE_SPD))
12105                 intel_dump_infoframe(dev_priv, &pipe_config->infoframes.spd);
12106         if (pipe_config->infoframes.enable &
12107             intel_hdmi_infoframe_enable(HDMI_INFOFRAME_TYPE_VENDOR))
12108                 intel_dump_infoframe(dev_priv, &pipe_config->infoframes.hdmi);
12109
12110         DRM_DEBUG_KMS("requested mode:\n");
12111         drm_mode_debug_printmodeline(&pipe_config->base.mode);
12112         DRM_DEBUG_KMS("adjusted mode:\n");
12113         drm_mode_debug_printmodeline(&pipe_config->base.adjusted_mode);
12114         intel_dump_crtc_timings(&pipe_config->base.adjusted_mode);
12115         DRM_DEBUG_KMS("port clock: %d, pipe src size: %dx%d, pixel rate %d\n",
12116                       pipe_config->port_clock,
12117                       pipe_config->pipe_src_w, pipe_config->pipe_src_h,
12118                       pipe_config->pixel_rate);
12119
12120         if (INTEL_GEN(dev_priv) >= 9)
12121                 DRM_DEBUG_KMS("num_scalers: %d, scaler_users: 0x%x, scaler_id: %d\n",
12122                               crtc->num_scalers,
12123                               pipe_config->scaler_state.scaler_users,
12124                               pipe_config->scaler_state.scaler_id);
12125
12126         if (HAS_GMCH(dev_priv))
12127                 DRM_DEBUG_KMS("gmch pfit: control: 0x%08x, ratios: 0x%08x, lvds border: 0x%08x\n",
12128                               pipe_config->gmch_pfit.control,
12129                               pipe_config->gmch_pfit.pgm_ratios,
12130                               pipe_config->gmch_pfit.lvds_border_bits);
12131         else
12132                 DRM_DEBUG_KMS("pch pfit: pos: 0x%08x, size: 0x%08x, %s, force thru: %s\n",
12133                               pipe_config->pch_pfit.pos,
12134                               pipe_config->pch_pfit.size,
12135                               enableddisabled(pipe_config->pch_pfit.enabled),
12136                               yesno(pipe_config->pch_pfit.force_thru));
12137
12138         DRM_DEBUG_KMS("ips: %i, double wide: %i\n",
12139                       pipe_config->ips_enabled, pipe_config->double_wide);
12140
12141         intel_dpll_dump_hw_state(dev_priv, &pipe_config->dpll_hw_state);
12142
12143         if (IS_CHERRYVIEW(dev_priv))
12144                 DRM_DEBUG_KMS("cgm_mode: 0x%x gamma_mode: 0x%x gamma_enable: %d csc_enable: %d\n",
12145                               pipe_config->cgm_mode, pipe_config->gamma_mode,
12146                               pipe_config->gamma_enable, pipe_config->csc_enable);
12147         else
12148                 DRM_DEBUG_KMS("csc_mode: 0x%x gamma_mode: 0x%x gamma_enable: %d csc_enable: %d\n",
12149                               pipe_config->csc_mode, pipe_config->gamma_mode,
12150                               pipe_config->gamma_enable, pipe_config->csc_enable);
12151
12152 dump_planes:
12153         if (!state)
12154                 return;
12155
12156         for_each_new_intel_plane_in_state(state, plane, plane_state, i) {
12157                 if (plane->pipe == crtc->pipe)
12158                         intel_dump_plane_state(plane_state);
12159         }
12160 }
12161
12162 static bool check_digital_port_conflicts(struct intel_atomic_state *state)
12163 {
12164         struct drm_device *dev = state->base.dev;
12165         struct drm_connector *connector;
12166         struct drm_connector_list_iter conn_iter;
12167         unsigned int used_ports = 0;
12168         unsigned int used_mst_ports = 0;
12169         bool ret = true;
12170
12171         /*
12172          * Walk the connector list instead of the encoder
12173          * list to detect the problem on ddi platforms
12174          * where there's just one encoder per digital port.
12175          */
12176         drm_connector_list_iter_begin(dev, &conn_iter);
12177         drm_for_each_connector_iter(connector, &conn_iter) {
12178                 struct drm_connector_state *connector_state;
12179                 struct intel_encoder *encoder;
12180
12181                 connector_state =
12182                         drm_atomic_get_new_connector_state(&state->base,
12183                                                            connector);
12184                 if (!connector_state)
12185                         connector_state = connector->state;
12186
12187                 if (!connector_state->best_encoder)
12188                         continue;
12189
12190                 encoder = to_intel_encoder(connector_state->best_encoder);
12191
12192                 WARN_ON(!connector_state->crtc);
12193
12194                 switch (encoder->type) {
12195                         unsigned int port_mask;
12196                 case INTEL_OUTPUT_DDI:
12197                         if (WARN_ON(!HAS_DDI(to_i915(dev))))
12198                                 break;
12199                         /* else, fall through */
12200                 case INTEL_OUTPUT_DP:
12201                 case INTEL_OUTPUT_HDMI:
12202                 case INTEL_OUTPUT_EDP:
12203                         port_mask = 1 << encoder->port;
12204
12205                         /* the same port mustn't appear more than once */
12206                         if (used_ports & port_mask)
12207                                 ret = false;
12208
12209                         used_ports |= port_mask;
12210                         break;
12211                 case INTEL_OUTPUT_DP_MST:
12212                         used_mst_ports |=
12213                                 1 << encoder->port;
12214                         break;
12215                 default:
12216                         break;
12217                 }
12218         }
12219         drm_connector_list_iter_end(&conn_iter);
12220
12221         /* can't mix MST and SST/HDMI on the same port */
12222         if (used_ports & used_mst_ports)
12223                 return false;
12224
12225         return ret;
12226 }
12227
12228 static int
12229 clear_intel_crtc_state(struct intel_crtc_state *crtc_state)
12230 {
12231         struct drm_i915_private *dev_priv =
12232                 to_i915(crtc_state->base.crtc->dev);
12233         struct intel_crtc_state *saved_state;
12234
12235         saved_state = kzalloc(sizeof(*saved_state), GFP_KERNEL);
12236         if (!saved_state)
12237                 return -ENOMEM;
12238
12239         /* FIXME: before the switch to atomic started, a new pipe_config was
12240          * kzalloc'd. Code that depends on any field being zero should be
12241          * fixed, so that the crtc_state can be safely duplicated. For now,
12242          * only fields that are know to not cause problems are preserved. */
12243
12244         saved_state->scaler_state = crtc_state->scaler_state;
12245         saved_state->shared_dpll = crtc_state->shared_dpll;
12246         saved_state->dpll_hw_state = crtc_state->dpll_hw_state;
12247         memcpy(saved_state->icl_port_dplls, crtc_state->icl_port_dplls,
12248                sizeof(saved_state->icl_port_dplls));
12249         saved_state->crc_enabled = crtc_state->crc_enabled;
12250         if (IS_G4X(dev_priv) ||
12251             IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
12252                 saved_state->wm = crtc_state->wm;
12253
12254         /* Keep base drm_crtc_state intact, only clear our extended struct */
12255         BUILD_BUG_ON(offsetof(struct intel_crtc_state, base));
12256         memcpy(&crtc_state->base + 1, &saved_state->base + 1,
12257                sizeof(*crtc_state) - sizeof(crtc_state->base));
12258
12259         kfree(saved_state);
12260         return 0;
12261 }
12262
12263 static int
12264 intel_modeset_pipe_config(struct intel_crtc_state *pipe_config)
12265 {
12266         struct drm_crtc *crtc = pipe_config->base.crtc;
12267         struct drm_atomic_state *state = pipe_config->base.state;
12268         struct intel_encoder *encoder;
12269         struct drm_connector *connector;
12270         struct drm_connector_state *connector_state;
12271         int base_bpp, ret;
12272         int i;
12273         bool retry = true;
12274
12275         ret = clear_intel_crtc_state(pipe_config);
12276         if (ret)
12277                 return ret;
12278
12279         pipe_config->cpu_transcoder =
12280                 (enum transcoder) to_intel_crtc(crtc)->pipe;
12281
12282         /*
12283          * Sanitize sync polarity flags based on requested ones. If neither
12284          * positive or negative polarity is requested, treat this as meaning
12285          * negative polarity.
12286          */
12287         if (!(pipe_config->base.adjusted_mode.flags &
12288               (DRM_MODE_FLAG_PHSYNC | DRM_MODE_FLAG_NHSYNC)))
12289                 pipe_config->base.adjusted_mode.flags |= DRM_MODE_FLAG_NHSYNC;
12290
12291         if (!(pipe_config->base.adjusted_mode.flags &
12292               (DRM_MODE_FLAG_PVSYNC | DRM_MODE_FLAG_NVSYNC)))
12293                 pipe_config->base.adjusted_mode.flags |= DRM_MODE_FLAG_NVSYNC;
12294
12295         ret = compute_baseline_pipe_bpp(to_intel_crtc(crtc),
12296                                         pipe_config);
12297         if (ret)
12298                 return ret;
12299
12300         base_bpp = pipe_config->pipe_bpp;
12301
12302         /*
12303          * Determine the real pipe dimensions. Note that stereo modes can
12304          * increase the actual pipe size due to the frame doubling and
12305          * insertion of additional space for blanks between the frame. This
12306          * is stored in the crtc timings. We use the requested mode to do this
12307          * computation to clearly distinguish it from the adjusted mode, which
12308          * can be changed by the connectors in the below retry loop.
12309          */
12310         drm_mode_get_hv_timing(&pipe_config->base.mode,
12311                                &pipe_config->pipe_src_w,
12312                                &pipe_config->pipe_src_h);
12313
12314         for_each_new_connector_in_state(state, connector, connector_state, i) {
12315                 if (connector_state->crtc != crtc)
12316                         continue;
12317
12318                 encoder = to_intel_encoder(connector_state->best_encoder);
12319
12320                 if (!check_single_encoder_cloning(state, to_intel_crtc(crtc), encoder)) {
12321                         DRM_DEBUG_KMS("rejecting invalid cloning configuration\n");
12322                         return -EINVAL;
12323                 }
12324
12325                 /*
12326                  * Determine output_types before calling the .compute_config()
12327                  * hooks so that the hooks can use this information safely.
12328                  */
12329                 if (encoder->compute_output_type)
12330                         pipe_config->output_types |=
12331                                 BIT(encoder->compute_output_type(encoder, pipe_config,
12332                                                                  connector_state));
12333                 else
12334                         pipe_config->output_types |= BIT(encoder->type);
12335         }
12336
12337 encoder_retry:
12338         /* Ensure the port clock defaults are reset when retrying. */
12339         pipe_config->port_clock = 0;
12340         pipe_config->pixel_multiplier = 1;
12341
12342         /* Fill in default crtc timings, allow encoders to overwrite them. */
12343         drm_mode_set_crtcinfo(&pipe_config->base.adjusted_mode,
12344                               CRTC_STEREO_DOUBLE);
12345
12346         /* Pass our mode to the connectors and the CRTC to give them a chance to
12347          * adjust it according to limitations or connector properties, and also
12348          * a chance to reject the mode entirely.
12349          */
12350         for_each_new_connector_in_state(state, connector, connector_state, i) {
12351                 if (connector_state->crtc != crtc)
12352                         continue;
12353
12354                 encoder = to_intel_encoder(connector_state->best_encoder);
12355                 ret = encoder->compute_config(encoder, pipe_config,
12356                                               connector_state);
12357                 if (ret < 0) {
12358                         if (ret != -EDEADLK)
12359                                 DRM_DEBUG_KMS("Encoder config failure: %d\n",
12360                                               ret);
12361                         return ret;
12362                 }
12363         }
12364
12365         /* Set default port clock if not overwritten by the encoder. Needs to be
12366          * done afterwards in case the encoder adjusts the mode. */
12367         if (!pipe_config->port_clock)
12368                 pipe_config->port_clock = pipe_config->base.adjusted_mode.crtc_clock
12369                         * pipe_config->pixel_multiplier;
12370
12371         ret = intel_crtc_compute_config(to_intel_crtc(crtc), pipe_config);
12372         if (ret == -EDEADLK)
12373                 return ret;
12374         if (ret < 0) {
12375                 DRM_DEBUG_KMS("CRTC fixup failed\n");
12376                 return ret;
12377         }
12378
12379         if (ret == RETRY) {
12380                 if (WARN(!retry, "loop in pipe configuration computation\n"))
12381                         return -EINVAL;
12382
12383                 DRM_DEBUG_KMS("CRTC bw constrained, retrying\n");
12384                 retry = false;
12385                 goto encoder_retry;
12386         }
12387
12388         /* Dithering seems to not pass-through bits correctly when it should, so
12389          * only enable it on 6bpc panels and when its not a compliance
12390          * test requesting 6bpc video pattern.
12391          */
12392         pipe_config->dither = (pipe_config->pipe_bpp == 6*3) &&
12393                 !pipe_config->dither_force_disable;
12394         DRM_DEBUG_KMS("hw max bpp: %i, pipe bpp: %i, dithering: %i\n",
12395                       base_bpp, pipe_config->pipe_bpp, pipe_config->dither);
12396
12397         return 0;
12398 }
12399
12400 bool intel_fuzzy_clock_check(int clock1, int clock2)
12401 {
12402         int diff;
12403
12404         if (clock1 == clock2)
12405                 return true;
12406
12407         if (!clock1 || !clock2)
12408                 return false;
12409
12410         diff = abs(clock1 - clock2);
12411
12412         if (((((diff + clock1 + clock2) * 100)) / (clock1 + clock2)) < 105)
12413                 return true;
12414
12415         return false;
12416 }
12417
12418 static bool
12419 intel_compare_m_n(unsigned int m, unsigned int n,
12420                   unsigned int m2, unsigned int n2,
12421                   bool exact)
12422 {
12423         if (m == m2 && n == n2)
12424                 return true;
12425
12426         if (exact || !m || !n || !m2 || !n2)
12427                 return false;
12428
12429         BUILD_BUG_ON(DATA_LINK_M_N_MASK > INT_MAX);
12430
12431         if (n > n2) {
12432                 while (n > n2) {
12433                         m2 <<= 1;
12434                         n2 <<= 1;
12435                 }
12436         } else if (n < n2) {
12437                 while (n < n2) {
12438                         m <<= 1;
12439                         n <<= 1;
12440                 }
12441         }
12442
12443         if (n != n2)
12444                 return false;
12445
12446         return intel_fuzzy_clock_check(m, m2);
12447 }
12448
12449 static bool
12450 intel_compare_link_m_n(const struct intel_link_m_n *m_n,
12451                        const struct intel_link_m_n *m2_n2,
12452                        bool exact)
12453 {
12454         return m_n->tu == m2_n2->tu &&
12455                 intel_compare_m_n(m_n->gmch_m, m_n->gmch_n,
12456                                   m2_n2->gmch_m, m2_n2->gmch_n, exact) &&
12457                 intel_compare_m_n(m_n->link_m, m_n->link_n,
12458                                   m2_n2->link_m, m2_n2->link_n, exact);
12459 }
12460
12461 static bool
12462 intel_compare_infoframe(const union hdmi_infoframe *a,
12463                         const union hdmi_infoframe *b)
12464 {
12465         return memcmp(a, b, sizeof(*a)) == 0;
12466 }
12467
12468 static void
12469 pipe_config_infoframe_mismatch(struct drm_i915_private *dev_priv,
12470                                bool fastset, const char *name,
12471                                const union hdmi_infoframe *a,
12472                                const union hdmi_infoframe *b)
12473 {
12474         if (fastset) {
12475                 if ((drm_debug & DRM_UT_KMS) == 0)
12476                         return;
12477
12478                 drm_dbg(DRM_UT_KMS, "fastset mismatch in %s infoframe", name);
12479                 drm_dbg(DRM_UT_KMS, "expected:");
12480                 hdmi_infoframe_log(KERN_DEBUG, dev_priv->drm.dev, a);
12481                 drm_dbg(DRM_UT_KMS, "found");
12482                 hdmi_infoframe_log(KERN_DEBUG, dev_priv->drm.dev, b);
12483         } else {
12484                 drm_err("mismatch in %s infoframe", name);
12485                 drm_err("expected:");
12486                 hdmi_infoframe_log(KERN_ERR, dev_priv->drm.dev, a);
12487                 drm_err("found");
12488                 hdmi_infoframe_log(KERN_ERR, dev_priv->drm.dev, b);
12489         }
12490 }
12491
12492 static void __printf(3, 4)
12493 pipe_config_mismatch(bool fastset, const char *name, const char *format, ...)
12494 {
12495         struct va_format vaf;
12496         va_list args;
12497
12498         va_start(args, format);
12499         vaf.fmt = format;
12500         vaf.va = &args;
12501
12502         if (fastset)
12503                 drm_dbg(DRM_UT_KMS, "fastset mismatch in %s %pV", name, &vaf);
12504         else
12505                 drm_err("mismatch in %s %pV", name, &vaf);
12506
12507         va_end(args);
12508 }
12509
12510 static bool fastboot_enabled(struct drm_i915_private *dev_priv)
12511 {
12512         if (i915_modparams.fastboot != -1)
12513                 return i915_modparams.fastboot;
12514
12515         /* Enable fastboot by default on Skylake and newer */
12516         if (INTEL_GEN(dev_priv) >= 9)
12517                 return true;
12518
12519         /* Enable fastboot by default on VLV and CHV */
12520         if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
12521                 return true;
12522
12523         /* Disabled by default on all others */
12524         return false;
12525 }
12526
12527 static bool
12528 intel_pipe_config_compare(const struct intel_crtc_state *current_config,
12529                           const struct intel_crtc_state *pipe_config,
12530                           bool fastset)
12531 {
12532         struct drm_i915_private *dev_priv = to_i915(current_config->base.crtc->dev);
12533         bool ret = true;
12534         u32 bp_gamma = 0;
12535         bool fixup_inherited = fastset &&
12536                 (current_config->base.mode.private_flags & I915_MODE_FLAG_INHERITED) &&
12537                 !(pipe_config->base.mode.private_flags & I915_MODE_FLAG_INHERITED);
12538
12539         if (fixup_inherited && !fastboot_enabled(dev_priv)) {
12540                 DRM_DEBUG_KMS("initial modeset and fastboot not set\n");
12541                 ret = false;
12542         }
12543
12544 #define PIPE_CONF_CHECK_X(name) do { \
12545         if (current_config->name != pipe_config->name) { \
12546                 pipe_config_mismatch(fastset, __stringify(name), \
12547                                      "(expected 0x%08x, found 0x%08x)\n", \
12548                                      current_config->name, \
12549                                      pipe_config->name); \
12550                 ret = false; \
12551         } \
12552 } while (0)
12553
12554 #define PIPE_CONF_CHECK_I(name) do { \
12555         if (current_config->name != pipe_config->name) { \
12556                 pipe_config_mismatch(fastset, __stringify(name), \
12557                                      "(expected %i, found %i)\n", \
12558                                      current_config->name, \
12559                                      pipe_config->name); \
12560                 ret = false; \
12561         } \
12562 } while (0)
12563
12564 #define PIPE_CONF_CHECK_BOOL(name) do { \
12565         if (current_config->name != pipe_config->name) { \
12566                 pipe_config_mismatch(fastset, __stringify(name), \
12567                                      "(expected %s, found %s)\n", \
12568                                      yesno(current_config->name), \
12569                                      yesno(pipe_config->name)); \
12570                 ret = false; \
12571         } \
12572 } while (0)
12573
12574 /*
12575  * Checks state where we only read out the enabling, but not the entire
12576  * state itself (like full infoframes or ELD for audio). These states
12577  * require a full modeset on bootup to fix up.
12578  */
12579 #define PIPE_CONF_CHECK_BOOL_INCOMPLETE(name) do { \
12580         if (!fixup_inherited || (!current_config->name && !pipe_config->name)) { \
12581                 PIPE_CONF_CHECK_BOOL(name); \
12582         } else { \
12583                 pipe_config_mismatch(fastset, __stringify(name), \
12584                                      "unable to verify whether state matches exactly, forcing modeset (expected %s, found %s)\n", \
12585                                      yesno(current_config->name), \
12586                                      yesno(pipe_config->name)); \
12587                 ret = false; \
12588         } \
12589 } while (0)
12590
12591 #define PIPE_CONF_CHECK_P(name) do { \
12592         if (current_config->name != pipe_config->name) { \
12593                 pipe_config_mismatch(fastset, __stringify(name), \
12594                                      "(expected %p, found %p)\n", \
12595                                      current_config->name, \
12596                                      pipe_config->name); \
12597                 ret = false; \
12598         } \
12599 } while (0)
12600
12601 #define PIPE_CONF_CHECK_M_N(name) do { \
12602         if (!intel_compare_link_m_n(&current_config->name, \
12603                                     &pipe_config->name,\
12604                                     !fastset)) { \
12605                 pipe_config_mismatch(fastset, __stringify(name), \
12606                                      "(expected tu %i gmch %i/%i link %i/%i, " \
12607                                      "found tu %i, gmch %i/%i link %i/%i)\n", \
12608                                      current_config->name.tu, \
12609                                      current_config->name.gmch_m, \
12610                                      current_config->name.gmch_n, \
12611                                      current_config->name.link_m, \
12612                                      current_config->name.link_n, \
12613                                      pipe_config->name.tu, \
12614                                      pipe_config->name.gmch_m, \
12615                                      pipe_config->name.gmch_n, \
12616                                      pipe_config->name.link_m, \
12617                                      pipe_config->name.link_n); \
12618                 ret = false; \
12619         } \
12620 } while (0)
12621
12622 /* This is required for BDW+ where there is only one set of registers for
12623  * switching between high and low RR.
12624  * This macro can be used whenever a comparison has to be made between one
12625  * hw state and multiple sw state variables.
12626  */
12627 #define PIPE_CONF_CHECK_M_N_ALT(name, alt_name) do { \
12628         if (!intel_compare_link_m_n(&current_config->name, \
12629                                     &pipe_config->name, !fastset) && \
12630             !intel_compare_link_m_n(&current_config->alt_name, \
12631                                     &pipe_config->name, !fastset)) { \
12632                 pipe_config_mismatch(fastset, __stringify(name), \
12633                                      "(expected tu %i gmch %i/%i link %i/%i, " \
12634                                      "or tu %i gmch %i/%i link %i/%i, " \
12635                                      "found tu %i, gmch %i/%i link %i/%i)\n", \
12636                                      current_config->name.tu, \
12637                                      current_config->name.gmch_m, \
12638                                      current_config->name.gmch_n, \
12639                                      current_config->name.link_m, \
12640                                      current_config->name.link_n, \
12641                                      current_config->alt_name.tu, \
12642                                      current_config->alt_name.gmch_m, \
12643                                      current_config->alt_name.gmch_n, \
12644                                      current_config->alt_name.link_m, \
12645                                      current_config->alt_name.link_n, \
12646                                      pipe_config->name.tu, \
12647                                      pipe_config->name.gmch_m, \
12648                                      pipe_config->name.gmch_n, \
12649                                      pipe_config->name.link_m, \
12650                                      pipe_config->name.link_n); \
12651                 ret = false; \
12652         } \
12653 } while (0)
12654
12655 #define PIPE_CONF_CHECK_FLAGS(name, mask) do { \
12656         if ((current_config->name ^ pipe_config->name) & (mask)) { \
12657                 pipe_config_mismatch(fastset, __stringify(name), \
12658                                      "(%x) (expected %i, found %i)\n", \
12659                                      (mask), \
12660                                      current_config->name & (mask), \
12661                                      pipe_config->name & (mask)); \
12662                 ret = false; \
12663         } \
12664 } while (0)
12665
12666 #define PIPE_CONF_CHECK_CLOCK_FUZZY(name) do { \
12667         if (!intel_fuzzy_clock_check(current_config->name, pipe_config->name)) { \
12668                 pipe_config_mismatch(fastset, __stringify(name), \
12669                                      "(expected %i, found %i)\n", \
12670                                      current_config->name, \
12671                                      pipe_config->name); \
12672                 ret = false; \
12673         } \
12674 } while (0)
12675
12676 #define PIPE_CONF_CHECK_INFOFRAME(name) do { \
12677         if (!intel_compare_infoframe(&current_config->infoframes.name, \
12678                                      &pipe_config->infoframes.name)) { \
12679                 pipe_config_infoframe_mismatch(dev_priv, fastset, __stringify(name), \
12680                                                &current_config->infoframes.name, \
12681                                                &pipe_config->infoframes.name); \
12682                 ret = false; \
12683         } \
12684 } while (0)
12685
12686 #define PIPE_CONF_CHECK_COLOR_LUT(name1, name2, bit_precision) do { \
12687         if (current_config->name1 != pipe_config->name1) { \
12688                 pipe_config_mismatch(fastset, __stringify(name1), \
12689                                 "(expected %i, found %i, won't compare lut values)\n", \
12690                                 current_config->name1, \
12691                                 pipe_config->name1); \
12692                 ret = false;\
12693         } else { \
12694                 if (!intel_color_lut_equal(current_config->name2, \
12695                                         pipe_config->name2, pipe_config->name1, \
12696                                         bit_precision)) { \
12697                         pipe_config_mismatch(fastset, __stringify(name2), \
12698                                         "hw_state doesn't match sw_state\n"); \
12699                         ret = false; \
12700                 } \
12701         } \
12702 } while (0)
12703
12704 #define PIPE_CONF_QUIRK(quirk) \
12705         ((current_config->quirks | pipe_config->quirks) & (quirk))
12706
12707         PIPE_CONF_CHECK_I(cpu_transcoder);
12708
12709         PIPE_CONF_CHECK_BOOL(has_pch_encoder);
12710         PIPE_CONF_CHECK_I(fdi_lanes);
12711         PIPE_CONF_CHECK_M_N(fdi_m_n);
12712
12713         PIPE_CONF_CHECK_I(lane_count);
12714         PIPE_CONF_CHECK_X(lane_lat_optim_mask);
12715
12716         if (INTEL_GEN(dev_priv) < 8) {
12717                 PIPE_CONF_CHECK_M_N(dp_m_n);
12718
12719                 if (current_config->has_drrs)
12720                         PIPE_CONF_CHECK_M_N(dp_m2_n2);
12721         } else
12722                 PIPE_CONF_CHECK_M_N_ALT(dp_m_n, dp_m2_n2);
12723
12724         PIPE_CONF_CHECK_X(output_types);
12725
12726         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hdisplay);
12727         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_htotal);
12728         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hblank_start);
12729         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hblank_end);
12730         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hsync_start);
12731         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hsync_end);
12732
12733         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vdisplay);
12734         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vtotal);
12735         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vblank_start);
12736         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vblank_end);
12737         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vsync_start);
12738         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vsync_end);
12739
12740         PIPE_CONF_CHECK_I(pixel_multiplier);
12741         PIPE_CONF_CHECK_I(output_format);
12742         PIPE_CONF_CHECK_BOOL(has_hdmi_sink);
12743         if ((INTEL_GEN(dev_priv) < 8 && !IS_HASWELL(dev_priv)) ||
12744             IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
12745                 PIPE_CONF_CHECK_BOOL(limited_color_range);
12746
12747         PIPE_CONF_CHECK_BOOL(hdmi_scrambling);
12748         PIPE_CONF_CHECK_BOOL(hdmi_high_tmds_clock_ratio);
12749         PIPE_CONF_CHECK_BOOL(has_infoframe);
12750
12751         PIPE_CONF_CHECK_BOOL_INCOMPLETE(has_audio);
12752
12753         PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
12754                               DRM_MODE_FLAG_INTERLACE);
12755
12756         if (!PIPE_CONF_QUIRK(PIPE_CONFIG_QUIRK_MODE_SYNC_FLAGS)) {
12757                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
12758                                       DRM_MODE_FLAG_PHSYNC);
12759                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
12760                                       DRM_MODE_FLAG_NHSYNC);
12761                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
12762                                       DRM_MODE_FLAG_PVSYNC);
12763                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
12764                                       DRM_MODE_FLAG_NVSYNC);
12765         }
12766
12767         PIPE_CONF_CHECK_X(gmch_pfit.control);
12768         /* pfit ratios are autocomputed by the hw on gen4+ */
12769         if (INTEL_GEN(dev_priv) < 4)
12770                 PIPE_CONF_CHECK_X(gmch_pfit.pgm_ratios);
12771         PIPE_CONF_CHECK_X(gmch_pfit.lvds_border_bits);
12772
12773         /*
12774          * Changing the EDP transcoder input mux
12775          * (A_ONOFF vs. A_ON) requires a full modeset.
12776          */
12777         PIPE_CONF_CHECK_BOOL(pch_pfit.force_thru);
12778
12779         if (!fastset) {
12780                 PIPE_CONF_CHECK_I(pipe_src_w);
12781                 PIPE_CONF_CHECK_I(pipe_src_h);
12782
12783                 PIPE_CONF_CHECK_BOOL(pch_pfit.enabled);
12784                 if (current_config->pch_pfit.enabled) {
12785                         PIPE_CONF_CHECK_X(pch_pfit.pos);
12786                         PIPE_CONF_CHECK_X(pch_pfit.size);
12787                 }
12788
12789                 PIPE_CONF_CHECK_I(scaler_state.scaler_id);
12790                 PIPE_CONF_CHECK_CLOCK_FUZZY(pixel_rate);
12791
12792                 PIPE_CONF_CHECK_X(gamma_mode);
12793                 if (IS_CHERRYVIEW(dev_priv))
12794                         PIPE_CONF_CHECK_X(cgm_mode);
12795                 else
12796                         PIPE_CONF_CHECK_X(csc_mode);
12797                 PIPE_CONF_CHECK_BOOL(gamma_enable);
12798                 PIPE_CONF_CHECK_BOOL(csc_enable);
12799
12800                 bp_gamma = intel_color_get_gamma_bit_precision(pipe_config);
12801                 if (bp_gamma)
12802                         PIPE_CONF_CHECK_COLOR_LUT(gamma_mode, base.gamma_lut, bp_gamma);
12803
12804         }
12805
12806         PIPE_CONF_CHECK_BOOL(double_wide);
12807
12808         PIPE_CONF_CHECK_P(shared_dpll);
12809         PIPE_CONF_CHECK_X(dpll_hw_state.dpll);
12810         PIPE_CONF_CHECK_X(dpll_hw_state.dpll_md);
12811         PIPE_CONF_CHECK_X(dpll_hw_state.fp0);
12812         PIPE_CONF_CHECK_X(dpll_hw_state.fp1);
12813         PIPE_CONF_CHECK_X(dpll_hw_state.wrpll);
12814         PIPE_CONF_CHECK_X(dpll_hw_state.spll);
12815         PIPE_CONF_CHECK_X(dpll_hw_state.ctrl1);
12816         PIPE_CONF_CHECK_X(dpll_hw_state.cfgcr1);
12817         PIPE_CONF_CHECK_X(dpll_hw_state.cfgcr2);
12818         PIPE_CONF_CHECK_X(dpll_hw_state.cfgcr0);
12819         PIPE_CONF_CHECK_X(dpll_hw_state.ebb0);
12820         PIPE_CONF_CHECK_X(dpll_hw_state.ebb4);
12821         PIPE_CONF_CHECK_X(dpll_hw_state.pll0);
12822         PIPE_CONF_CHECK_X(dpll_hw_state.pll1);
12823         PIPE_CONF_CHECK_X(dpll_hw_state.pll2);
12824         PIPE_CONF_CHECK_X(dpll_hw_state.pll3);
12825         PIPE_CONF_CHECK_X(dpll_hw_state.pll6);
12826         PIPE_CONF_CHECK_X(dpll_hw_state.pll8);
12827         PIPE_CONF_CHECK_X(dpll_hw_state.pll9);
12828         PIPE_CONF_CHECK_X(dpll_hw_state.pll10);
12829         PIPE_CONF_CHECK_X(dpll_hw_state.pcsdw12);
12830         PIPE_CONF_CHECK_X(dpll_hw_state.mg_refclkin_ctl);
12831         PIPE_CONF_CHECK_X(dpll_hw_state.mg_clktop2_coreclkctl1);
12832         PIPE_CONF_CHECK_X(dpll_hw_state.mg_clktop2_hsclkctl);
12833         PIPE_CONF_CHECK_X(dpll_hw_state.mg_pll_div0);
12834         PIPE_CONF_CHECK_X(dpll_hw_state.mg_pll_div1);
12835         PIPE_CONF_CHECK_X(dpll_hw_state.mg_pll_lf);
12836         PIPE_CONF_CHECK_X(dpll_hw_state.mg_pll_frac_lock);
12837         PIPE_CONF_CHECK_X(dpll_hw_state.mg_pll_ssc);
12838         PIPE_CONF_CHECK_X(dpll_hw_state.mg_pll_bias);
12839         PIPE_CONF_CHECK_X(dpll_hw_state.mg_pll_tdc_coldst_bias);
12840
12841         PIPE_CONF_CHECK_X(dsi_pll.ctrl);
12842         PIPE_CONF_CHECK_X(dsi_pll.div);
12843
12844         if (IS_G4X(dev_priv) || INTEL_GEN(dev_priv) >= 5)
12845                 PIPE_CONF_CHECK_I(pipe_bpp);
12846
12847         PIPE_CONF_CHECK_CLOCK_FUZZY(base.adjusted_mode.crtc_clock);
12848         PIPE_CONF_CHECK_CLOCK_FUZZY(port_clock);
12849
12850         PIPE_CONF_CHECK_I(min_voltage_level);
12851
12852         PIPE_CONF_CHECK_X(infoframes.enable);
12853         PIPE_CONF_CHECK_X(infoframes.gcp);
12854         PIPE_CONF_CHECK_INFOFRAME(avi);
12855         PIPE_CONF_CHECK_INFOFRAME(spd);
12856         PIPE_CONF_CHECK_INFOFRAME(hdmi);
12857         PIPE_CONF_CHECK_INFOFRAME(drm);
12858
12859 #undef PIPE_CONF_CHECK_X
12860 #undef PIPE_CONF_CHECK_I
12861 #undef PIPE_CONF_CHECK_BOOL
12862 #undef PIPE_CONF_CHECK_BOOL_INCOMPLETE
12863 #undef PIPE_CONF_CHECK_P
12864 #undef PIPE_CONF_CHECK_FLAGS
12865 #undef PIPE_CONF_CHECK_CLOCK_FUZZY
12866 #undef PIPE_CONF_CHECK_COLOR_LUT
12867 #undef PIPE_CONF_QUIRK
12868
12869         return ret;
12870 }
12871
12872 static void intel_pipe_config_sanity_check(struct drm_i915_private *dev_priv,
12873                                            const struct intel_crtc_state *pipe_config)
12874 {
12875         if (pipe_config->has_pch_encoder) {
12876                 int fdi_dotclock = intel_dotclock_calculate(intel_fdi_link_freq(dev_priv, pipe_config),
12877                                                             &pipe_config->fdi_m_n);
12878                 int dotclock = pipe_config->base.adjusted_mode.crtc_clock;
12879
12880                 /*
12881                  * FDI already provided one idea for the dotclock.
12882                  * Yell if the encoder disagrees.
12883                  */
12884                 WARN(!intel_fuzzy_clock_check(fdi_dotclock, dotclock),
12885                      "FDI dotclock and encoder dotclock mismatch, fdi: %i, encoder: %i\n",
12886                      fdi_dotclock, dotclock);
12887         }
12888 }
12889
12890 static void verify_wm_state(struct intel_crtc *crtc,
12891                             struct intel_crtc_state *new_crtc_state)
12892 {
12893         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
12894         struct skl_hw_state {
12895                 struct skl_ddb_entry ddb_y[I915_MAX_PLANES];
12896                 struct skl_ddb_entry ddb_uv[I915_MAX_PLANES];
12897                 struct skl_ddb_allocation ddb;
12898                 struct skl_pipe_wm wm;
12899         } *hw;
12900         struct skl_ddb_allocation *sw_ddb;
12901         struct skl_pipe_wm *sw_wm;
12902         struct skl_ddb_entry *hw_ddb_entry, *sw_ddb_entry;
12903         const enum pipe pipe = crtc->pipe;
12904         int plane, level, max_level = ilk_wm_max_level(dev_priv);
12905
12906         if (INTEL_GEN(dev_priv) < 9 || !new_crtc_state->base.active)
12907                 return;
12908
12909         hw = kzalloc(sizeof(*hw), GFP_KERNEL);
12910         if (!hw)
12911                 return;
12912
12913         skl_pipe_wm_get_hw_state(crtc, &hw->wm);
12914         sw_wm = &new_crtc_state->wm.skl.optimal;
12915
12916         skl_pipe_ddb_get_hw_state(crtc, hw->ddb_y, hw->ddb_uv);
12917
12918         skl_ddb_get_hw_state(dev_priv, &hw->ddb);
12919         sw_ddb = &dev_priv->wm.skl_hw.ddb;
12920
12921         if (INTEL_GEN(dev_priv) >= 11 &&
12922             hw->ddb.enabled_slices != sw_ddb->enabled_slices)
12923                 DRM_ERROR("mismatch in DBUF Slices (expected %u, got %u)\n",
12924                           sw_ddb->enabled_slices,
12925                           hw->ddb.enabled_slices);
12926
12927         /* planes */
12928         for_each_universal_plane(dev_priv, pipe, plane) {
12929                 struct skl_plane_wm *hw_plane_wm, *sw_plane_wm;
12930
12931                 hw_plane_wm = &hw->wm.planes[plane];
12932                 sw_plane_wm = &sw_wm->planes[plane];
12933
12934                 /* Watermarks */
12935                 for (level = 0; level <= max_level; level++) {
12936                         if (skl_wm_level_equals(&hw_plane_wm->wm[level],
12937                                                 &sw_plane_wm->wm[level]))
12938                                 continue;
12939
12940                         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",
12941                                   pipe_name(pipe), plane + 1, level,
12942                                   sw_plane_wm->wm[level].plane_en,
12943                                   sw_plane_wm->wm[level].plane_res_b,
12944                                   sw_plane_wm->wm[level].plane_res_l,
12945                                   hw_plane_wm->wm[level].plane_en,
12946                                   hw_plane_wm->wm[level].plane_res_b,
12947                                   hw_plane_wm->wm[level].plane_res_l);
12948                 }
12949
12950                 if (!skl_wm_level_equals(&hw_plane_wm->trans_wm,
12951                                          &sw_plane_wm->trans_wm)) {
12952                         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",
12953                                   pipe_name(pipe), plane + 1,
12954                                   sw_plane_wm->trans_wm.plane_en,
12955                                   sw_plane_wm->trans_wm.plane_res_b,
12956                                   sw_plane_wm->trans_wm.plane_res_l,
12957                                   hw_plane_wm->trans_wm.plane_en,
12958                                   hw_plane_wm->trans_wm.plane_res_b,
12959                                   hw_plane_wm->trans_wm.plane_res_l);
12960                 }
12961
12962                 /* DDB */
12963                 hw_ddb_entry = &hw->ddb_y[plane];
12964                 sw_ddb_entry = &new_crtc_state->wm.skl.plane_ddb_y[plane];
12965
12966                 if (!skl_ddb_entry_equal(hw_ddb_entry, sw_ddb_entry)) {
12967                         DRM_ERROR("mismatch in DDB state pipe %c plane %d (expected (%u,%u), found (%u,%u))\n",
12968                                   pipe_name(pipe), plane + 1,
12969                                   sw_ddb_entry->start, sw_ddb_entry->end,
12970                                   hw_ddb_entry->start, hw_ddb_entry->end);
12971                 }
12972         }
12973
12974         /*
12975          * cursor
12976          * If the cursor plane isn't active, we may not have updated it's ddb
12977          * allocation. In that case since the ddb allocation will be updated
12978          * once the plane becomes visible, we can skip this check
12979          */
12980         if (1) {
12981                 struct skl_plane_wm *hw_plane_wm, *sw_plane_wm;
12982
12983                 hw_plane_wm = &hw->wm.planes[PLANE_CURSOR];
12984                 sw_plane_wm = &sw_wm->planes[PLANE_CURSOR];
12985
12986                 /* Watermarks */
12987                 for (level = 0; level <= max_level; level++) {
12988                         if (skl_wm_level_equals(&hw_plane_wm->wm[level],
12989                                                 &sw_plane_wm->wm[level]))
12990                                 continue;
12991
12992                         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",
12993                                   pipe_name(pipe), level,
12994                                   sw_plane_wm->wm[level].plane_en,
12995                                   sw_plane_wm->wm[level].plane_res_b,
12996                                   sw_plane_wm->wm[level].plane_res_l,
12997                                   hw_plane_wm->wm[level].plane_en,
12998                                   hw_plane_wm->wm[level].plane_res_b,
12999                                   hw_plane_wm->wm[level].plane_res_l);
13000                 }
13001
13002                 if (!skl_wm_level_equals(&hw_plane_wm->trans_wm,
13003                                          &sw_plane_wm->trans_wm)) {
13004                         DRM_ERROR("mismatch in trans WM pipe %c cursor (expected e=%d b=%u l=%u, got e=%d b=%u l=%u)\n",
13005                                   pipe_name(pipe),
13006                                   sw_plane_wm->trans_wm.plane_en,
13007                                   sw_plane_wm->trans_wm.plane_res_b,
13008                                   sw_plane_wm->trans_wm.plane_res_l,
13009                                   hw_plane_wm->trans_wm.plane_en,
13010                                   hw_plane_wm->trans_wm.plane_res_b,
13011                                   hw_plane_wm->trans_wm.plane_res_l);
13012                 }
13013
13014                 /* DDB */
13015                 hw_ddb_entry = &hw->ddb_y[PLANE_CURSOR];
13016                 sw_ddb_entry = &new_crtc_state->wm.skl.plane_ddb_y[PLANE_CURSOR];
13017
13018                 if (!skl_ddb_entry_equal(hw_ddb_entry, sw_ddb_entry)) {
13019                         DRM_ERROR("mismatch in DDB state pipe %c cursor (expected (%u,%u), found (%u,%u))\n",
13020                                   pipe_name(pipe),
13021                                   sw_ddb_entry->start, sw_ddb_entry->end,
13022                                   hw_ddb_entry->start, hw_ddb_entry->end);
13023                 }
13024         }
13025
13026         kfree(hw);
13027 }
13028
13029 static void
13030 verify_connector_state(struct intel_atomic_state *state,
13031                        struct intel_crtc *crtc)
13032 {
13033         struct drm_connector *connector;
13034         struct drm_connector_state *new_conn_state;
13035         int i;
13036
13037         for_each_new_connector_in_state(&state->base, connector, new_conn_state, i) {
13038                 struct drm_encoder *encoder = connector->encoder;
13039                 struct intel_crtc_state *crtc_state = NULL;
13040
13041                 if (new_conn_state->crtc != &crtc->base)
13042                         continue;
13043
13044                 if (crtc)
13045                         crtc_state = intel_atomic_get_new_crtc_state(state, crtc);
13046
13047                 intel_connector_verify_state(crtc_state, new_conn_state);
13048
13049                 I915_STATE_WARN(new_conn_state->best_encoder != encoder,
13050                      "connector's atomic encoder doesn't match legacy encoder\n");
13051         }
13052 }
13053
13054 static void
13055 verify_encoder_state(struct drm_i915_private *dev_priv, struct intel_atomic_state *state)
13056 {
13057         struct intel_encoder *encoder;
13058         struct drm_connector *connector;
13059         struct drm_connector_state *old_conn_state, *new_conn_state;
13060         int i;
13061
13062         for_each_intel_encoder(&dev_priv->drm, encoder) {
13063                 bool enabled = false, found = false;
13064                 enum pipe pipe;
13065
13066                 DRM_DEBUG_KMS("[ENCODER:%d:%s]\n",
13067                               encoder->base.base.id,
13068                               encoder->base.name);
13069
13070                 for_each_oldnew_connector_in_state(&state->base, connector, old_conn_state,
13071                                                    new_conn_state, i) {
13072                         if (old_conn_state->best_encoder == &encoder->base)
13073                                 found = true;
13074
13075                         if (new_conn_state->best_encoder != &encoder->base)
13076                                 continue;
13077                         found = enabled = true;
13078
13079                         I915_STATE_WARN(new_conn_state->crtc !=
13080                                         encoder->base.crtc,
13081                              "connector's crtc doesn't match encoder crtc\n");
13082                 }
13083
13084                 if (!found)
13085                         continue;
13086
13087                 I915_STATE_WARN(!!encoder->base.crtc != enabled,
13088                      "encoder's enabled state mismatch "
13089                      "(expected %i, found %i)\n",
13090                      !!encoder->base.crtc, enabled);
13091
13092                 if (!encoder->base.crtc) {
13093                         bool active;
13094
13095                         active = encoder->get_hw_state(encoder, &pipe);
13096                         I915_STATE_WARN(active,
13097                              "encoder detached but still enabled on pipe %c.\n",
13098                              pipe_name(pipe));
13099                 }
13100         }
13101 }
13102
13103 static void
13104 verify_crtc_state(struct intel_crtc *crtc,
13105                   struct intel_crtc_state *old_crtc_state,
13106                   struct intel_crtc_state *new_crtc_state)
13107 {
13108         struct drm_device *dev = crtc->base.dev;
13109         struct drm_i915_private *dev_priv = to_i915(dev);
13110         struct intel_encoder *encoder;
13111         struct intel_crtc_state *pipe_config;
13112         struct drm_atomic_state *state;
13113         bool active;
13114
13115         state = old_crtc_state->base.state;
13116         __drm_atomic_helper_crtc_destroy_state(&old_crtc_state->base);
13117         pipe_config = old_crtc_state;
13118         memset(pipe_config, 0, sizeof(*pipe_config));
13119         pipe_config->base.crtc = &crtc->base;
13120         pipe_config->base.state = state;
13121
13122         DRM_DEBUG_KMS("[CRTC:%d:%s]\n", crtc->base.base.id, crtc->base.name);
13123
13124         active = dev_priv->display.get_pipe_config(crtc, pipe_config);
13125
13126         /* we keep both pipes enabled on 830 */
13127         if (IS_I830(dev_priv))
13128                 active = new_crtc_state->base.active;
13129
13130         I915_STATE_WARN(new_crtc_state->base.active != active,
13131              "crtc active state doesn't match with hw state "
13132              "(expected %i, found %i)\n", new_crtc_state->base.active, active);
13133
13134         I915_STATE_WARN(crtc->active != new_crtc_state->base.active,
13135              "transitional active state does not match atomic hw state "
13136              "(expected %i, found %i)\n", new_crtc_state->base.active, crtc->active);
13137
13138         for_each_encoder_on_crtc(dev, &crtc->base, encoder) {
13139                 enum pipe pipe;
13140
13141                 active = encoder->get_hw_state(encoder, &pipe);
13142                 I915_STATE_WARN(active != new_crtc_state->base.active,
13143                         "[ENCODER:%i] active %i with crtc active %i\n",
13144                         encoder->base.base.id, active, new_crtc_state->base.active);
13145
13146                 I915_STATE_WARN(active && crtc->pipe != pipe,
13147                                 "Encoder connected to wrong pipe %c\n",
13148                                 pipe_name(pipe));
13149
13150                 if (active)
13151                         encoder->get_config(encoder, pipe_config);
13152         }
13153
13154         intel_crtc_compute_pixel_rate(pipe_config);
13155
13156         if (!new_crtc_state->base.active)
13157                 return;
13158
13159         intel_pipe_config_sanity_check(dev_priv, pipe_config);
13160
13161         if (!intel_pipe_config_compare(new_crtc_state,
13162                                        pipe_config, false)) {
13163                 I915_STATE_WARN(1, "pipe state doesn't match!\n");
13164                 intel_dump_pipe_config(pipe_config, NULL, "[hw state]");
13165                 intel_dump_pipe_config(new_crtc_state, NULL, "[sw state]");
13166         }
13167 }
13168
13169 static void
13170 intel_verify_planes(struct intel_atomic_state *state)
13171 {
13172         struct intel_plane *plane;
13173         const struct intel_plane_state *plane_state;
13174         int i;
13175
13176         for_each_new_intel_plane_in_state(state, plane,
13177                                           plane_state, i)
13178                 assert_plane(plane, plane_state->slave ||
13179                              plane_state->base.visible);
13180 }
13181
13182 static void
13183 verify_single_dpll_state(struct drm_i915_private *dev_priv,
13184                          struct intel_shared_dpll *pll,
13185                          struct intel_crtc *crtc,
13186                          struct intel_crtc_state *new_crtc_state)
13187 {
13188         struct intel_dpll_hw_state dpll_hw_state;
13189         unsigned int crtc_mask;
13190         bool active;
13191
13192         memset(&dpll_hw_state, 0, sizeof(dpll_hw_state));
13193
13194         DRM_DEBUG_KMS("%s\n", pll->info->name);
13195
13196         active = pll->info->funcs->get_hw_state(dev_priv, pll, &dpll_hw_state);
13197
13198         if (!(pll->info->flags & INTEL_DPLL_ALWAYS_ON)) {
13199                 I915_STATE_WARN(!pll->on && pll->active_mask,
13200                      "pll in active use but not on in sw tracking\n");
13201                 I915_STATE_WARN(pll->on && !pll->active_mask,
13202                      "pll is on but not used by any active crtc\n");
13203                 I915_STATE_WARN(pll->on != active,
13204                      "pll on state mismatch (expected %i, found %i)\n",
13205                      pll->on, active);
13206         }
13207
13208         if (!crtc) {
13209                 I915_STATE_WARN(pll->active_mask & ~pll->state.crtc_mask,
13210                                 "more active pll users than references: %x vs %x\n",
13211                                 pll->active_mask, pll->state.crtc_mask);
13212
13213                 return;
13214         }
13215
13216         crtc_mask = drm_crtc_mask(&crtc->base);
13217
13218         if (new_crtc_state->base.active)
13219                 I915_STATE_WARN(!(pll->active_mask & crtc_mask),
13220                                 "pll active mismatch (expected pipe %c in active mask 0x%02x)\n",
13221                                 pipe_name(drm_crtc_index(&crtc->base)), pll->active_mask);
13222         else
13223                 I915_STATE_WARN(pll->active_mask & crtc_mask,
13224                                 "pll active mismatch (didn't expect pipe %c in active mask 0x%02x)\n",
13225                                 pipe_name(drm_crtc_index(&crtc->base)), pll->active_mask);
13226
13227         I915_STATE_WARN(!(pll->state.crtc_mask & crtc_mask),
13228                         "pll enabled crtcs mismatch (expected 0x%x in 0x%02x)\n",
13229                         crtc_mask, pll->state.crtc_mask);
13230
13231         I915_STATE_WARN(pll->on && memcmp(&pll->state.hw_state,
13232                                           &dpll_hw_state,
13233                                           sizeof(dpll_hw_state)),
13234                         "pll hw state mismatch\n");
13235 }
13236
13237 static void
13238 verify_shared_dpll_state(struct intel_crtc *crtc,
13239                          struct intel_crtc_state *old_crtc_state,
13240                          struct intel_crtc_state *new_crtc_state)
13241 {
13242         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
13243
13244         if (new_crtc_state->shared_dpll)
13245                 verify_single_dpll_state(dev_priv, new_crtc_state->shared_dpll, crtc, new_crtc_state);
13246
13247         if (old_crtc_state->shared_dpll &&
13248             old_crtc_state->shared_dpll != new_crtc_state->shared_dpll) {
13249                 unsigned int crtc_mask = drm_crtc_mask(&crtc->base);
13250                 struct intel_shared_dpll *pll = old_crtc_state->shared_dpll;
13251
13252                 I915_STATE_WARN(pll->active_mask & crtc_mask,
13253                                 "pll active mismatch (didn't expect pipe %c in active mask)\n",
13254                                 pipe_name(drm_crtc_index(&crtc->base)));
13255                 I915_STATE_WARN(pll->state.crtc_mask & crtc_mask,
13256                                 "pll enabled crtcs mismatch (found %x in enabled mask)\n",
13257                                 pipe_name(drm_crtc_index(&crtc->base)));
13258         }
13259 }
13260
13261 static void
13262 intel_modeset_verify_crtc(struct intel_crtc *crtc,
13263                           struct intel_atomic_state *state,
13264                           struct intel_crtc_state *old_crtc_state,
13265                           struct intel_crtc_state *new_crtc_state)
13266 {
13267         if (!needs_modeset(new_crtc_state) && !new_crtc_state->update_pipe)
13268                 return;
13269
13270         verify_wm_state(crtc, new_crtc_state);
13271         verify_connector_state(state, crtc);
13272         verify_crtc_state(crtc, old_crtc_state, new_crtc_state);
13273         verify_shared_dpll_state(crtc, old_crtc_state, new_crtc_state);
13274 }
13275
13276 static void
13277 verify_disabled_dpll_state(struct drm_i915_private *dev_priv)
13278 {
13279         int i;
13280
13281         for (i = 0; i < dev_priv->num_shared_dpll; i++)
13282                 verify_single_dpll_state(dev_priv, &dev_priv->shared_dplls[i], NULL, NULL);
13283 }
13284
13285 static void
13286 intel_modeset_verify_disabled(struct drm_i915_private *dev_priv,
13287                               struct intel_atomic_state *state)
13288 {
13289         verify_encoder_state(dev_priv, state);
13290         verify_connector_state(state, NULL);
13291         verify_disabled_dpll_state(dev_priv);
13292 }
13293
13294 static void update_scanline_offset(const struct intel_crtc_state *crtc_state)
13295 {
13296         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
13297         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
13298
13299         /*
13300          * The scanline counter increments at the leading edge of hsync.
13301          *
13302          * On most platforms it starts counting from vtotal-1 on the
13303          * first active line. That means the scanline counter value is
13304          * always one less than what we would expect. Ie. just after
13305          * start of vblank, which also occurs at start of hsync (on the
13306          * last active line), the scanline counter will read vblank_start-1.
13307          *
13308          * On gen2 the scanline counter starts counting from 1 instead
13309          * of vtotal-1, so we have to subtract one (or rather add vtotal-1
13310          * to keep the value positive), instead of adding one.
13311          *
13312          * On HSW+ the behaviour of the scanline counter depends on the output
13313          * type. For DP ports it behaves like most other platforms, but on HDMI
13314          * there's an extra 1 line difference. So we need to add two instead of
13315          * one to the value.
13316          *
13317          * On VLV/CHV DSI the scanline counter would appear to increment
13318          * approx. 1/3 of a scanline before start of vblank. Unfortunately
13319          * that means we can't tell whether we're in vblank or not while
13320          * we're on that particular line. We must still set scanline_offset
13321          * to 1 so that the vblank timestamps come out correct when we query
13322          * the scanline counter from within the vblank interrupt handler.
13323          * However if queried just before the start of vblank we'll get an
13324          * answer that's slightly in the future.
13325          */
13326         if (IS_GEN(dev_priv, 2)) {
13327                 const struct drm_display_mode *adjusted_mode = &crtc_state->base.adjusted_mode;
13328                 int vtotal;
13329
13330                 vtotal = adjusted_mode->crtc_vtotal;
13331                 if (adjusted_mode->flags & DRM_MODE_FLAG_INTERLACE)
13332                         vtotal /= 2;
13333
13334                 crtc->scanline_offset = vtotal - 1;
13335         } else if (HAS_DDI(dev_priv) &&
13336                    intel_crtc_has_type(crtc_state, INTEL_OUTPUT_HDMI)) {
13337                 crtc->scanline_offset = 2;
13338         } else
13339                 crtc->scanline_offset = 1;
13340 }
13341
13342 static void intel_modeset_clear_plls(struct intel_atomic_state *state)
13343 {
13344         struct drm_i915_private *dev_priv = to_i915(state->base.dev);
13345         struct intel_crtc_state *new_crtc_state;
13346         struct intel_crtc *crtc;
13347         int i;
13348
13349         if (!dev_priv->display.crtc_compute_clock)
13350                 return;
13351
13352         for_each_new_intel_crtc_in_state(state, crtc, new_crtc_state, i) {
13353                 if (!needs_modeset(new_crtc_state))
13354                         continue;
13355
13356                 intel_release_shared_dplls(state, crtc);
13357         }
13358 }
13359
13360 /*
13361  * This implements the workaround described in the "notes" section of the mode
13362  * set sequence documentation. When going from no pipes or single pipe to
13363  * multiple pipes, and planes are enabled after the pipe, we need to wait at
13364  * least 2 vblanks on the first pipe before enabling planes on the second pipe.
13365  */
13366 static int haswell_mode_set_planes_workaround(struct intel_atomic_state *state)
13367 {
13368         struct intel_crtc_state *crtc_state;
13369         struct intel_crtc *crtc;
13370         struct intel_crtc_state *first_crtc_state = NULL;
13371         struct intel_crtc_state *other_crtc_state = NULL;
13372         enum pipe first_pipe = INVALID_PIPE, enabled_pipe = INVALID_PIPE;
13373         int i;
13374
13375         /* look at all crtc's that are going to be enabled in during modeset */
13376         for_each_new_intel_crtc_in_state(state, crtc, crtc_state, i) {
13377                 if (!crtc_state->base.active ||
13378                     !needs_modeset(crtc_state))
13379                         continue;
13380
13381                 if (first_crtc_state) {
13382                         other_crtc_state = crtc_state;
13383                         break;
13384                 } else {
13385                         first_crtc_state = crtc_state;
13386                         first_pipe = crtc->pipe;
13387                 }
13388         }
13389
13390         /* No workaround needed? */
13391         if (!first_crtc_state)
13392                 return 0;
13393
13394         /* w/a possibly needed, check how many crtc's are already enabled. */
13395         for_each_intel_crtc(state->base.dev, crtc) {
13396                 crtc_state = intel_atomic_get_crtc_state(&state->base, crtc);
13397                 if (IS_ERR(crtc_state))
13398                         return PTR_ERR(crtc_state);
13399
13400                 crtc_state->hsw_workaround_pipe = INVALID_PIPE;
13401
13402                 if (!crtc_state->base.active ||
13403                     needs_modeset(crtc_state))
13404                         continue;
13405
13406                 /* 2 or more enabled crtcs means no need for w/a */
13407                 if (enabled_pipe != INVALID_PIPE)
13408                         return 0;
13409
13410                 enabled_pipe = crtc->pipe;
13411         }
13412
13413         if (enabled_pipe != INVALID_PIPE)
13414                 first_crtc_state->hsw_workaround_pipe = enabled_pipe;
13415         else if (other_crtc_state)
13416                 other_crtc_state->hsw_workaround_pipe = first_pipe;
13417
13418         return 0;
13419 }
13420
13421 static int intel_lock_all_pipes(struct intel_atomic_state *state)
13422 {
13423         struct drm_i915_private *dev_priv = to_i915(state->base.dev);
13424         struct intel_crtc *crtc;
13425
13426         /* Add all pipes to the state */
13427         for_each_intel_crtc(&dev_priv->drm, crtc) {
13428                 struct intel_crtc_state *crtc_state;
13429
13430                 crtc_state = intel_atomic_get_crtc_state(&state->base, crtc);
13431                 if (IS_ERR(crtc_state))
13432                         return PTR_ERR(crtc_state);
13433         }
13434
13435         return 0;
13436 }
13437
13438 static int intel_modeset_all_pipes(struct intel_atomic_state *state)
13439 {
13440         struct drm_i915_private *dev_priv = to_i915(state->base.dev);
13441         struct intel_crtc *crtc;
13442
13443         /*
13444          * Add all pipes to the state, and force
13445          * a modeset on all the active ones.
13446          */
13447         for_each_intel_crtc(&dev_priv->drm, crtc) {
13448                 struct intel_crtc_state *crtc_state;
13449                 int ret;
13450
13451                 crtc_state = intel_atomic_get_crtc_state(&state->base, crtc);
13452                 if (IS_ERR(crtc_state))
13453                         return PTR_ERR(crtc_state);
13454
13455                 if (!crtc_state->base.active || needs_modeset(crtc_state))
13456                         continue;
13457
13458                 crtc_state->base.mode_changed = true;
13459
13460                 ret = drm_atomic_add_affected_connectors(&state->base,
13461                                                          &crtc->base);
13462                 if (ret)
13463                         return ret;
13464
13465                 ret = drm_atomic_add_affected_planes(&state->base,
13466                                                      &crtc->base);
13467                 if (ret)
13468                         return ret;
13469         }
13470
13471         return 0;
13472 }
13473
13474 static int intel_modeset_checks(struct intel_atomic_state *state)
13475 {
13476         struct drm_i915_private *dev_priv = to_i915(state->base.dev);
13477         struct intel_crtc_state *old_crtc_state, *new_crtc_state;
13478         struct intel_crtc *crtc;
13479         int ret = 0, i;
13480
13481         if (!check_digital_port_conflicts(state)) {
13482                 DRM_DEBUG_KMS("rejecting conflicting digital port configuration\n");
13483                 return -EINVAL;
13484         }
13485
13486         /* keep the current setting */
13487         if (!state->cdclk.force_min_cdclk_changed)
13488                 state->cdclk.force_min_cdclk = dev_priv->cdclk.force_min_cdclk;
13489
13490         state->modeset = true;
13491         state->active_pipes = dev_priv->active_pipes;
13492         state->cdclk.logical = dev_priv->cdclk.logical;
13493         state->cdclk.actual = dev_priv->cdclk.actual;
13494         state->cdclk.pipe = INVALID_PIPE;
13495
13496         for_each_oldnew_intel_crtc_in_state(state, crtc, old_crtc_state,
13497                                             new_crtc_state, i) {
13498                 if (new_crtc_state->base.active)
13499                         state->active_pipes |= BIT(crtc->pipe);
13500                 else
13501                         state->active_pipes &= ~BIT(crtc->pipe);
13502
13503                 if (old_crtc_state->base.active != new_crtc_state->base.active)
13504                         state->active_pipe_changes |= BIT(crtc->pipe);
13505         }
13506
13507         /*
13508          * See if the config requires any additional preparation, e.g.
13509          * to adjust global state with pipes off.  We need to do this
13510          * here so we can get the modeset_pipe updated config for the new
13511          * mode set on this crtc.  For other crtcs we need to use the
13512          * adjusted_mode bits in the crtc directly.
13513          */
13514         if (dev_priv->display.modeset_calc_cdclk) {
13515                 enum pipe pipe;
13516
13517                 ret = dev_priv->display.modeset_calc_cdclk(state);
13518                 if (ret < 0)
13519                         return ret;
13520
13521                 /*
13522                  * Writes to dev_priv->cdclk.logical must protected by
13523                  * holding all the crtc locks, even if we don't end up
13524                  * touching the hardware
13525                  */
13526                 if (intel_cdclk_changed(&dev_priv->cdclk.logical,
13527                                         &state->cdclk.logical)) {
13528                         ret = intel_lock_all_pipes(state);
13529                         if (ret < 0)
13530                                 return ret;
13531                 }
13532
13533                 if (is_power_of_2(state->active_pipes)) {
13534                         struct intel_crtc *crtc;
13535                         struct intel_crtc_state *crtc_state;
13536
13537                         pipe = ilog2(state->active_pipes);
13538                         crtc = intel_get_crtc_for_pipe(dev_priv, pipe);
13539                         crtc_state = intel_atomic_get_new_crtc_state(state, crtc);
13540                         if (crtc_state && needs_modeset(crtc_state))
13541                                 pipe = INVALID_PIPE;
13542                 } else {
13543                         pipe = INVALID_PIPE;
13544                 }
13545
13546                 /* All pipes must be switched off while we change the cdclk. */
13547                 if (pipe != INVALID_PIPE &&
13548                     intel_cdclk_needs_cd2x_update(dev_priv,
13549                                                   &dev_priv->cdclk.actual,
13550                                                   &state->cdclk.actual)) {
13551                         ret = intel_lock_all_pipes(state);
13552                         if (ret < 0)
13553                                 return ret;
13554
13555                         state->cdclk.pipe = pipe;
13556                 } else if (intel_cdclk_needs_modeset(&dev_priv->cdclk.actual,
13557                                                      &state->cdclk.actual)) {
13558                         ret = intel_modeset_all_pipes(state);
13559                         if (ret < 0)
13560                                 return ret;
13561
13562                         state->cdclk.pipe = INVALID_PIPE;
13563                 }
13564
13565                 DRM_DEBUG_KMS("New cdclk calculated to be logical %u kHz, actual %u kHz\n",
13566                               state->cdclk.logical.cdclk,
13567                               state->cdclk.actual.cdclk);
13568                 DRM_DEBUG_KMS("New voltage level calculated to be logical %u, actual %u\n",
13569                               state->cdclk.logical.voltage_level,
13570                               state->cdclk.actual.voltage_level);
13571         }
13572
13573         intel_modeset_clear_plls(state);
13574
13575         if (IS_HASWELL(dev_priv))
13576                 return haswell_mode_set_planes_workaround(state);
13577
13578         return 0;
13579 }
13580
13581 /*
13582  * Handle calculation of various watermark data at the end of the atomic check
13583  * phase.  The code here should be run after the per-crtc and per-plane 'check'
13584  * handlers to ensure that all derived state has been updated.
13585  */
13586 static int calc_watermark_data(struct intel_atomic_state *state)
13587 {
13588         struct drm_device *dev = state->base.dev;
13589         struct drm_i915_private *dev_priv = to_i915(dev);
13590
13591         /* Is there platform-specific watermark information to calculate? */
13592         if (dev_priv->display.compute_global_watermarks)
13593                 return dev_priv->display.compute_global_watermarks(state);
13594
13595         return 0;
13596 }
13597
13598 static void intel_crtc_check_fastset(const struct intel_crtc_state *old_crtc_state,
13599                                      struct intel_crtc_state *new_crtc_state)
13600 {
13601         if (!intel_pipe_config_compare(old_crtc_state, new_crtc_state, true))
13602                 return;
13603
13604         new_crtc_state->base.mode_changed = false;
13605         new_crtc_state->update_pipe = true;
13606
13607         /*
13608          * If we're not doing the full modeset we want to
13609          * keep the current M/N values as they may be
13610          * sufficiently different to the computed values
13611          * to cause problems.
13612          *
13613          * FIXME: should really copy more fuzzy state here
13614          */
13615         new_crtc_state->fdi_m_n = old_crtc_state->fdi_m_n;
13616         new_crtc_state->dp_m_n = old_crtc_state->dp_m_n;
13617         new_crtc_state->dp_m2_n2 = old_crtc_state->dp_m2_n2;
13618         new_crtc_state->has_drrs = old_crtc_state->has_drrs;
13619 }
13620
13621 /**
13622  * intel_atomic_check - validate state object
13623  * @dev: drm device
13624  * @_state: state to validate
13625  */
13626 static int intel_atomic_check(struct drm_device *dev,
13627                               struct drm_atomic_state *_state)
13628 {
13629         struct drm_i915_private *dev_priv = to_i915(dev);
13630         struct intel_atomic_state *state = to_intel_atomic_state(_state);
13631         struct intel_crtc_state *old_crtc_state, *new_crtc_state;
13632         struct intel_crtc *crtc;
13633         int ret, i;
13634         bool any_ms = state->cdclk.force_min_cdclk_changed;
13635
13636         /* Catch I915_MODE_FLAG_INHERITED */
13637         for_each_oldnew_intel_crtc_in_state(state, crtc, old_crtc_state,
13638                                             new_crtc_state, i) {
13639                 if (new_crtc_state->base.mode.private_flags !=
13640                     old_crtc_state->base.mode.private_flags)
13641                         new_crtc_state->base.mode_changed = true;
13642         }
13643
13644         ret = drm_atomic_helper_check_modeset(dev, &state->base);
13645         if (ret)
13646                 goto fail;
13647
13648         for_each_oldnew_intel_crtc_in_state(state, crtc, old_crtc_state,
13649                                             new_crtc_state, i) {
13650                 if (!needs_modeset(new_crtc_state))
13651                         continue;
13652
13653                 if (!new_crtc_state->base.enable) {
13654                         any_ms = true;
13655                         continue;
13656                 }
13657
13658                 ret = intel_modeset_pipe_config(new_crtc_state);
13659                 if (ret)
13660                         goto fail;
13661
13662                 intel_crtc_check_fastset(old_crtc_state, new_crtc_state);
13663
13664                 if (needs_modeset(new_crtc_state))
13665                         any_ms = true;
13666         }
13667
13668         ret = drm_dp_mst_atomic_check(&state->base);
13669         if (ret)
13670                 goto fail;
13671
13672         if (any_ms) {
13673                 ret = intel_modeset_checks(state);
13674                 if (ret)
13675                         goto fail;
13676         } else {
13677                 state->cdclk.logical = dev_priv->cdclk.logical;
13678         }
13679
13680         ret = icl_add_linked_planes(state);
13681         if (ret)
13682                 goto fail;
13683
13684         ret = drm_atomic_helper_check_planes(dev, &state->base);
13685         if (ret)
13686                 goto fail;
13687
13688         intel_fbc_choose_crtc(dev_priv, state);
13689         ret = calc_watermark_data(state);
13690         if (ret)
13691                 goto fail;
13692
13693         ret = intel_bw_atomic_check(state);
13694         if (ret)
13695                 goto fail;
13696
13697         for_each_oldnew_intel_crtc_in_state(state, crtc, old_crtc_state,
13698                                             new_crtc_state, i) {
13699                 if (!needs_modeset(new_crtc_state) &&
13700                     !new_crtc_state->update_pipe)
13701                         continue;
13702
13703                 intel_dump_pipe_config(new_crtc_state, state,
13704                                        needs_modeset(new_crtc_state) ?
13705                                        "[modeset]" : "[fastset]");
13706         }
13707
13708         return 0;
13709
13710  fail:
13711         if (ret == -EDEADLK)
13712                 return ret;
13713
13714         /*
13715          * FIXME would probably be nice to know which crtc specifically
13716          * caused the failure, in cases where we can pinpoint it.
13717          */
13718         for_each_oldnew_intel_crtc_in_state(state, crtc, old_crtc_state,
13719                                             new_crtc_state, i)
13720                 intel_dump_pipe_config(new_crtc_state, state, "[failed]");
13721
13722         return ret;
13723 }
13724
13725 static int intel_atomic_prepare_commit(struct intel_atomic_state *state)
13726 {
13727         return drm_atomic_helper_prepare_planes(state->base.dev,
13728                                                 &state->base);
13729 }
13730
13731 u32 intel_crtc_get_vblank_counter(struct intel_crtc *crtc)
13732 {
13733         struct drm_device *dev = crtc->base.dev;
13734         struct drm_vblank_crtc *vblank = &dev->vblank[drm_crtc_index(&crtc->base)];
13735
13736         if (!vblank->max_vblank_count)
13737                 return (u32)drm_crtc_accurate_vblank_count(&crtc->base);
13738
13739         return crtc->base.funcs->get_vblank_counter(&crtc->base);
13740 }
13741
13742 static void intel_update_crtc(struct intel_crtc *crtc,
13743                               struct intel_atomic_state *state,
13744                               struct intel_crtc_state *old_crtc_state,
13745                               struct intel_crtc_state *new_crtc_state)
13746 {
13747         struct drm_device *dev = state->base.dev;
13748         struct drm_i915_private *dev_priv = to_i915(dev);
13749         bool modeset = needs_modeset(new_crtc_state);
13750         struct intel_plane_state *new_plane_state =
13751                 intel_atomic_get_new_plane_state(state,
13752                                                  to_intel_plane(crtc->base.primary));
13753
13754         if (modeset) {
13755                 update_scanline_offset(new_crtc_state);
13756                 dev_priv->display.crtc_enable(new_crtc_state, state);
13757
13758                 /* vblanks work again, re-enable pipe CRC. */
13759                 intel_crtc_enable_pipe_crc(crtc);
13760         } else {
13761                 intel_pre_plane_update(old_crtc_state, new_crtc_state);
13762
13763                 if (new_crtc_state->update_pipe)
13764                         intel_encoders_update_pipe(crtc, new_crtc_state, state);
13765         }
13766
13767         if (new_crtc_state->update_pipe && !new_crtc_state->enable_fbc)
13768                 intel_fbc_disable(crtc);
13769         else if (new_plane_state)
13770                 intel_fbc_enable(crtc, new_crtc_state, new_plane_state);
13771
13772         intel_begin_crtc_commit(state, crtc);
13773
13774         if (INTEL_GEN(dev_priv) >= 9)
13775                 skl_update_planes_on_crtc(state, crtc);
13776         else
13777                 i9xx_update_planes_on_crtc(state, crtc);
13778
13779         intel_finish_crtc_commit(state, crtc);
13780 }
13781
13782 static void intel_old_crtc_state_disables(struct intel_atomic_state *state,
13783                                           struct intel_crtc_state *old_crtc_state,
13784                                           struct intel_crtc_state *new_crtc_state,
13785                                           struct intel_crtc *crtc)
13786 {
13787         struct drm_i915_private *dev_priv = to_i915(state->base.dev);
13788
13789         intel_crtc_disable_planes(state, crtc);
13790
13791         /*
13792          * We need to disable pipe CRC before disabling the pipe,
13793          * or we race against vblank off.
13794          */
13795         intel_crtc_disable_pipe_crc(crtc);
13796
13797         dev_priv->display.crtc_disable(old_crtc_state, state);
13798         crtc->active = false;
13799         intel_fbc_disable(crtc);
13800         intel_disable_shared_dpll(old_crtc_state);
13801
13802         /*
13803          * Underruns don't always raise interrupts,
13804          * so check manually.
13805          */
13806         intel_check_cpu_fifo_underruns(dev_priv);
13807         intel_check_pch_fifo_underruns(dev_priv);
13808
13809         /* FIXME unify this for all platforms */
13810         if (!new_crtc_state->base.active &&
13811             !HAS_GMCH(dev_priv) &&
13812             dev_priv->display.initial_watermarks)
13813                 dev_priv->display.initial_watermarks(state,
13814                                                      new_crtc_state);
13815 }
13816
13817 static void intel_commit_modeset_disables(struct intel_atomic_state *state)
13818 {
13819         struct intel_crtc_state *new_crtc_state, *old_crtc_state;
13820         struct intel_crtc *crtc;
13821         int i;
13822
13823         /*
13824          * Disable CRTC/pipes in reverse order because some features(MST in
13825          * TGL+) requires master and slave relationship between pipes, so it
13826          * should always pick the lowest pipe as master as it will be enabled
13827          * first and disable in the reverse order so the master will be the
13828          * last one to be disabled.
13829          */
13830         for_each_oldnew_intel_crtc_in_state_reverse(state, crtc, old_crtc_state,
13831                                                     new_crtc_state, i) {
13832                 if (!needs_modeset(new_crtc_state))
13833                         continue;
13834
13835                 intel_pre_plane_update(old_crtc_state, new_crtc_state);
13836
13837                 if (old_crtc_state->base.active)
13838                         intel_old_crtc_state_disables(state,
13839                                                       old_crtc_state,
13840                                                       new_crtc_state,
13841                                                       crtc);
13842         }
13843 }
13844
13845 static void intel_commit_modeset_enables(struct intel_atomic_state *state)
13846 {
13847         struct intel_crtc *crtc;
13848         struct intel_crtc_state *old_crtc_state, *new_crtc_state;
13849         int i;
13850
13851         for_each_oldnew_intel_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
13852                 if (!new_crtc_state->base.active)
13853                         continue;
13854
13855                 intel_update_crtc(crtc, state, old_crtc_state,
13856                                   new_crtc_state);
13857         }
13858 }
13859
13860 static void skl_commit_modeset_enables(struct intel_atomic_state *state)
13861 {
13862         struct drm_i915_private *dev_priv = to_i915(state->base.dev);
13863         struct intel_crtc *crtc;
13864         struct intel_crtc_state *old_crtc_state, *new_crtc_state;
13865         unsigned int updated = 0;
13866         bool progress;
13867         enum pipe pipe;
13868         int i;
13869         u8 hw_enabled_slices = dev_priv->wm.skl_hw.ddb.enabled_slices;
13870         u8 required_slices = state->wm_results.ddb.enabled_slices;
13871         struct skl_ddb_entry entries[I915_MAX_PIPES] = {};
13872
13873         for_each_oldnew_intel_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i)
13874                 /* ignore allocations for crtc's that have been turned off. */
13875                 if (new_crtc_state->base.active)
13876                         entries[i] = old_crtc_state->wm.skl.ddb;
13877
13878         /* If 2nd DBuf slice required, enable it here */
13879         if (INTEL_GEN(dev_priv) >= 11 && required_slices > hw_enabled_slices)
13880                 icl_dbuf_slices_update(dev_priv, required_slices);
13881
13882         /*
13883          * Whenever the number of active pipes changes, we need to make sure we
13884          * update the pipes in the right order so that their ddb allocations
13885          * never overlap with eachother inbetween CRTC updates. Otherwise we'll
13886          * cause pipe underruns and other bad stuff.
13887          */
13888         do {
13889                 progress = false;
13890
13891                 for_each_oldnew_intel_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
13892                         bool vbl_wait = false;
13893                         unsigned int cmask = drm_crtc_mask(&crtc->base);
13894
13895                         pipe = crtc->pipe;
13896
13897                         if (updated & cmask || !new_crtc_state->base.active)
13898                                 continue;
13899
13900                         if (skl_ddb_allocation_overlaps(&new_crtc_state->wm.skl.ddb,
13901                                                         entries,
13902                                                         INTEL_INFO(dev_priv)->num_pipes, i))
13903                                 continue;
13904
13905                         updated |= cmask;
13906                         entries[i] = new_crtc_state->wm.skl.ddb;
13907
13908                         /*
13909                          * If this is an already active pipe, it's DDB changed,
13910                          * and this isn't the last pipe that needs updating
13911                          * then we need to wait for a vblank to pass for the
13912                          * new ddb allocation to take effect.
13913                          */
13914                         if (!skl_ddb_entry_equal(&new_crtc_state->wm.skl.ddb,
13915                                                  &old_crtc_state->wm.skl.ddb) &&
13916                             !new_crtc_state->base.active_changed &&
13917                             state->wm_results.dirty_pipes != updated)
13918                                 vbl_wait = true;
13919
13920                         intel_update_crtc(crtc, state, old_crtc_state,
13921                                           new_crtc_state);
13922
13923                         if (vbl_wait)
13924                                 intel_wait_for_vblank(dev_priv, pipe);
13925
13926                         progress = true;
13927                 }
13928         } while (progress);
13929
13930         /* If 2nd DBuf slice is no more required disable it */
13931         if (INTEL_GEN(dev_priv) >= 11 && required_slices < hw_enabled_slices)
13932                 icl_dbuf_slices_update(dev_priv, required_slices);
13933 }
13934
13935 static void intel_atomic_helper_free_state(struct drm_i915_private *dev_priv)
13936 {
13937         struct intel_atomic_state *state, *next;
13938         struct llist_node *freed;
13939
13940         freed = llist_del_all(&dev_priv->atomic_helper.free_list);
13941         llist_for_each_entry_safe(state, next, freed, freed)
13942                 drm_atomic_state_put(&state->base);
13943 }
13944
13945 static void intel_atomic_helper_free_state_worker(struct work_struct *work)
13946 {
13947         struct drm_i915_private *dev_priv =
13948                 container_of(work, typeof(*dev_priv), atomic_helper.free_work);
13949
13950         intel_atomic_helper_free_state(dev_priv);
13951 }
13952
13953 static void intel_atomic_commit_fence_wait(struct intel_atomic_state *intel_state)
13954 {
13955         struct wait_queue_entry wait_fence, wait_reset;
13956         struct drm_i915_private *dev_priv = to_i915(intel_state->base.dev);
13957
13958         init_wait_entry(&wait_fence, 0);
13959         init_wait_entry(&wait_reset, 0);
13960         for (;;) {
13961                 prepare_to_wait(&intel_state->commit_ready.wait,
13962                                 &wait_fence, TASK_UNINTERRUPTIBLE);
13963                 prepare_to_wait(bit_waitqueue(&dev_priv->gt.reset.flags,
13964                                               I915_RESET_MODESET),
13965                                 &wait_reset, TASK_UNINTERRUPTIBLE);
13966
13967
13968                 if (i915_sw_fence_done(&intel_state->commit_ready) ||
13969                     test_bit(I915_RESET_MODESET, &dev_priv->gt.reset.flags))
13970                         break;
13971
13972                 schedule();
13973         }
13974         finish_wait(&intel_state->commit_ready.wait, &wait_fence);
13975         finish_wait(bit_waitqueue(&dev_priv->gt.reset.flags,
13976                                   I915_RESET_MODESET),
13977                     &wait_reset);
13978 }
13979
13980 static void intel_atomic_cleanup_work(struct work_struct *work)
13981 {
13982         struct drm_atomic_state *state =
13983                 container_of(work, struct drm_atomic_state, commit_work);
13984         struct drm_i915_private *i915 = to_i915(state->dev);
13985
13986         drm_atomic_helper_cleanup_planes(&i915->drm, state);
13987         drm_atomic_helper_commit_cleanup_done(state);
13988         drm_atomic_state_put(state);
13989
13990         intel_atomic_helper_free_state(i915);
13991 }
13992
13993 static void intel_atomic_commit_tail(struct intel_atomic_state *state)
13994 {
13995         struct drm_device *dev = state->base.dev;
13996         struct drm_i915_private *dev_priv = to_i915(dev);
13997         struct intel_crtc_state *new_crtc_state, *old_crtc_state;
13998         struct intel_crtc *crtc;
13999         u64 put_domains[I915_MAX_PIPES] = {};
14000         intel_wakeref_t wakeref = 0;
14001         int i;
14002
14003         intel_atomic_commit_fence_wait(state);
14004
14005         drm_atomic_helper_wait_for_dependencies(&state->base);
14006
14007         if (state->modeset)
14008                 wakeref = intel_display_power_get(dev_priv, POWER_DOMAIN_MODESET);
14009
14010         for_each_oldnew_intel_crtc_in_state(state, crtc, old_crtc_state,
14011                                             new_crtc_state, i) {
14012                 if (needs_modeset(new_crtc_state) ||
14013                     new_crtc_state->update_pipe) {
14014
14015                         put_domains[crtc->pipe] =
14016                                 modeset_get_crtc_power_domains(new_crtc_state);
14017                 }
14018         }
14019
14020         intel_commit_modeset_disables(state);
14021
14022         /* FIXME: Eventually get rid of our crtc->config pointer */
14023         for_each_new_intel_crtc_in_state(state, crtc, new_crtc_state, i)
14024                 crtc->config = new_crtc_state;
14025
14026         if (state->modeset) {
14027                 drm_atomic_helper_update_legacy_modeset_state(dev, &state->base);
14028
14029                 intel_set_cdclk_pre_plane_update(dev_priv,
14030                                                  &state->cdclk.actual,
14031                                                  &dev_priv->cdclk.actual,
14032                                                  state->cdclk.pipe);
14033
14034                 /*
14035                  * SKL workaround: bspec recommends we disable the SAGV when we
14036                  * have more then one pipe enabled
14037                  */
14038                 if (!intel_can_enable_sagv(state))
14039                         intel_disable_sagv(dev_priv);
14040
14041                 intel_modeset_verify_disabled(dev_priv, state);
14042         }
14043
14044         /* Complete the events for pipes that have now been disabled */
14045         for_each_new_intel_crtc_in_state(state, crtc, new_crtc_state, i) {
14046                 bool modeset = needs_modeset(new_crtc_state);
14047
14048                 /* Complete events for now disable pipes here. */
14049                 if (modeset && !new_crtc_state->base.active && new_crtc_state->base.event) {
14050                         spin_lock_irq(&dev->event_lock);
14051                         drm_crtc_send_vblank_event(&crtc->base, new_crtc_state->base.event);
14052                         spin_unlock_irq(&dev->event_lock);
14053
14054                         new_crtc_state->base.event = NULL;
14055                 }
14056         }
14057
14058         if (state->modeset)
14059                 intel_encoders_update_prepare(state);
14060
14061         /* Now enable the clocks, plane, pipe, and connectors that we set up. */
14062         dev_priv->display.commit_modeset_enables(state);
14063
14064         if (state->modeset) {
14065                 intel_encoders_update_complete(state);
14066
14067                 intel_set_cdclk_post_plane_update(dev_priv,
14068                                                   &state->cdclk.actual,
14069                                                   &dev_priv->cdclk.actual,
14070                                                   state->cdclk.pipe);
14071         }
14072
14073         /* FIXME: We should call drm_atomic_helper_commit_hw_done() here
14074          * already, but still need the state for the delayed optimization. To
14075          * fix this:
14076          * - wrap the optimization/post_plane_update stuff into a per-crtc work.
14077          * - schedule that vblank worker _before_ calling hw_done
14078          * - at the start of commit_tail, cancel it _synchrously
14079          * - switch over to the vblank wait helper in the core after that since
14080          *   we don't need out special handling any more.
14081          */
14082         drm_atomic_helper_wait_for_flip_done(dev, &state->base);
14083
14084         for_each_new_intel_crtc_in_state(state, crtc, new_crtc_state, i) {
14085                 if (new_crtc_state->base.active &&
14086                     !needs_modeset(new_crtc_state) &&
14087                     (new_crtc_state->base.color_mgmt_changed ||
14088                      new_crtc_state->update_pipe))
14089                         intel_color_load_luts(new_crtc_state);
14090         }
14091
14092         /*
14093          * Now that the vblank has passed, we can go ahead and program the
14094          * optimal watermarks on platforms that need two-step watermark
14095          * programming.
14096          *
14097          * TODO: Move this (and other cleanup) to an async worker eventually.
14098          */
14099         for_each_new_intel_crtc_in_state(state, crtc, new_crtc_state, i) {
14100                 if (dev_priv->display.optimize_watermarks)
14101                         dev_priv->display.optimize_watermarks(state,
14102                                                               new_crtc_state);
14103         }
14104
14105         for_each_oldnew_intel_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
14106                 intel_post_plane_update(old_crtc_state);
14107
14108                 if (put_domains[i])
14109                         modeset_put_power_domains(dev_priv, put_domains[i]);
14110
14111                 intel_modeset_verify_crtc(crtc, state, old_crtc_state, new_crtc_state);
14112         }
14113
14114         if (state->modeset)
14115                 intel_verify_planes(state);
14116
14117         if (state->modeset && intel_can_enable_sagv(state))
14118                 intel_enable_sagv(dev_priv);
14119
14120         drm_atomic_helper_commit_hw_done(&state->base);
14121
14122         if (state->modeset) {
14123                 /* As one of the primary mmio accessors, KMS has a high
14124                  * likelihood of triggering bugs in unclaimed access. After we
14125                  * finish modesetting, see if an error has been flagged, and if
14126                  * so enable debugging for the next modeset - and hope we catch
14127                  * the culprit.
14128                  */
14129                 intel_uncore_arm_unclaimed_mmio_detection(&dev_priv->uncore);
14130                 intel_display_power_put(dev_priv, POWER_DOMAIN_MODESET, wakeref);
14131         }
14132         intel_runtime_pm_put(&dev_priv->runtime_pm, state->wakeref);
14133
14134         /*
14135          * Defer the cleanup of the old state to a separate worker to not
14136          * impede the current task (userspace for blocking modesets) that
14137          * are executed inline. For out-of-line asynchronous modesets/flips,
14138          * deferring to a new worker seems overkill, but we would place a
14139          * schedule point (cond_resched()) here anyway to keep latencies
14140          * down.
14141          */
14142         INIT_WORK(&state->base.commit_work, intel_atomic_cleanup_work);
14143         queue_work(system_highpri_wq, &state->base.commit_work);
14144 }
14145
14146 static void intel_atomic_commit_work(struct work_struct *work)
14147 {
14148         struct intel_atomic_state *state =
14149                 container_of(work, struct intel_atomic_state, base.commit_work);
14150
14151         intel_atomic_commit_tail(state);
14152 }
14153
14154 static int __i915_sw_fence_call
14155 intel_atomic_commit_ready(struct i915_sw_fence *fence,
14156                           enum i915_sw_fence_notify notify)
14157 {
14158         struct intel_atomic_state *state =
14159                 container_of(fence, struct intel_atomic_state, commit_ready);
14160
14161         switch (notify) {
14162         case FENCE_COMPLETE:
14163                 /* we do blocking waits in the worker, nothing to do here */
14164                 break;
14165         case FENCE_FREE:
14166                 {
14167                         struct intel_atomic_helper *helper =
14168                                 &to_i915(state->base.dev)->atomic_helper;
14169
14170                         if (llist_add(&state->freed, &helper->free_list))
14171                                 schedule_work(&helper->free_work);
14172                         break;
14173                 }
14174         }
14175
14176         return NOTIFY_DONE;
14177 }
14178
14179 static void intel_atomic_track_fbs(struct intel_atomic_state *state)
14180 {
14181         struct intel_plane_state *old_plane_state, *new_plane_state;
14182         struct intel_plane *plane;
14183         int i;
14184
14185         for_each_oldnew_intel_plane_in_state(state, plane, old_plane_state,
14186                                              new_plane_state, i)
14187                 intel_frontbuffer_track(to_intel_frontbuffer(old_plane_state->base.fb),
14188                                         to_intel_frontbuffer(new_plane_state->base.fb),
14189                                         plane->frontbuffer_bit);
14190 }
14191
14192 static int intel_atomic_commit(struct drm_device *dev,
14193                                struct drm_atomic_state *_state,
14194                                bool nonblock)
14195 {
14196         struct intel_atomic_state *state = to_intel_atomic_state(_state);
14197         struct drm_i915_private *dev_priv = to_i915(dev);
14198         int ret = 0;
14199
14200         state->wakeref = intel_runtime_pm_get(&dev_priv->runtime_pm);
14201
14202         drm_atomic_state_get(&state->base);
14203         i915_sw_fence_init(&state->commit_ready,
14204                            intel_atomic_commit_ready);
14205
14206         /*
14207          * The intel_legacy_cursor_update() fast path takes care
14208          * of avoiding the vblank waits for simple cursor
14209          * movement and flips. For cursor on/off and size changes,
14210          * we want to perform the vblank waits so that watermark
14211          * updates happen during the correct frames. Gen9+ have
14212          * double buffered watermarks and so shouldn't need this.
14213          *
14214          * Unset state->legacy_cursor_update before the call to
14215          * drm_atomic_helper_setup_commit() because otherwise
14216          * drm_atomic_helper_wait_for_flip_done() is a noop and
14217          * we get FIFO underruns because we didn't wait
14218          * for vblank.
14219          *
14220          * FIXME doing watermarks and fb cleanup from a vblank worker
14221          * (assuming we had any) would solve these problems.
14222          */
14223         if (INTEL_GEN(dev_priv) < 9 && state->base.legacy_cursor_update) {
14224                 struct intel_crtc_state *new_crtc_state;
14225                 struct intel_crtc *crtc;
14226                 int i;
14227
14228                 for_each_new_intel_crtc_in_state(state, crtc, new_crtc_state, i)
14229                         if (new_crtc_state->wm.need_postvbl_update ||
14230                             new_crtc_state->update_wm_post)
14231                                 state->base.legacy_cursor_update = false;
14232         }
14233
14234         ret = intel_atomic_prepare_commit(state);
14235         if (ret) {
14236                 DRM_DEBUG_ATOMIC("Preparing state failed with %i\n", ret);
14237                 i915_sw_fence_commit(&state->commit_ready);
14238                 intel_runtime_pm_put(&dev_priv->runtime_pm, state->wakeref);
14239                 return ret;
14240         }
14241
14242         ret = drm_atomic_helper_setup_commit(&state->base, nonblock);
14243         if (!ret)
14244                 ret = drm_atomic_helper_swap_state(&state->base, true);
14245
14246         if (ret) {
14247                 i915_sw_fence_commit(&state->commit_ready);
14248
14249                 drm_atomic_helper_cleanup_planes(dev, &state->base);
14250                 intel_runtime_pm_put(&dev_priv->runtime_pm, state->wakeref);
14251                 return ret;
14252         }
14253         dev_priv->wm.distrust_bios_wm = false;
14254         intel_shared_dpll_swap_state(state);
14255         intel_atomic_track_fbs(state);
14256
14257         if (state->modeset) {
14258                 memcpy(dev_priv->min_cdclk, state->min_cdclk,
14259                        sizeof(state->min_cdclk));
14260                 memcpy(dev_priv->min_voltage_level, state->min_voltage_level,
14261                        sizeof(state->min_voltage_level));
14262                 dev_priv->active_pipes = state->active_pipes;
14263                 dev_priv->cdclk.force_min_cdclk = state->cdclk.force_min_cdclk;
14264
14265                 intel_cdclk_swap_state(state);
14266         }
14267
14268         drm_atomic_state_get(&state->base);
14269         INIT_WORK(&state->base.commit_work, intel_atomic_commit_work);
14270
14271         i915_sw_fence_commit(&state->commit_ready);
14272         if (nonblock && state->modeset) {
14273                 queue_work(dev_priv->modeset_wq, &state->base.commit_work);
14274         } else if (nonblock) {
14275                 queue_work(system_unbound_wq, &state->base.commit_work);
14276         } else {
14277                 if (state->modeset)
14278                         flush_workqueue(dev_priv->modeset_wq);
14279                 intel_atomic_commit_tail(state);
14280         }
14281
14282         return 0;
14283 }
14284
14285 struct wait_rps_boost {
14286         struct wait_queue_entry wait;
14287
14288         struct drm_crtc *crtc;
14289         struct i915_request *request;
14290 };
14291
14292 static int do_rps_boost(struct wait_queue_entry *_wait,
14293                         unsigned mode, int sync, void *key)
14294 {
14295         struct wait_rps_boost *wait = container_of(_wait, typeof(*wait), wait);
14296         struct i915_request *rq = wait->request;
14297
14298         /*
14299          * If we missed the vblank, but the request is already running it
14300          * is reasonable to assume that it will complete before the next
14301          * vblank without our intervention, so leave RPS alone.
14302          */
14303         if (!i915_request_started(rq))
14304                 gen6_rps_boost(rq);
14305         i915_request_put(rq);
14306
14307         drm_crtc_vblank_put(wait->crtc);
14308
14309         list_del(&wait->wait.entry);
14310         kfree(wait);
14311         return 1;
14312 }
14313
14314 static void add_rps_boost_after_vblank(struct drm_crtc *crtc,
14315                                        struct dma_fence *fence)
14316 {
14317         struct wait_rps_boost *wait;
14318
14319         if (!dma_fence_is_i915(fence))
14320                 return;
14321
14322         if (INTEL_GEN(to_i915(crtc->dev)) < 6)
14323                 return;
14324
14325         if (drm_crtc_vblank_get(crtc))
14326                 return;
14327
14328         wait = kmalloc(sizeof(*wait), GFP_KERNEL);
14329         if (!wait) {
14330                 drm_crtc_vblank_put(crtc);
14331                 return;
14332         }
14333
14334         wait->request = to_request(dma_fence_get(fence));
14335         wait->crtc = crtc;
14336
14337         wait->wait.func = do_rps_boost;
14338         wait->wait.flags = 0;
14339
14340         add_wait_queue(drm_crtc_vblank_waitqueue(crtc), &wait->wait);
14341 }
14342
14343 static int intel_plane_pin_fb(struct intel_plane_state *plane_state)
14344 {
14345         struct intel_plane *plane = to_intel_plane(plane_state->base.plane);
14346         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
14347         struct drm_framebuffer *fb = plane_state->base.fb;
14348         struct i915_vma *vma;
14349
14350         if (plane->id == PLANE_CURSOR &&
14351             INTEL_INFO(dev_priv)->display.cursor_needs_physical) {
14352                 struct drm_i915_gem_object *obj = intel_fb_obj(fb);
14353                 const int align = intel_cursor_alignment(dev_priv);
14354                 int err;
14355
14356                 err = i915_gem_object_attach_phys(obj, align);
14357                 if (err)
14358                         return err;
14359         }
14360
14361         vma = intel_pin_and_fence_fb_obj(fb,
14362                                          &plane_state->view,
14363                                          intel_plane_uses_fence(plane_state),
14364                                          &plane_state->flags);
14365         if (IS_ERR(vma))
14366                 return PTR_ERR(vma);
14367
14368         plane_state->vma = vma;
14369
14370         return 0;
14371 }
14372
14373 static void intel_plane_unpin_fb(struct intel_plane_state *old_plane_state)
14374 {
14375         struct i915_vma *vma;
14376
14377         vma = fetch_and_zero(&old_plane_state->vma);
14378         if (vma)
14379                 intel_unpin_fb_vma(vma, old_plane_state->flags);
14380 }
14381
14382 static void fb_obj_bump_render_priority(struct drm_i915_gem_object *obj)
14383 {
14384         struct i915_sched_attr attr = {
14385                 .priority = I915_PRIORITY_DISPLAY,
14386         };
14387
14388         i915_gem_object_wait_priority(obj, 0, &attr);
14389 }
14390
14391 /**
14392  * intel_prepare_plane_fb - Prepare fb for usage on plane
14393  * @plane: drm plane to prepare for
14394  * @new_state: the plane state being prepared
14395  *
14396  * Prepares a framebuffer for usage on a display plane.  Generally this
14397  * involves pinning the underlying object and updating the frontbuffer tracking
14398  * bits.  Some older platforms need special physical address handling for
14399  * cursor planes.
14400  *
14401  * Must be called with struct_mutex held.
14402  *
14403  * Returns 0 on success, negative error code on failure.
14404  */
14405 int
14406 intel_prepare_plane_fb(struct drm_plane *plane,
14407                        struct drm_plane_state *new_state)
14408 {
14409         struct intel_atomic_state *intel_state =
14410                 to_intel_atomic_state(new_state->state);
14411         struct drm_i915_private *dev_priv = to_i915(plane->dev);
14412         struct drm_framebuffer *fb = new_state->fb;
14413         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
14414         struct drm_i915_gem_object *old_obj = intel_fb_obj(plane->state->fb);
14415         int ret;
14416
14417         if (old_obj) {
14418                 struct intel_crtc_state *crtc_state =
14419                         intel_atomic_get_new_crtc_state(intel_state,
14420                                                         to_intel_crtc(plane->state->crtc));
14421
14422                 /* Big Hammer, we also need to ensure that any pending
14423                  * MI_WAIT_FOR_EVENT inside a user batch buffer on the
14424                  * current scanout is retired before unpinning the old
14425                  * framebuffer. Note that we rely on userspace rendering
14426                  * into the buffer attached to the pipe they are waiting
14427                  * on. If not, userspace generates a GPU hang with IPEHR
14428                  * point to the MI_WAIT_FOR_EVENT.
14429                  *
14430                  * This should only fail upon a hung GPU, in which case we
14431                  * can safely continue.
14432                  */
14433                 if (needs_modeset(crtc_state)) {
14434                         ret = i915_sw_fence_await_reservation(&intel_state->commit_ready,
14435                                                               old_obj->base.resv, NULL,
14436                                                               false, 0,
14437                                                               GFP_KERNEL);
14438                         if (ret < 0)
14439                                 return ret;
14440                 }
14441         }
14442
14443         if (new_state->fence) { /* explicit fencing */
14444                 ret = i915_sw_fence_await_dma_fence(&intel_state->commit_ready,
14445                                                     new_state->fence,
14446                                                     I915_FENCE_TIMEOUT,
14447                                                     GFP_KERNEL);
14448                 if (ret < 0)
14449                         return ret;
14450         }
14451
14452         if (!obj)
14453                 return 0;
14454
14455         ret = i915_gem_object_pin_pages(obj);
14456         if (ret)
14457                 return ret;
14458
14459         ret = mutex_lock_interruptible(&dev_priv->drm.struct_mutex);
14460         if (ret) {
14461                 i915_gem_object_unpin_pages(obj);
14462                 return ret;
14463         }
14464
14465         ret = intel_plane_pin_fb(to_intel_plane_state(new_state));
14466
14467         mutex_unlock(&dev_priv->drm.struct_mutex);
14468         i915_gem_object_unpin_pages(obj);
14469         if (ret)
14470                 return ret;
14471
14472         fb_obj_bump_render_priority(obj);
14473         intel_frontbuffer_flush(obj->frontbuffer, ORIGIN_DIRTYFB);
14474
14475         if (!new_state->fence) { /* implicit fencing */
14476                 struct dma_fence *fence;
14477
14478                 ret = i915_sw_fence_await_reservation(&intel_state->commit_ready,
14479                                                       obj->base.resv, NULL,
14480                                                       false, I915_FENCE_TIMEOUT,
14481                                                       GFP_KERNEL);
14482                 if (ret < 0)
14483                         return ret;
14484
14485                 fence = dma_resv_get_excl_rcu(obj->base.resv);
14486                 if (fence) {
14487                         add_rps_boost_after_vblank(new_state->crtc, fence);
14488                         dma_fence_put(fence);
14489                 }
14490         } else {
14491                 add_rps_boost_after_vblank(new_state->crtc, new_state->fence);
14492         }
14493
14494         /*
14495          * We declare pageflips to be interactive and so merit a small bias
14496          * towards upclocking to deliver the frame on time. By only changing
14497          * the RPS thresholds to sample more regularly and aim for higher
14498          * clocks we can hopefully deliver low power workloads (like kodi)
14499          * that are not quite steady state without resorting to forcing
14500          * maximum clocks following a vblank miss (see do_rps_boost()).
14501          */
14502         if (!intel_state->rps_interactive) {
14503                 intel_rps_mark_interactive(dev_priv, true);
14504                 intel_state->rps_interactive = true;
14505         }
14506
14507         return 0;
14508 }
14509
14510 /**
14511  * intel_cleanup_plane_fb - Cleans up an fb after plane use
14512  * @plane: drm plane to clean up for
14513  * @old_state: the state from the previous modeset
14514  *
14515  * Cleans up a framebuffer that has just been removed from a plane.
14516  *
14517  * Must be called with struct_mutex held.
14518  */
14519 void
14520 intel_cleanup_plane_fb(struct drm_plane *plane,
14521                        struct drm_plane_state *old_state)
14522 {
14523         struct intel_atomic_state *intel_state =
14524                 to_intel_atomic_state(old_state->state);
14525         struct drm_i915_private *dev_priv = to_i915(plane->dev);
14526
14527         if (intel_state->rps_interactive) {
14528                 intel_rps_mark_interactive(dev_priv, false);
14529                 intel_state->rps_interactive = false;
14530         }
14531
14532         /* Should only be called after a successful intel_prepare_plane_fb()! */
14533         mutex_lock(&dev_priv->drm.struct_mutex);
14534         intel_plane_unpin_fb(to_intel_plane_state(old_state));
14535         mutex_unlock(&dev_priv->drm.struct_mutex);
14536 }
14537
14538 int
14539 skl_max_scale(const struct intel_crtc_state *crtc_state,
14540               u32 pixel_format)
14541 {
14542         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
14543         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
14544         int max_scale, mult;
14545         int crtc_clock, max_dotclk, tmpclk1, tmpclk2;
14546
14547         if (!crtc_state->base.enable)
14548                 return DRM_PLANE_HELPER_NO_SCALING;
14549
14550         crtc_clock = crtc_state->base.adjusted_mode.crtc_clock;
14551         max_dotclk = to_intel_atomic_state(crtc_state->base.state)->cdclk.logical.cdclk;
14552
14553         if (IS_GEMINILAKE(dev_priv) || INTEL_GEN(dev_priv) >= 10)
14554                 max_dotclk *= 2;
14555
14556         if (WARN_ON_ONCE(!crtc_clock || max_dotclk < crtc_clock))
14557                 return DRM_PLANE_HELPER_NO_SCALING;
14558
14559         /*
14560          * skl max scale is lower of:
14561          *    close to 3 but not 3, -1 is for that purpose
14562          *            or
14563          *    cdclk/crtc_clock
14564          */
14565         mult = is_planar_yuv_format(pixel_format) ? 2 : 3;
14566         tmpclk1 = (1 << 16) * mult - 1;
14567         tmpclk2 = (1 << 8) * ((max_dotclk << 8) / crtc_clock);
14568         max_scale = min(tmpclk1, tmpclk2);
14569
14570         return max_scale;
14571 }
14572
14573 static void intel_begin_crtc_commit(struct intel_atomic_state *state,
14574                                     struct intel_crtc *crtc)
14575 {
14576         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
14577         struct intel_crtc_state *old_crtc_state =
14578                 intel_atomic_get_old_crtc_state(state, crtc);
14579         struct intel_crtc_state *new_crtc_state =
14580                 intel_atomic_get_new_crtc_state(state, crtc);
14581         bool modeset = needs_modeset(new_crtc_state);
14582
14583         /* Perform vblank evasion around commit operation */
14584         intel_pipe_update_start(new_crtc_state);
14585
14586         if (modeset)
14587                 goto out;
14588
14589         if (new_crtc_state->base.color_mgmt_changed ||
14590             new_crtc_state->update_pipe)
14591                 intel_color_commit(new_crtc_state);
14592
14593         if (new_crtc_state->update_pipe)
14594                 intel_update_pipe_config(old_crtc_state, new_crtc_state);
14595         else if (INTEL_GEN(dev_priv) >= 9)
14596                 skl_detach_scalers(new_crtc_state);
14597
14598         if (INTEL_GEN(dev_priv) >= 9 || IS_BROADWELL(dev_priv))
14599                 bdw_set_pipemisc(new_crtc_state);
14600
14601 out:
14602         if (dev_priv->display.atomic_update_watermarks)
14603                 dev_priv->display.atomic_update_watermarks(state,
14604                                                            new_crtc_state);
14605 }
14606
14607 void intel_crtc_arm_fifo_underrun(struct intel_crtc *crtc,
14608                                   struct intel_crtc_state *crtc_state)
14609 {
14610         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
14611
14612         if (!IS_GEN(dev_priv, 2))
14613                 intel_set_cpu_fifo_underrun_reporting(dev_priv, crtc->pipe, true);
14614
14615         if (crtc_state->has_pch_encoder) {
14616                 enum pipe pch_transcoder =
14617                         intel_crtc_pch_transcoder(crtc);
14618
14619                 intel_set_pch_fifo_underrun_reporting(dev_priv, pch_transcoder, true);
14620         }
14621 }
14622
14623 static void intel_finish_crtc_commit(struct intel_atomic_state *state,
14624                                      struct intel_crtc *crtc)
14625 {
14626         struct intel_crtc_state *old_crtc_state =
14627                 intel_atomic_get_old_crtc_state(state, crtc);
14628         struct intel_crtc_state *new_crtc_state =
14629                 intel_atomic_get_new_crtc_state(state, crtc);
14630
14631         intel_pipe_update_end(new_crtc_state);
14632
14633         if (new_crtc_state->update_pipe &&
14634             !needs_modeset(new_crtc_state) &&
14635             old_crtc_state->base.mode.private_flags & I915_MODE_FLAG_INHERITED)
14636                 intel_crtc_arm_fifo_underrun(crtc, new_crtc_state);
14637 }
14638
14639 /**
14640  * intel_plane_destroy - destroy a plane
14641  * @plane: plane to destroy
14642  *
14643  * Common destruction function for all types of planes (primary, cursor,
14644  * sprite).
14645  */
14646 void intel_plane_destroy(struct drm_plane *plane)
14647 {
14648         drm_plane_cleanup(plane);
14649         kfree(to_intel_plane(plane));
14650 }
14651
14652 static bool i8xx_plane_format_mod_supported(struct drm_plane *_plane,
14653                                             u32 format, u64 modifier)
14654 {
14655         switch (modifier) {
14656         case DRM_FORMAT_MOD_LINEAR:
14657         case I915_FORMAT_MOD_X_TILED:
14658                 break;
14659         default:
14660                 return false;
14661         }
14662
14663         switch (format) {
14664         case DRM_FORMAT_C8:
14665         case DRM_FORMAT_RGB565:
14666         case DRM_FORMAT_XRGB1555:
14667         case DRM_FORMAT_XRGB8888:
14668                 return modifier == DRM_FORMAT_MOD_LINEAR ||
14669                         modifier == I915_FORMAT_MOD_X_TILED;
14670         default:
14671                 return false;
14672         }
14673 }
14674
14675 static bool i965_plane_format_mod_supported(struct drm_plane *_plane,
14676                                             u32 format, u64 modifier)
14677 {
14678         switch (modifier) {
14679         case DRM_FORMAT_MOD_LINEAR:
14680         case I915_FORMAT_MOD_X_TILED:
14681                 break;
14682         default:
14683                 return false;
14684         }
14685
14686         switch (format) {
14687         case DRM_FORMAT_C8:
14688         case DRM_FORMAT_RGB565:
14689         case DRM_FORMAT_XRGB8888:
14690         case DRM_FORMAT_XBGR8888:
14691         case DRM_FORMAT_XRGB2101010:
14692         case DRM_FORMAT_XBGR2101010:
14693                 return modifier == DRM_FORMAT_MOD_LINEAR ||
14694                         modifier == I915_FORMAT_MOD_X_TILED;
14695         default:
14696                 return false;
14697         }
14698 }
14699
14700 static bool intel_cursor_format_mod_supported(struct drm_plane *_plane,
14701                                               u32 format, u64 modifier)
14702 {
14703         return modifier == DRM_FORMAT_MOD_LINEAR &&
14704                 format == DRM_FORMAT_ARGB8888;
14705 }
14706
14707 static const struct drm_plane_funcs i965_plane_funcs = {
14708         .update_plane = drm_atomic_helper_update_plane,
14709         .disable_plane = drm_atomic_helper_disable_plane,
14710         .destroy = intel_plane_destroy,
14711         .atomic_duplicate_state = intel_plane_duplicate_state,
14712         .atomic_destroy_state = intel_plane_destroy_state,
14713         .format_mod_supported = i965_plane_format_mod_supported,
14714 };
14715
14716 static const struct drm_plane_funcs i8xx_plane_funcs = {
14717         .update_plane = drm_atomic_helper_update_plane,
14718         .disable_plane = drm_atomic_helper_disable_plane,
14719         .destroy = intel_plane_destroy,
14720         .atomic_duplicate_state = intel_plane_duplicate_state,
14721         .atomic_destroy_state = intel_plane_destroy_state,
14722         .format_mod_supported = i8xx_plane_format_mod_supported,
14723 };
14724
14725 static int
14726 intel_legacy_cursor_update(struct drm_plane *plane,
14727                            struct drm_crtc *crtc,
14728                            struct drm_framebuffer *fb,
14729                            int crtc_x, int crtc_y,
14730                            unsigned int crtc_w, unsigned int crtc_h,
14731                            u32 src_x, u32 src_y,
14732                            u32 src_w, u32 src_h,
14733                            struct drm_modeset_acquire_ctx *ctx)
14734 {
14735         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
14736         struct drm_plane_state *old_plane_state, *new_plane_state;
14737         struct intel_plane *intel_plane = to_intel_plane(plane);
14738         struct intel_crtc_state *crtc_state =
14739                 to_intel_crtc_state(crtc->state);
14740         struct intel_crtc_state *new_crtc_state;
14741         int ret;
14742
14743         /*
14744          * When crtc is inactive or there is a modeset pending,
14745          * wait for it to complete in the slowpath
14746          */
14747         if (!crtc_state->base.active || needs_modeset(crtc_state) ||
14748             crtc_state->update_pipe)
14749                 goto slow;
14750
14751         old_plane_state = plane->state;
14752         /*
14753          * Don't do an async update if there is an outstanding commit modifying
14754          * the plane.  This prevents our async update's changes from getting
14755          * overridden by a previous synchronous update's state.
14756          */
14757         if (old_plane_state->commit &&
14758             !try_wait_for_completion(&old_plane_state->commit->hw_done))
14759                 goto slow;
14760
14761         /*
14762          * If any parameters change that may affect watermarks,
14763          * take the slowpath. Only changing fb or position should be
14764          * in the fastpath.
14765          */
14766         if (old_plane_state->crtc != crtc ||
14767             old_plane_state->src_w != src_w ||
14768             old_plane_state->src_h != src_h ||
14769             old_plane_state->crtc_w != crtc_w ||
14770             old_plane_state->crtc_h != crtc_h ||
14771             !old_plane_state->fb != !fb)
14772                 goto slow;
14773
14774         new_plane_state = intel_plane_duplicate_state(plane);
14775         if (!new_plane_state)
14776                 return -ENOMEM;
14777
14778         new_crtc_state = to_intel_crtc_state(intel_crtc_duplicate_state(crtc));
14779         if (!new_crtc_state) {
14780                 ret = -ENOMEM;
14781                 goto out_free;
14782         }
14783
14784         drm_atomic_set_fb_for_plane(new_plane_state, fb);
14785
14786         new_plane_state->src_x = src_x;
14787         new_plane_state->src_y = src_y;
14788         new_plane_state->src_w = src_w;
14789         new_plane_state->src_h = src_h;
14790         new_plane_state->crtc_x = crtc_x;
14791         new_plane_state->crtc_y = crtc_y;
14792         new_plane_state->crtc_w = crtc_w;
14793         new_plane_state->crtc_h = crtc_h;
14794
14795         ret = intel_plane_atomic_check_with_state(crtc_state, new_crtc_state,
14796                                                   to_intel_plane_state(old_plane_state),
14797                                                   to_intel_plane_state(new_plane_state));
14798         if (ret)
14799                 goto out_free;
14800
14801         ret = mutex_lock_interruptible(&dev_priv->drm.struct_mutex);
14802         if (ret)
14803                 goto out_free;
14804
14805         ret = intel_plane_pin_fb(to_intel_plane_state(new_plane_state));
14806         if (ret)
14807                 goto out_unlock;
14808
14809         intel_frontbuffer_flush(to_intel_frontbuffer(fb), ORIGIN_FLIP);
14810         intel_frontbuffer_track(to_intel_frontbuffer(old_plane_state->fb),
14811                                 to_intel_frontbuffer(fb),
14812                                 intel_plane->frontbuffer_bit);
14813
14814         /* Swap plane state */
14815         plane->state = new_plane_state;
14816
14817         /*
14818          * We cannot swap crtc_state as it may be in use by an atomic commit or
14819          * page flip that's running simultaneously. If we swap crtc_state and
14820          * destroy the old state, we will cause a use-after-free there.
14821          *
14822          * Only update active_planes, which is needed for our internal
14823          * bookkeeping. Either value will do the right thing when updating
14824          * planes atomically. If the cursor was part of the atomic update then
14825          * we would have taken the slowpath.
14826          */
14827         crtc_state->active_planes = new_crtc_state->active_planes;
14828
14829         if (plane->state->visible)
14830                 intel_update_plane(intel_plane, crtc_state,
14831                                    to_intel_plane_state(plane->state));
14832         else
14833                 intel_disable_plane(intel_plane, crtc_state);
14834
14835         intel_plane_unpin_fb(to_intel_plane_state(old_plane_state));
14836
14837 out_unlock:
14838         mutex_unlock(&dev_priv->drm.struct_mutex);
14839 out_free:
14840         if (new_crtc_state)
14841                 intel_crtc_destroy_state(crtc, &new_crtc_state->base);
14842         if (ret)
14843                 intel_plane_destroy_state(plane, new_plane_state);
14844         else
14845                 intel_plane_destroy_state(plane, old_plane_state);
14846         return ret;
14847
14848 slow:
14849         return drm_atomic_helper_update_plane(plane, crtc, fb,
14850                                               crtc_x, crtc_y, crtc_w, crtc_h,
14851                                               src_x, src_y, src_w, src_h, ctx);
14852 }
14853
14854 static const struct drm_plane_funcs intel_cursor_plane_funcs = {
14855         .update_plane = intel_legacy_cursor_update,
14856         .disable_plane = drm_atomic_helper_disable_plane,
14857         .destroy = intel_plane_destroy,
14858         .atomic_duplicate_state = intel_plane_duplicate_state,
14859         .atomic_destroy_state = intel_plane_destroy_state,
14860         .format_mod_supported = intel_cursor_format_mod_supported,
14861 };
14862
14863 static bool i9xx_plane_has_fbc(struct drm_i915_private *dev_priv,
14864                                enum i9xx_plane_id i9xx_plane)
14865 {
14866         if (!HAS_FBC(dev_priv))
14867                 return false;
14868
14869         if (IS_BROADWELL(dev_priv) || IS_HASWELL(dev_priv))
14870                 return i9xx_plane == PLANE_A; /* tied to pipe A */
14871         else if (IS_IVYBRIDGE(dev_priv))
14872                 return i9xx_plane == PLANE_A || i9xx_plane == PLANE_B ||
14873                         i9xx_plane == PLANE_C;
14874         else if (INTEL_GEN(dev_priv) >= 4)
14875                 return i9xx_plane == PLANE_A || i9xx_plane == PLANE_B;
14876         else
14877                 return i9xx_plane == PLANE_A;
14878 }
14879
14880 static struct intel_plane *
14881 intel_primary_plane_create(struct drm_i915_private *dev_priv, enum pipe pipe)
14882 {
14883         struct intel_plane *plane;
14884         const struct drm_plane_funcs *plane_funcs;
14885         unsigned int supported_rotations;
14886         unsigned int possible_crtcs;
14887         const u64 *modifiers;
14888         const u32 *formats;
14889         int num_formats;
14890         int ret;
14891
14892         if (INTEL_GEN(dev_priv) >= 9)
14893                 return skl_universal_plane_create(dev_priv, pipe,
14894                                                   PLANE_PRIMARY);
14895
14896         plane = intel_plane_alloc();
14897         if (IS_ERR(plane))
14898                 return plane;
14899
14900         plane->pipe = pipe;
14901         /*
14902          * On gen2/3 only plane A can do FBC, but the panel fitter and LVDS
14903          * port is hooked to pipe B. Hence we want plane A feeding pipe B.
14904          */
14905         if (HAS_FBC(dev_priv) && INTEL_GEN(dev_priv) < 4)
14906                 plane->i9xx_plane = (enum i9xx_plane_id) !pipe;
14907         else
14908                 plane->i9xx_plane = (enum i9xx_plane_id) pipe;
14909         plane->id = PLANE_PRIMARY;
14910         plane->frontbuffer_bit = INTEL_FRONTBUFFER(pipe, plane->id);
14911
14912         plane->has_fbc = i9xx_plane_has_fbc(dev_priv, plane->i9xx_plane);
14913         if (plane->has_fbc) {
14914                 struct intel_fbc *fbc = &dev_priv->fbc;
14915
14916                 fbc->possible_framebuffer_bits |= plane->frontbuffer_bit;
14917         }
14918
14919         if (INTEL_GEN(dev_priv) >= 4) {
14920                 formats = i965_primary_formats;
14921                 num_formats = ARRAY_SIZE(i965_primary_formats);
14922                 modifiers = i9xx_format_modifiers;
14923
14924                 plane->max_stride = i9xx_plane_max_stride;
14925                 plane->update_plane = i9xx_update_plane;
14926                 plane->disable_plane = i9xx_disable_plane;
14927                 plane->get_hw_state = i9xx_plane_get_hw_state;
14928                 plane->check_plane = i9xx_plane_check;
14929
14930                 plane_funcs = &i965_plane_funcs;
14931         } else {
14932                 formats = i8xx_primary_formats;
14933                 num_formats = ARRAY_SIZE(i8xx_primary_formats);
14934                 modifiers = i9xx_format_modifiers;
14935
14936                 plane->max_stride = i9xx_plane_max_stride;
14937                 plane->update_plane = i9xx_update_plane;
14938                 plane->disable_plane = i9xx_disable_plane;
14939                 plane->get_hw_state = i9xx_plane_get_hw_state;
14940                 plane->check_plane = i9xx_plane_check;
14941
14942                 plane_funcs = &i8xx_plane_funcs;
14943         }
14944
14945         possible_crtcs = BIT(pipe);
14946
14947         if (INTEL_GEN(dev_priv) >= 5 || IS_G4X(dev_priv))
14948                 ret = drm_universal_plane_init(&dev_priv->drm, &plane->base,
14949                                                possible_crtcs, plane_funcs,
14950                                                formats, num_formats, modifiers,
14951                                                DRM_PLANE_TYPE_PRIMARY,
14952                                                "primary %c", pipe_name(pipe));
14953         else
14954                 ret = drm_universal_plane_init(&dev_priv->drm, &plane->base,
14955                                                possible_crtcs, plane_funcs,
14956                                                formats, num_formats, modifiers,
14957                                                DRM_PLANE_TYPE_PRIMARY,
14958                                                "plane %c",
14959                                                plane_name(plane->i9xx_plane));
14960         if (ret)
14961                 goto fail;
14962
14963         if (IS_CHERRYVIEW(dev_priv) && pipe == PIPE_B) {
14964                 supported_rotations =
14965                         DRM_MODE_ROTATE_0 | DRM_MODE_ROTATE_180 |
14966                         DRM_MODE_REFLECT_X;
14967         } else if (INTEL_GEN(dev_priv) >= 4) {
14968                 supported_rotations =
14969                         DRM_MODE_ROTATE_0 | DRM_MODE_ROTATE_180;
14970         } else {
14971                 supported_rotations = DRM_MODE_ROTATE_0;
14972         }
14973
14974         if (INTEL_GEN(dev_priv) >= 4)
14975                 drm_plane_create_rotation_property(&plane->base,
14976                                                    DRM_MODE_ROTATE_0,
14977                                                    supported_rotations);
14978
14979         drm_plane_helper_add(&plane->base, &intel_plane_helper_funcs);
14980
14981         return plane;
14982
14983 fail:
14984         intel_plane_free(plane);
14985
14986         return ERR_PTR(ret);
14987 }
14988
14989 static struct intel_plane *
14990 intel_cursor_plane_create(struct drm_i915_private *dev_priv,
14991                           enum pipe pipe)
14992 {
14993         unsigned int possible_crtcs;
14994         struct intel_plane *cursor;
14995         int ret;
14996
14997         cursor = intel_plane_alloc();
14998         if (IS_ERR(cursor))
14999                 return cursor;
15000
15001         cursor->pipe = pipe;
15002         cursor->i9xx_plane = (enum i9xx_plane_id) pipe;
15003         cursor->id = PLANE_CURSOR;
15004         cursor->frontbuffer_bit = INTEL_FRONTBUFFER(pipe, cursor->id);
15005
15006         if (IS_I845G(dev_priv) || IS_I865G(dev_priv)) {
15007                 cursor->max_stride = i845_cursor_max_stride;
15008                 cursor->update_plane = i845_update_cursor;
15009                 cursor->disable_plane = i845_disable_cursor;
15010                 cursor->get_hw_state = i845_cursor_get_hw_state;
15011                 cursor->check_plane = i845_check_cursor;
15012         } else {
15013                 cursor->max_stride = i9xx_cursor_max_stride;
15014                 cursor->update_plane = i9xx_update_cursor;
15015                 cursor->disable_plane = i9xx_disable_cursor;
15016                 cursor->get_hw_state = i9xx_cursor_get_hw_state;
15017                 cursor->check_plane = i9xx_check_cursor;
15018         }
15019
15020         cursor->cursor.base = ~0;
15021         cursor->cursor.cntl = ~0;
15022
15023         if (IS_I845G(dev_priv) || IS_I865G(dev_priv) || HAS_CUR_FBC(dev_priv))
15024                 cursor->cursor.size = ~0;
15025
15026         possible_crtcs = BIT(pipe);
15027
15028         ret = drm_universal_plane_init(&dev_priv->drm, &cursor->base,
15029                                        possible_crtcs, &intel_cursor_plane_funcs,
15030                                        intel_cursor_formats,
15031                                        ARRAY_SIZE(intel_cursor_formats),
15032                                        cursor_format_modifiers,
15033                                        DRM_PLANE_TYPE_CURSOR,
15034                                        "cursor %c", pipe_name(pipe));
15035         if (ret)
15036                 goto fail;
15037
15038         if (INTEL_GEN(dev_priv) >= 4)
15039                 drm_plane_create_rotation_property(&cursor->base,
15040                                                    DRM_MODE_ROTATE_0,
15041                                                    DRM_MODE_ROTATE_0 |
15042                                                    DRM_MODE_ROTATE_180);
15043
15044         drm_plane_helper_add(&cursor->base, &intel_plane_helper_funcs);
15045
15046         return cursor;
15047
15048 fail:
15049         intel_plane_free(cursor);
15050
15051         return ERR_PTR(ret);
15052 }
15053
15054 static void intel_crtc_init_scalers(struct intel_crtc *crtc,
15055                                     struct intel_crtc_state *crtc_state)
15056 {
15057         struct intel_crtc_scaler_state *scaler_state =
15058                 &crtc_state->scaler_state;
15059         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
15060         int i;
15061
15062         crtc->num_scalers = RUNTIME_INFO(dev_priv)->num_scalers[crtc->pipe];
15063         if (!crtc->num_scalers)
15064                 return;
15065
15066         for (i = 0; i < crtc->num_scalers; i++) {
15067                 struct intel_scaler *scaler = &scaler_state->scalers[i];
15068
15069                 scaler->in_use = 0;
15070                 scaler->mode = 0;
15071         }
15072
15073         scaler_state->scaler_id = -1;
15074 }
15075
15076 #define INTEL_CRTC_FUNCS \
15077         .gamma_set = drm_atomic_helper_legacy_gamma_set, \
15078         .set_config = drm_atomic_helper_set_config, \
15079         .destroy = intel_crtc_destroy, \
15080         .page_flip = drm_atomic_helper_page_flip, \
15081         .atomic_duplicate_state = intel_crtc_duplicate_state, \
15082         .atomic_destroy_state = intel_crtc_destroy_state, \
15083         .set_crc_source = intel_crtc_set_crc_source, \
15084         .verify_crc_source = intel_crtc_verify_crc_source, \
15085         .get_crc_sources = intel_crtc_get_crc_sources
15086
15087 static const struct drm_crtc_funcs bdw_crtc_funcs = {
15088         INTEL_CRTC_FUNCS,
15089
15090         .get_vblank_counter = g4x_get_vblank_counter,
15091         .enable_vblank = bdw_enable_vblank,
15092         .disable_vblank = bdw_disable_vblank,
15093 };
15094
15095 static const struct drm_crtc_funcs ilk_crtc_funcs = {
15096         INTEL_CRTC_FUNCS,
15097
15098         .get_vblank_counter = g4x_get_vblank_counter,
15099         .enable_vblank = ilk_enable_vblank,
15100         .disable_vblank = ilk_disable_vblank,
15101 };
15102
15103 static const struct drm_crtc_funcs g4x_crtc_funcs = {
15104         INTEL_CRTC_FUNCS,
15105
15106         .get_vblank_counter = g4x_get_vblank_counter,
15107         .enable_vblank = i965_enable_vblank,
15108         .disable_vblank = i965_disable_vblank,
15109 };
15110
15111 static const struct drm_crtc_funcs i965_crtc_funcs = {
15112         INTEL_CRTC_FUNCS,
15113
15114         .get_vblank_counter = i915_get_vblank_counter,
15115         .enable_vblank = i965_enable_vblank,
15116         .disable_vblank = i965_disable_vblank,
15117 };
15118
15119 static const struct drm_crtc_funcs i945gm_crtc_funcs = {
15120         INTEL_CRTC_FUNCS,
15121
15122         .get_vblank_counter = i915_get_vblank_counter,
15123         .enable_vblank = i945gm_enable_vblank,
15124         .disable_vblank = i945gm_disable_vblank,
15125 };
15126
15127 static const struct drm_crtc_funcs i915_crtc_funcs = {
15128         INTEL_CRTC_FUNCS,
15129
15130         .get_vblank_counter = i915_get_vblank_counter,
15131         .enable_vblank = i8xx_enable_vblank,
15132         .disable_vblank = i8xx_disable_vblank,
15133 };
15134
15135 static const struct drm_crtc_funcs i8xx_crtc_funcs = {
15136         INTEL_CRTC_FUNCS,
15137
15138         /* no hw vblank counter */
15139         .enable_vblank = i8xx_enable_vblank,
15140         .disable_vblank = i8xx_disable_vblank,
15141 };
15142
15143 static int intel_crtc_init(struct drm_i915_private *dev_priv, enum pipe pipe)
15144 {
15145         const struct drm_crtc_funcs *funcs;
15146         struct intel_crtc *intel_crtc;
15147         struct intel_crtc_state *crtc_state = NULL;
15148         struct intel_plane *primary = NULL;
15149         struct intel_plane *cursor = NULL;
15150         int sprite, ret;
15151
15152         intel_crtc = kzalloc(sizeof(*intel_crtc), GFP_KERNEL);
15153         if (!intel_crtc)
15154                 return -ENOMEM;
15155
15156         crtc_state = kzalloc(sizeof(*crtc_state), GFP_KERNEL);
15157         if (!crtc_state) {
15158                 ret = -ENOMEM;
15159                 goto fail;
15160         }
15161         __drm_atomic_helper_crtc_reset(&intel_crtc->base, &crtc_state->base);
15162         intel_crtc->config = crtc_state;
15163
15164         primary = intel_primary_plane_create(dev_priv, pipe);
15165         if (IS_ERR(primary)) {
15166                 ret = PTR_ERR(primary);
15167                 goto fail;
15168         }
15169         intel_crtc->plane_ids_mask |= BIT(primary->id);
15170
15171         for_each_sprite(dev_priv, pipe, sprite) {
15172                 struct intel_plane *plane;
15173
15174                 plane = intel_sprite_plane_create(dev_priv, pipe, sprite);
15175                 if (IS_ERR(plane)) {
15176                         ret = PTR_ERR(plane);
15177                         goto fail;
15178                 }
15179                 intel_crtc->plane_ids_mask |= BIT(plane->id);
15180         }
15181
15182         cursor = intel_cursor_plane_create(dev_priv, pipe);
15183         if (IS_ERR(cursor)) {
15184                 ret = PTR_ERR(cursor);
15185                 goto fail;
15186         }
15187         intel_crtc->plane_ids_mask |= BIT(cursor->id);
15188
15189         if (HAS_GMCH(dev_priv)) {
15190                 if (IS_CHERRYVIEW(dev_priv) ||
15191                     IS_VALLEYVIEW(dev_priv) || IS_G4X(dev_priv))
15192                         funcs = &g4x_crtc_funcs;
15193                 else if (IS_GEN(dev_priv, 4))
15194                         funcs = &i965_crtc_funcs;
15195                 else if (IS_I945GM(dev_priv))
15196                         funcs = &i945gm_crtc_funcs;
15197                 else if (IS_GEN(dev_priv, 3))
15198                         funcs = &i915_crtc_funcs;
15199                 else
15200                         funcs = &i8xx_crtc_funcs;
15201         } else {
15202                 if (INTEL_GEN(dev_priv) >= 8)
15203                         funcs = &bdw_crtc_funcs;
15204                 else
15205                         funcs = &ilk_crtc_funcs;
15206         }
15207
15208         ret = drm_crtc_init_with_planes(&dev_priv->drm, &intel_crtc->base,
15209                                         &primary->base, &cursor->base,
15210                                         funcs, "pipe %c", pipe_name(pipe));
15211         if (ret)
15212                 goto fail;
15213
15214         intel_crtc->pipe = pipe;
15215
15216         /* initialize shared scalers */
15217         intel_crtc_init_scalers(intel_crtc, crtc_state);
15218
15219         BUG_ON(pipe >= ARRAY_SIZE(dev_priv->pipe_to_crtc_mapping) ||
15220                dev_priv->pipe_to_crtc_mapping[pipe] != NULL);
15221         dev_priv->pipe_to_crtc_mapping[pipe] = intel_crtc;
15222
15223         if (INTEL_GEN(dev_priv) < 9) {
15224                 enum i9xx_plane_id i9xx_plane = primary->i9xx_plane;
15225
15226                 BUG_ON(i9xx_plane >= ARRAY_SIZE(dev_priv->plane_to_crtc_mapping) ||
15227                        dev_priv->plane_to_crtc_mapping[i9xx_plane] != NULL);
15228                 dev_priv->plane_to_crtc_mapping[i9xx_plane] = intel_crtc;
15229         }
15230
15231         drm_crtc_helper_add(&intel_crtc->base, &intel_helper_funcs);
15232
15233         intel_color_init(intel_crtc);
15234
15235         WARN_ON(drm_crtc_index(&intel_crtc->base) != intel_crtc->pipe);
15236
15237         return 0;
15238
15239 fail:
15240         /*
15241          * drm_mode_config_cleanup() will free up any
15242          * crtcs/planes already initialized.
15243          */
15244         kfree(crtc_state);
15245         kfree(intel_crtc);
15246
15247         return ret;
15248 }
15249
15250 int intel_get_pipe_from_crtc_id_ioctl(struct drm_device *dev, void *data,
15251                                       struct drm_file *file)
15252 {
15253         struct drm_i915_get_pipe_from_crtc_id *pipe_from_crtc_id = data;
15254         struct drm_crtc *drmmode_crtc;
15255         struct intel_crtc *crtc;
15256
15257         drmmode_crtc = drm_crtc_find(dev, file, pipe_from_crtc_id->crtc_id);
15258         if (!drmmode_crtc)
15259                 return -ENOENT;
15260
15261         crtc = to_intel_crtc(drmmode_crtc);
15262         pipe_from_crtc_id->pipe = crtc->pipe;
15263
15264         return 0;
15265 }
15266
15267 static int intel_encoder_clones(struct intel_encoder *encoder)
15268 {
15269         struct drm_device *dev = encoder->base.dev;
15270         struct intel_encoder *source_encoder;
15271         int index_mask = 0;
15272         int entry = 0;
15273
15274         for_each_intel_encoder(dev, source_encoder) {
15275                 if (encoders_cloneable(encoder, source_encoder))
15276                         index_mask |= (1 << entry);
15277
15278                 entry++;
15279         }
15280
15281         return index_mask;
15282 }
15283
15284 static bool ilk_has_edp_a(struct drm_i915_private *dev_priv)
15285 {
15286         if (!IS_MOBILE(dev_priv))
15287                 return false;
15288
15289         if ((I915_READ(DP_A) & DP_DETECTED) == 0)
15290                 return false;
15291
15292         if (IS_GEN(dev_priv, 5) && (I915_READ(FUSE_STRAP) & ILK_eDP_A_DISABLE))
15293                 return false;
15294
15295         return true;
15296 }
15297
15298 static bool intel_ddi_crt_present(struct drm_i915_private *dev_priv)
15299 {
15300         if (INTEL_GEN(dev_priv) >= 9)
15301                 return false;
15302
15303         if (IS_HSW_ULT(dev_priv) || IS_BDW_ULT(dev_priv))
15304                 return false;
15305
15306         if (HAS_PCH_LPT_H(dev_priv) &&
15307             I915_READ(SFUSE_STRAP) & SFUSE_STRAP_CRT_DISABLED)
15308                 return false;
15309
15310         /* DDI E can't be used if DDI A requires 4 lanes */
15311         if (I915_READ(DDI_BUF_CTL(PORT_A)) & DDI_A_4_LANES)
15312                 return false;
15313
15314         if (!dev_priv->vbt.int_crt_support)
15315                 return false;
15316
15317         return true;
15318 }
15319
15320 void intel_pps_unlock_regs_wa(struct drm_i915_private *dev_priv)
15321 {
15322         int pps_num;
15323         int pps_idx;
15324
15325         if (HAS_DDI(dev_priv))
15326                 return;
15327         /*
15328          * This w/a is needed at least on CPT/PPT, but to be sure apply it
15329          * everywhere where registers can be write protected.
15330          */
15331         if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
15332                 pps_num = 2;
15333         else
15334                 pps_num = 1;
15335
15336         for (pps_idx = 0; pps_idx < pps_num; pps_idx++) {
15337                 u32 val = I915_READ(PP_CONTROL(pps_idx));
15338
15339                 val = (val & ~PANEL_UNLOCK_MASK) | PANEL_UNLOCK_REGS;
15340                 I915_WRITE(PP_CONTROL(pps_idx), val);
15341         }
15342 }
15343
15344 static void intel_pps_init(struct drm_i915_private *dev_priv)
15345 {
15346         if (HAS_PCH_SPLIT(dev_priv) || IS_GEN9_LP(dev_priv))
15347                 dev_priv->pps_mmio_base = PCH_PPS_BASE;
15348         else if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
15349                 dev_priv->pps_mmio_base = VLV_PPS_BASE;
15350         else
15351                 dev_priv->pps_mmio_base = PPS_BASE;
15352
15353         intel_pps_unlock_regs_wa(dev_priv);
15354 }
15355
15356 static void intel_setup_outputs(struct drm_i915_private *dev_priv)
15357 {
15358         struct intel_encoder *encoder;
15359         bool dpd_is_edp = false;
15360
15361         intel_pps_init(dev_priv);
15362
15363         if (!HAS_DISPLAY(dev_priv))
15364                 return;
15365
15366         if (INTEL_GEN(dev_priv) >= 12) {
15367                 /* TODO: initialize TC ports as well */
15368                 intel_ddi_init(dev_priv, PORT_A);
15369                 intel_ddi_init(dev_priv, PORT_B);
15370                 icl_dsi_init(dev_priv);
15371         } else if (IS_ELKHARTLAKE(dev_priv)) {
15372                 intel_ddi_init(dev_priv, PORT_A);
15373                 intel_ddi_init(dev_priv, PORT_B);
15374                 intel_ddi_init(dev_priv, PORT_C);
15375                 intel_ddi_init(dev_priv, PORT_D);
15376                 icl_dsi_init(dev_priv);
15377         } else if (IS_GEN(dev_priv, 11)) {
15378                 intel_ddi_init(dev_priv, PORT_A);
15379                 intel_ddi_init(dev_priv, PORT_B);
15380                 intel_ddi_init(dev_priv, PORT_C);
15381                 intel_ddi_init(dev_priv, PORT_D);
15382                 intel_ddi_init(dev_priv, PORT_E);
15383                 /*
15384                  * On some ICL SKUs port F is not present. No strap bits for
15385                  * this, so rely on VBT.
15386                  * Work around broken VBTs on SKUs known to have no port F.
15387                  */
15388                 if (IS_ICL_WITH_PORT_F(dev_priv) &&
15389                     intel_bios_is_port_present(dev_priv, PORT_F))
15390                         intel_ddi_init(dev_priv, PORT_F);
15391
15392                 icl_dsi_init(dev_priv);
15393         } else if (IS_GEN9_LP(dev_priv)) {
15394                 /*
15395                  * FIXME: Broxton doesn't support port detection via the
15396                  * DDI_BUF_CTL_A or SFUSE_STRAP registers, find another way to
15397                  * detect the ports.
15398                  */
15399                 intel_ddi_init(dev_priv, PORT_A);
15400                 intel_ddi_init(dev_priv, PORT_B);
15401                 intel_ddi_init(dev_priv, PORT_C);
15402
15403                 vlv_dsi_init(dev_priv);
15404         } else if (HAS_DDI(dev_priv)) {
15405                 int found;
15406
15407                 if (intel_ddi_crt_present(dev_priv))
15408                         intel_crt_init(dev_priv);
15409
15410                 /*
15411                  * Haswell uses DDI functions to detect digital outputs.
15412                  * On SKL pre-D0 the strap isn't connected, so we assume
15413                  * it's there.
15414                  */
15415                 found = I915_READ(DDI_BUF_CTL(PORT_A)) & DDI_INIT_DISPLAY_DETECTED;
15416                 /* WaIgnoreDDIAStrap: skl */
15417                 if (found || IS_GEN9_BC(dev_priv))
15418                         intel_ddi_init(dev_priv, PORT_A);
15419
15420                 /* DDI B, C, D, and F detection is indicated by the SFUSE_STRAP
15421                  * register */
15422                 found = I915_READ(SFUSE_STRAP);
15423
15424                 if (found & SFUSE_STRAP_DDIB_DETECTED)
15425                         intel_ddi_init(dev_priv, PORT_B);
15426                 if (found & SFUSE_STRAP_DDIC_DETECTED)
15427                         intel_ddi_init(dev_priv, PORT_C);
15428                 if (found & SFUSE_STRAP_DDID_DETECTED)
15429                         intel_ddi_init(dev_priv, PORT_D);
15430                 if (found & SFUSE_STRAP_DDIF_DETECTED)
15431                         intel_ddi_init(dev_priv, PORT_F);
15432                 /*
15433                  * On SKL we don't have a way to detect DDI-E so we rely on VBT.
15434                  */
15435                 if (IS_GEN9_BC(dev_priv) &&
15436                     intel_bios_is_port_present(dev_priv, PORT_E))
15437                         intel_ddi_init(dev_priv, PORT_E);
15438
15439         } else if (HAS_PCH_SPLIT(dev_priv)) {
15440                 int found;
15441
15442                 /*
15443                  * intel_edp_init_connector() depends on this completing first,
15444                  * to prevent the registration of both eDP and LVDS and the
15445                  * incorrect sharing of the PPS.
15446                  */
15447                 intel_lvds_init(dev_priv);
15448                 intel_crt_init(dev_priv);
15449
15450                 dpd_is_edp = intel_dp_is_port_edp(dev_priv, PORT_D);
15451
15452                 if (ilk_has_edp_a(dev_priv))
15453                         intel_dp_init(dev_priv, DP_A, PORT_A);
15454
15455                 if (I915_READ(PCH_HDMIB) & SDVO_DETECTED) {
15456                         /* PCH SDVOB multiplex with HDMIB */
15457                         found = intel_sdvo_init(dev_priv, PCH_SDVOB, PORT_B);
15458                         if (!found)
15459                                 intel_hdmi_init(dev_priv, PCH_HDMIB, PORT_B);
15460                         if (!found && (I915_READ(PCH_DP_B) & DP_DETECTED))
15461                                 intel_dp_init(dev_priv, PCH_DP_B, PORT_B);
15462                 }
15463
15464                 if (I915_READ(PCH_HDMIC) & SDVO_DETECTED)
15465                         intel_hdmi_init(dev_priv, PCH_HDMIC, PORT_C);
15466
15467                 if (!dpd_is_edp && I915_READ(PCH_HDMID) & SDVO_DETECTED)
15468                         intel_hdmi_init(dev_priv, PCH_HDMID, PORT_D);
15469
15470                 if (I915_READ(PCH_DP_C) & DP_DETECTED)
15471                         intel_dp_init(dev_priv, PCH_DP_C, PORT_C);
15472
15473                 if (I915_READ(PCH_DP_D) & DP_DETECTED)
15474                         intel_dp_init(dev_priv, PCH_DP_D, PORT_D);
15475         } else if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv)) {
15476                 bool has_edp, has_port;
15477
15478                 if (IS_VALLEYVIEW(dev_priv) && dev_priv->vbt.int_crt_support)
15479                         intel_crt_init(dev_priv);
15480
15481                 /*
15482                  * The DP_DETECTED bit is the latched state of the DDC
15483                  * SDA pin at boot. However since eDP doesn't require DDC
15484                  * (no way to plug in a DP->HDMI dongle) the DDC pins for
15485                  * eDP ports may have been muxed to an alternate function.
15486                  * Thus we can't rely on the DP_DETECTED bit alone to detect
15487                  * eDP ports. Consult the VBT as well as DP_DETECTED to
15488                  * detect eDP ports.
15489                  *
15490                  * Sadly the straps seem to be missing sometimes even for HDMI
15491                  * ports (eg. on Voyo V3 - CHT x7-Z8700), so check both strap
15492                  * and VBT for the presence of the port. Additionally we can't
15493                  * trust the port type the VBT declares as we've seen at least
15494                  * HDMI ports that the VBT claim are DP or eDP.
15495                  */
15496                 has_edp = intel_dp_is_port_edp(dev_priv, PORT_B);
15497                 has_port = intel_bios_is_port_present(dev_priv, PORT_B);
15498                 if (I915_READ(VLV_DP_B) & DP_DETECTED || has_port)
15499                         has_edp &= intel_dp_init(dev_priv, VLV_DP_B, PORT_B);
15500                 if ((I915_READ(VLV_HDMIB) & SDVO_DETECTED || has_port) && !has_edp)
15501                         intel_hdmi_init(dev_priv, VLV_HDMIB, PORT_B);
15502
15503                 has_edp = intel_dp_is_port_edp(dev_priv, PORT_C);
15504                 has_port = intel_bios_is_port_present(dev_priv, PORT_C);
15505                 if (I915_READ(VLV_DP_C) & DP_DETECTED || has_port)
15506                         has_edp &= intel_dp_init(dev_priv, VLV_DP_C, PORT_C);
15507                 if ((I915_READ(VLV_HDMIC) & SDVO_DETECTED || has_port) && !has_edp)
15508                         intel_hdmi_init(dev_priv, VLV_HDMIC, PORT_C);
15509
15510                 if (IS_CHERRYVIEW(dev_priv)) {
15511                         /*
15512                          * eDP not supported on port D,
15513                          * so no need to worry about it
15514                          */
15515                         has_port = intel_bios_is_port_present(dev_priv, PORT_D);
15516                         if (I915_READ(CHV_DP_D) & DP_DETECTED || has_port)
15517                                 intel_dp_init(dev_priv, CHV_DP_D, PORT_D);
15518                         if (I915_READ(CHV_HDMID) & SDVO_DETECTED || has_port)
15519                                 intel_hdmi_init(dev_priv, CHV_HDMID, PORT_D);
15520                 }
15521
15522                 vlv_dsi_init(dev_priv);
15523         } else if (IS_PINEVIEW(dev_priv)) {
15524                 intel_lvds_init(dev_priv);
15525                 intel_crt_init(dev_priv);
15526         } else if (IS_GEN_RANGE(dev_priv, 3, 4)) {
15527                 bool found = false;
15528
15529                 if (IS_MOBILE(dev_priv))
15530                         intel_lvds_init(dev_priv);
15531
15532                 intel_crt_init(dev_priv);
15533
15534                 if (I915_READ(GEN3_SDVOB) & SDVO_DETECTED) {
15535                         DRM_DEBUG_KMS("probing SDVOB\n");
15536                         found = intel_sdvo_init(dev_priv, GEN3_SDVOB, PORT_B);
15537                         if (!found && IS_G4X(dev_priv)) {
15538                                 DRM_DEBUG_KMS("probing HDMI on SDVOB\n");
15539                                 intel_hdmi_init(dev_priv, GEN4_HDMIB, PORT_B);
15540                         }
15541
15542                         if (!found && IS_G4X(dev_priv))
15543                                 intel_dp_init(dev_priv, DP_B, PORT_B);
15544                 }
15545
15546                 /* Before G4X SDVOC doesn't have its own detect register */
15547
15548                 if (I915_READ(GEN3_SDVOB) & SDVO_DETECTED) {
15549                         DRM_DEBUG_KMS("probing SDVOC\n");
15550                         found = intel_sdvo_init(dev_priv, GEN3_SDVOC, PORT_C);
15551                 }
15552
15553                 if (!found && (I915_READ(GEN3_SDVOC) & SDVO_DETECTED)) {
15554
15555                         if (IS_G4X(dev_priv)) {
15556                                 DRM_DEBUG_KMS("probing HDMI on SDVOC\n");
15557                                 intel_hdmi_init(dev_priv, GEN4_HDMIC, PORT_C);
15558                         }
15559                         if (IS_G4X(dev_priv))
15560                                 intel_dp_init(dev_priv, DP_C, PORT_C);
15561                 }
15562
15563                 if (IS_G4X(dev_priv) && (I915_READ(DP_D) & DP_DETECTED))
15564                         intel_dp_init(dev_priv, DP_D, PORT_D);
15565
15566                 if (SUPPORTS_TV(dev_priv))
15567                         intel_tv_init(dev_priv);
15568         } else if (IS_GEN(dev_priv, 2)) {
15569                 if (IS_I85X(dev_priv))
15570                         intel_lvds_init(dev_priv);
15571
15572                 intel_crt_init(dev_priv);
15573                 intel_dvo_init(dev_priv);
15574         }
15575
15576         intel_psr_init(dev_priv);
15577
15578         for_each_intel_encoder(&dev_priv->drm, encoder) {
15579                 encoder->base.possible_crtcs = encoder->crtc_mask;
15580                 encoder->base.possible_clones =
15581                         intel_encoder_clones(encoder);
15582         }
15583
15584         intel_init_pch_refclk(dev_priv);
15585
15586         drm_helper_move_panel_connectors_to_head(&dev_priv->drm);
15587 }
15588
15589 static void intel_user_framebuffer_destroy(struct drm_framebuffer *fb)
15590 {
15591         struct intel_framebuffer *intel_fb = to_intel_framebuffer(fb);
15592
15593         drm_framebuffer_cleanup(fb);
15594         intel_frontbuffer_put(intel_fb->frontbuffer);
15595
15596         kfree(intel_fb);
15597 }
15598
15599 static int intel_user_framebuffer_create_handle(struct drm_framebuffer *fb,
15600                                                 struct drm_file *file,
15601                                                 unsigned int *handle)
15602 {
15603         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
15604
15605         if (obj->userptr.mm) {
15606                 DRM_DEBUG("attempting to use a userptr for a framebuffer, denied\n");
15607                 return -EINVAL;
15608         }
15609
15610         return drm_gem_handle_create(file, &obj->base, handle);
15611 }
15612
15613 static int intel_user_framebuffer_dirty(struct drm_framebuffer *fb,
15614                                         struct drm_file *file,
15615                                         unsigned flags, unsigned color,
15616                                         struct drm_clip_rect *clips,
15617                                         unsigned num_clips)
15618 {
15619         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
15620
15621         i915_gem_object_flush_if_display(obj);
15622         intel_frontbuffer_flush(to_intel_frontbuffer(fb), ORIGIN_DIRTYFB);
15623
15624         return 0;
15625 }
15626
15627 static const struct drm_framebuffer_funcs intel_fb_funcs = {
15628         .destroy = intel_user_framebuffer_destroy,
15629         .create_handle = intel_user_framebuffer_create_handle,
15630         .dirty = intel_user_framebuffer_dirty,
15631 };
15632
15633 static int intel_framebuffer_init(struct intel_framebuffer *intel_fb,
15634                                   struct drm_i915_gem_object *obj,
15635                                   struct drm_mode_fb_cmd2 *mode_cmd)
15636 {
15637         struct drm_i915_private *dev_priv = to_i915(obj->base.dev);
15638         struct drm_framebuffer *fb = &intel_fb->base;
15639         u32 max_stride;
15640         unsigned int tiling, stride;
15641         int ret = -EINVAL;
15642         int i;
15643
15644         intel_fb->frontbuffer = intel_frontbuffer_get(obj);
15645         if (!intel_fb->frontbuffer)
15646                 return -ENOMEM;
15647
15648         i915_gem_object_lock(obj);
15649         tiling = i915_gem_object_get_tiling(obj);
15650         stride = i915_gem_object_get_stride(obj);
15651         i915_gem_object_unlock(obj);
15652
15653         if (mode_cmd->flags & DRM_MODE_FB_MODIFIERS) {
15654                 /*
15655                  * If there's a fence, enforce that
15656                  * the fb modifier and tiling mode match.
15657                  */
15658                 if (tiling != I915_TILING_NONE &&
15659                     tiling != intel_fb_modifier_to_tiling(mode_cmd->modifier[0])) {
15660                         DRM_DEBUG_KMS("tiling_mode doesn't match fb modifier\n");
15661                         goto err;
15662                 }
15663         } else {
15664                 if (tiling == I915_TILING_X) {
15665                         mode_cmd->modifier[0] = I915_FORMAT_MOD_X_TILED;
15666                 } else if (tiling == I915_TILING_Y) {
15667                         DRM_DEBUG_KMS("No Y tiling for legacy addfb\n");
15668                         goto err;
15669                 }
15670         }
15671
15672         if (!drm_any_plane_has_format(&dev_priv->drm,
15673                                       mode_cmd->pixel_format,
15674                                       mode_cmd->modifier[0])) {
15675                 struct drm_format_name_buf format_name;
15676
15677                 DRM_DEBUG_KMS("unsupported pixel format %s / modifier 0x%llx\n",
15678                               drm_get_format_name(mode_cmd->pixel_format,
15679                                                   &format_name),
15680                               mode_cmd->modifier[0]);
15681                 goto err;
15682         }
15683
15684         /*
15685          * gen2/3 display engine uses the fence if present,
15686          * so the tiling mode must match the fb modifier exactly.
15687          */
15688         if (INTEL_GEN(dev_priv) < 4 &&
15689             tiling != intel_fb_modifier_to_tiling(mode_cmd->modifier[0])) {
15690                 DRM_DEBUG_KMS("tiling_mode must match fb modifier exactly on gen2/3\n");
15691                 goto err;
15692         }
15693
15694         max_stride = intel_fb_max_stride(dev_priv, mode_cmd->pixel_format,
15695                                          mode_cmd->modifier[0]);
15696         if (mode_cmd->pitches[0] > max_stride) {
15697                 DRM_DEBUG_KMS("%s pitch (%u) must be at most %d\n",
15698                               mode_cmd->modifier[0] != DRM_FORMAT_MOD_LINEAR ?
15699                               "tiled" : "linear",
15700                               mode_cmd->pitches[0], max_stride);
15701                 goto err;
15702         }
15703
15704         /*
15705          * If there's a fence, enforce that
15706          * the fb pitch and fence stride match.
15707          */
15708         if (tiling != I915_TILING_NONE && mode_cmd->pitches[0] != stride) {
15709                 DRM_DEBUG_KMS("pitch (%d) must match tiling stride (%d)\n",
15710                               mode_cmd->pitches[0], stride);
15711                 goto err;
15712         }
15713
15714         /* FIXME need to adjust LINOFF/TILEOFF accordingly. */
15715         if (mode_cmd->offsets[0] != 0)
15716                 goto err;
15717
15718         drm_helper_mode_fill_fb_struct(&dev_priv->drm, fb, mode_cmd);
15719
15720         for (i = 0; i < fb->format->num_planes; i++) {
15721                 u32 stride_alignment;
15722
15723                 if (mode_cmd->handles[i] != mode_cmd->handles[0]) {
15724                         DRM_DEBUG_KMS("bad plane %d handle\n", i);
15725                         goto err;
15726                 }
15727
15728                 stride_alignment = intel_fb_stride_alignment(fb, i);
15729
15730                 /*
15731                  * Display WA #0531: skl,bxt,kbl,glk
15732                  *
15733                  * Render decompression and plane width > 3840
15734                  * combined with horizontal panning requires the
15735                  * plane stride to be a multiple of 4. We'll just
15736                  * require the entire fb to accommodate that to avoid
15737                  * potential runtime errors at plane configuration time.
15738                  */
15739                 if (IS_GEN(dev_priv, 9) && i == 0 && fb->width > 3840 &&
15740                     is_ccs_modifier(fb->modifier))
15741                         stride_alignment *= 4;
15742
15743                 if (fb->pitches[i] & (stride_alignment - 1)) {
15744                         DRM_DEBUG_KMS("plane %d pitch (%d) must be at least %u byte aligned\n",
15745                                       i, fb->pitches[i], stride_alignment);
15746                         goto err;
15747                 }
15748
15749                 fb->obj[i] = &obj->base;
15750         }
15751
15752         ret = intel_fill_fb_info(dev_priv, fb);
15753         if (ret)
15754                 goto err;
15755
15756         ret = drm_framebuffer_init(&dev_priv->drm, fb, &intel_fb_funcs);
15757         if (ret) {
15758                 DRM_ERROR("framebuffer init failed %d\n", ret);
15759                 goto err;
15760         }
15761
15762         return 0;
15763
15764 err:
15765         intel_frontbuffer_put(intel_fb->frontbuffer);
15766         return ret;
15767 }
15768
15769 static struct drm_framebuffer *
15770 intel_user_framebuffer_create(struct drm_device *dev,
15771                               struct drm_file *filp,
15772                               const struct drm_mode_fb_cmd2 *user_mode_cmd)
15773 {
15774         struct drm_framebuffer *fb;
15775         struct drm_i915_gem_object *obj;
15776         struct drm_mode_fb_cmd2 mode_cmd = *user_mode_cmd;
15777
15778         obj = i915_gem_object_lookup(filp, mode_cmd.handles[0]);
15779         if (!obj)
15780                 return ERR_PTR(-ENOENT);
15781
15782         fb = intel_framebuffer_create(obj, &mode_cmd);
15783         i915_gem_object_put(obj);
15784
15785         return fb;
15786 }
15787
15788 static void intel_atomic_state_free(struct drm_atomic_state *state)
15789 {
15790         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
15791
15792         drm_atomic_state_default_release(state);
15793
15794         i915_sw_fence_fini(&intel_state->commit_ready);
15795
15796         kfree(state);
15797 }
15798
15799 static enum drm_mode_status
15800 intel_mode_valid(struct drm_device *dev,
15801                  const struct drm_display_mode *mode)
15802 {
15803         struct drm_i915_private *dev_priv = to_i915(dev);
15804         int hdisplay_max, htotal_max;
15805         int vdisplay_max, vtotal_max;
15806
15807         /*
15808          * Can't reject DBLSCAN here because Xorg ddxen can add piles
15809          * of DBLSCAN modes to the output's mode list when they detect
15810          * the scaling mode property on the connector. And they don't
15811          * ask the kernel to validate those modes in any way until
15812          * modeset time at which point the client gets a protocol error.
15813          * So in order to not upset those clients we silently ignore the
15814          * DBLSCAN flag on such connectors. For other connectors we will
15815          * reject modes with the DBLSCAN flag in encoder->compute_config().
15816          * And we always reject DBLSCAN modes in connector->mode_valid()
15817          * as we never want such modes on the connector's mode list.
15818          */
15819
15820         if (mode->vscan > 1)
15821                 return MODE_NO_VSCAN;
15822
15823         if (mode->flags & DRM_MODE_FLAG_HSKEW)
15824                 return MODE_H_ILLEGAL;
15825
15826         if (mode->flags & (DRM_MODE_FLAG_CSYNC |
15827                            DRM_MODE_FLAG_NCSYNC |
15828                            DRM_MODE_FLAG_PCSYNC))
15829                 return MODE_HSYNC;
15830
15831         if (mode->flags & (DRM_MODE_FLAG_BCAST |
15832                            DRM_MODE_FLAG_PIXMUX |
15833                            DRM_MODE_FLAG_CLKDIV2))
15834                 return MODE_BAD;
15835
15836         if (INTEL_GEN(dev_priv) >= 9 ||
15837             IS_BROADWELL(dev_priv) || IS_HASWELL(dev_priv)) {
15838                 hdisplay_max = 8192; /* FDI max 4096 handled elsewhere */
15839                 vdisplay_max = 4096;
15840                 htotal_max = 8192;
15841                 vtotal_max = 8192;
15842         } else if (INTEL_GEN(dev_priv) >= 3) {
15843                 hdisplay_max = 4096;
15844                 vdisplay_max = 4096;
15845                 htotal_max = 8192;
15846                 vtotal_max = 8192;
15847         } else {
15848                 hdisplay_max = 2048;
15849                 vdisplay_max = 2048;
15850                 htotal_max = 4096;
15851                 vtotal_max = 4096;
15852         }
15853
15854         if (mode->hdisplay > hdisplay_max ||
15855             mode->hsync_start > htotal_max ||
15856             mode->hsync_end > htotal_max ||
15857             mode->htotal > htotal_max)
15858                 return MODE_H_ILLEGAL;
15859
15860         if (mode->vdisplay > vdisplay_max ||
15861             mode->vsync_start > vtotal_max ||
15862             mode->vsync_end > vtotal_max ||
15863             mode->vtotal > vtotal_max)
15864                 return MODE_V_ILLEGAL;
15865
15866         return MODE_OK;
15867 }
15868
15869 static const struct drm_mode_config_funcs intel_mode_funcs = {
15870         .fb_create = intel_user_framebuffer_create,
15871         .get_format_info = intel_get_format_info,
15872         .output_poll_changed = intel_fbdev_output_poll_changed,
15873         .mode_valid = intel_mode_valid,
15874         .atomic_check = intel_atomic_check,
15875         .atomic_commit = intel_atomic_commit,
15876         .atomic_state_alloc = intel_atomic_state_alloc,
15877         .atomic_state_clear = intel_atomic_state_clear,
15878         .atomic_state_free = intel_atomic_state_free,
15879 };
15880
15881 /**
15882  * intel_init_display_hooks - initialize the display modesetting hooks
15883  * @dev_priv: device private
15884  */
15885 void intel_init_display_hooks(struct drm_i915_private *dev_priv)
15886 {
15887         intel_init_cdclk_hooks(dev_priv);
15888
15889         if (INTEL_GEN(dev_priv) >= 9) {
15890                 dev_priv->display.get_pipe_config = haswell_get_pipe_config;
15891                 dev_priv->display.get_initial_plane_config =
15892                         skylake_get_initial_plane_config;
15893                 dev_priv->display.crtc_compute_clock =
15894                         haswell_crtc_compute_clock;
15895                 dev_priv->display.crtc_enable = haswell_crtc_enable;
15896                 dev_priv->display.crtc_disable = haswell_crtc_disable;
15897         } else if (HAS_DDI(dev_priv)) {
15898                 dev_priv->display.get_pipe_config = haswell_get_pipe_config;
15899                 dev_priv->display.get_initial_plane_config =
15900                         i9xx_get_initial_plane_config;
15901                 dev_priv->display.crtc_compute_clock =
15902                         haswell_crtc_compute_clock;
15903                 dev_priv->display.crtc_enable = haswell_crtc_enable;
15904                 dev_priv->display.crtc_disable = haswell_crtc_disable;
15905         } else if (HAS_PCH_SPLIT(dev_priv)) {
15906                 dev_priv->display.get_pipe_config = ironlake_get_pipe_config;
15907                 dev_priv->display.get_initial_plane_config =
15908                         i9xx_get_initial_plane_config;
15909                 dev_priv->display.crtc_compute_clock =
15910                         ironlake_crtc_compute_clock;
15911                 dev_priv->display.crtc_enable = ironlake_crtc_enable;
15912                 dev_priv->display.crtc_disable = ironlake_crtc_disable;
15913         } else if (IS_CHERRYVIEW(dev_priv)) {
15914                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
15915                 dev_priv->display.get_initial_plane_config =
15916                         i9xx_get_initial_plane_config;
15917                 dev_priv->display.crtc_compute_clock = chv_crtc_compute_clock;
15918                 dev_priv->display.crtc_enable = valleyview_crtc_enable;
15919                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
15920         } else if (IS_VALLEYVIEW(dev_priv)) {
15921                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
15922                 dev_priv->display.get_initial_plane_config =
15923                         i9xx_get_initial_plane_config;
15924                 dev_priv->display.crtc_compute_clock = vlv_crtc_compute_clock;
15925                 dev_priv->display.crtc_enable = valleyview_crtc_enable;
15926                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
15927         } else if (IS_G4X(dev_priv)) {
15928                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
15929                 dev_priv->display.get_initial_plane_config =
15930                         i9xx_get_initial_plane_config;
15931                 dev_priv->display.crtc_compute_clock = g4x_crtc_compute_clock;
15932                 dev_priv->display.crtc_enable = i9xx_crtc_enable;
15933                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
15934         } else if (IS_PINEVIEW(dev_priv)) {
15935                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
15936                 dev_priv->display.get_initial_plane_config =
15937                         i9xx_get_initial_plane_config;
15938                 dev_priv->display.crtc_compute_clock = pnv_crtc_compute_clock;
15939                 dev_priv->display.crtc_enable = i9xx_crtc_enable;
15940                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
15941         } else if (!IS_GEN(dev_priv, 2)) {
15942                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
15943                 dev_priv->display.get_initial_plane_config =
15944                         i9xx_get_initial_plane_config;
15945                 dev_priv->display.crtc_compute_clock = i9xx_crtc_compute_clock;
15946                 dev_priv->display.crtc_enable = i9xx_crtc_enable;
15947                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
15948         } else {
15949                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
15950                 dev_priv->display.get_initial_plane_config =
15951                         i9xx_get_initial_plane_config;
15952                 dev_priv->display.crtc_compute_clock = i8xx_crtc_compute_clock;
15953                 dev_priv->display.crtc_enable = i9xx_crtc_enable;
15954                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
15955         }
15956
15957         if (IS_GEN(dev_priv, 5)) {
15958                 dev_priv->display.fdi_link_train = ironlake_fdi_link_train;
15959         } else if (IS_GEN(dev_priv, 6)) {
15960                 dev_priv->display.fdi_link_train = gen6_fdi_link_train;
15961         } else if (IS_IVYBRIDGE(dev_priv)) {
15962                 /* FIXME: detect B0+ stepping and use auto training */
15963                 dev_priv->display.fdi_link_train = ivb_manual_fdi_link_train;
15964         } else if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv)) {
15965                 dev_priv->display.fdi_link_train = hsw_fdi_link_train;
15966         }
15967
15968         if (INTEL_GEN(dev_priv) >= 9)
15969                 dev_priv->display.commit_modeset_enables = skl_commit_modeset_enables;
15970         else
15971                 dev_priv->display.commit_modeset_enables = intel_commit_modeset_enables;
15972
15973 }
15974
15975 static i915_reg_t i915_vgacntrl_reg(struct drm_i915_private *dev_priv)
15976 {
15977         if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
15978                 return VLV_VGACNTRL;
15979         else if (INTEL_GEN(dev_priv) >= 5)
15980                 return CPU_VGACNTRL;
15981         else
15982                 return VGACNTRL;
15983 }
15984
15985 /* Disable the VGA plane that we never use */
15986 static void i915_disable_vga(struct drm_i915_private *dev_priv)
15987 {
15988         struct pci_dev *pdev = dev_priv->drm.pdev;
15989         u8 sr1;
15990         i915_reg_t vga_reg = i915_vgacntrl_reg(dev_priv);
15991
15992         /* WaEnableVGAAccessThroughIOPort:ctg,elk,ilk,snb,ivb,vlv,hsw */
15993         vga_get_uninterruptible(pdev, VGA_RSRC_LEGACY_IO);
15994         outb(SR01, VGA_SR_INDEX);
15995         sr1 = inb(VGA_SR_DATA);
15996         outb(sr1 | 1<<5, VGA_SR_DATA);
15997         vga_put(pdev, VGA_RSRC_LEGACY_IO);
15998         udelay(300);
15999
16000         I915_WRITE(vga_reg, VGA_DISP_DISABLE);
16001         POSTING_READ(vga_reg);
16002 }
16003
16004 void intel_modeset_init_hw(struct drm_device *dev)
16005 {
16006         struct drm_i915_private *dev_priv = to_i915(dev);
16007
16008         intel_update_cdclk(dev_priv);
16009         intel_dump_cdclk_state(&dev_priv->cdclk.hw, "Current CDCLK");
16010         dev_priv->cdclk.logical = dev_priv->cdclk.actual = dev_priv->cdclk.hw;
16011 }
16012
16013 /*
16014  * Calculate what we think the watermarks should be for the state we've read
16015  * out of the hardware and then immediately program those watermarks so that
16016  * we ensure the hardware settings match our internal state.
16017  *
16018  * We can calculate what we think WM's should be by creating a duplicate of the
16019  * current state (which was constructed during hardware readout) and running it
16020  * through the atomic check code to calculate new watermark values in the
16021  * state object.
16022  */
16023 static void sanitize_watermarks(struct drm_device *dev)
16024 {
16025         struct drm_i915_private *dev_priv = to_i915(dev);
16026         struct drm_atomic_state *state;
16027         struct intel_atomic_state *intel_state;
16028         struct intel_crtc *crtc;
16029         struct intel_crtc_state *crtc_state;
16030         struct drm_modeset_acquire_ctx ctx;
16031         int ret;
16032         int i;
16033
16034         /* Only supported on platforms that use atomic watermark design */
16035         if (!dev_priv->display.optimize_watermarks)
16036                 return;
16037
16038         /*
16039          * We need to hold connection_mutex before calling duplicate_state so
16040          * that the connector loop is protected.
16041          */
16042         drm_modeset_acquire_init(&ctx, 0);
16043 retry:
16044         ret = drm_modeset_lock_all_ctx(dev, &ctx);
16045         if (ret == -EDEADLK) {
16046                 drm_modeset_backoff(&ctx);
16047                 goto retry;
16048         } else if (WARN_ON(ret)) {
16049                 goto fail;
16050         }
16051
16052         state = drm_atomic_helper_duplicate_state(dev, &ctx);
16053         if (WARN_ON(IS_ERR(state)))
16054                 goto fail;
16055
16056         intel_state = to_intel_atomic_state(state);
16057
16058         /*
16059          * Hardware readout is the only time we don't want to calculate
16060          * intermediate watermarks (since we don't trust the current
16061          * watermarks).
16062          */
16063         if (!HAS_GMCH(dev_priv))
16064                 intel_state->skip_intermediate_wm = true;
16065
16066         ret = intel_atomic_check(dev, state);
16067         if (ret) {
16068                 /*
16069                  * If we fail here, it means that the hardware appears to be
16070                  * programmed in a way that shouldn't be possible, given our
16071                  * understanding of watermark requirements.  This might mean a
16072                  * mistake in the hardware readout code or a mistake in the
16073                  * watermark calculations for a given platform.  Raise a WARN
16074                  * so that this is noticeable.
16075                  *
16076                  * If this actually happens, we'll have to just leave the
16077                  * BIOS-programmed watermarks untouched and hope for the best.
16078                  */
16079                 WARN(true, "Could not determine valid watermarks for inherited state\n");
16080                 goto put_state;
16081         }
16082
16083         /* Write calculated watermark values back */
16084         for_each_new_intel_crtc_in_state(intel_state, crtc, crtc_state, i) {
16085                 crtc_state->wm.need_postvbl_update = true;
16086                 dev_priv->display.optimize_watermarks(intel_state, crtc_state);
16087
16088                 to_intel_crtc_state(crtc->base.state)->wm = crtc_state->wm;
16089         }
16090
16091 put_state:
16092         drm_atomic_state_put(state);
16093 fail:
16094         drm_modeset_drop_locks(&ctx);
16095         drm_modeset_acquire_fini(&ctx);
16096 }
16097
16098 static void intel_update_fdi_pll_freq(struct drm_i915_private *dev_priv)
16099 {
16100         if (IS_GEN(dev_priv, 5)) {
16101                 u32 fdi_pll_clk =
16102                         I915_READ(FDI_PLL_BIOS_0) & FDI_PLL_FB_CLOCK_MASK;
16103
16104                 dev_priv->fdi_pll_freq = (fdi_pll_clk + 2) * 10000;
16105         } else if (IS_GEN(dev_priv, 6) || IS_IVYBRIDGE(dev_priv)) {
16106                 dev_priv->fdi_pll_freq = 270000;
16107         } else {
16108                 return;
16109         }
16110
16111         DRM_DEBUG_DRIVER("FDI PLL freq=%d\n", dev_priv->fdi_pll_freq);
16112 }
16113
16114 static int intel_initial_commit(struct drm_device *dev)
16115 {
16116         struct drm_atomic_state *state = NULL;
16117         struct drm_modeset_acquire_ctx ctx;
16118         struct drm_crtc *crtc;
16119         struct drm_crtc_state *crtc_state;
16120         int ret = 0;
16121
16122         state = drm_atomic_state_alloc(dev);
16123         if (!state)
16124                 return -ENOMEM;
16125
16126         drm_modeset_acquire_init(&ctx, 0);
16127
16128 retry:
16129         state->acquire_ctx = &ctx;
16130
16131         drm_for_each_crtc(crtc, dev) {
16132                 crtc_state = drm_atomic_get_crtc_state(state, crtc);
16133                 if (IS_ERR(crtc_state)) {
16134                         ret = PTR_ERR(crtc_state);
16135                         goto out;
16136                 }
16137
16138                 if (crtc_state->active) {
16139                         ret = drm_atomic_add_affected_planes(state, crtc);
16140                         if (ret)
16141                                 goto out;
16142
16143                         /*
16144                          * FIXME hack to force a LUT update to avoid the
16145                          * plane update forcing the pipe gamma on without
16146                          * having a proper LUT loaded. Remove once we
16147                          * have readout for pipe gamma enable.
16148                          */
16149                         crtc_state->color_mgmt_changed = true;
16150                 }
16151         }
16152
16153         ret = drm_atomic_commit(state);
16154
16155 out:
16156         if (ret == -EDEADLK) {
16157                 drm_atomic_state_clear(state);
16158                 drm_modeset_backoff(&ctx);
16159                 goto retry;
16160         }
16161
16162         drm_atomic_state_put(state);
16163
16164         drm_modeset_drop_locks(&ctx);
16165         drm_modeset_acquire_fini(&ctx);
16166
16167         return ret;
16168 }
16169
16170 int intel_modeset_init(struct drm_device *dev)
16171 {
16172         struct drm_i915_private *dev_priv = to_i915(dev);
16173         enum pipe pipe;
16174         struct intel_crtc *crtc;
16175         int ret;
16176
16177         dev_priv->modeset_wq = alloc_ordered_workqueue("i915_modeset", 0);
16178
16179         drm_mode_config_init(dev);
16180
16181         ret = intel_bw_init(dev_priv);
16182         if (ret)
16183                 return ret;
16184
16185         dev->mode_config.min_width = 0;
16186         dev->mode_config.min_height = 0;
16187
16188         dev->mode_config.preferred_depth = 24;
16189         dev->mode_config.prefer_shadow = 1;
16190
16191         dev->mode_config.allow_fb_modifiers = true;
16192
16193         dev->mode_config.funcs = &intel_mode_funcs;
16194
16195         init_llist_head(&dev_priv->atomic_helper.free_list);
16196         INIT_WORK(&dev_priv->atomic_helper.free_work,
16197                   intel_atomic_helper_free_state_worker);
16198
16199         intel_init_quirks(dev_priv);
16200
16201         intel_fbc_init(dev_priv);
16202
16203         intel_init_pm(dev_priv);
16204
16205         /*
16206          * There may be no VBT; and if the BIOS enabled SSC we can
16207          * just keep using it to avoid unnecessary flicker.  Whereas if the
16208          * BIOS isn't using it, don't assume it will work even if the VBT
16209          * indicates as much.
16210          */
16211         if (HAS_PCH_IBX(dev_priv) || HAS_PCH_CPT(dev_priv)) {
16212                 bool bios_lvds_use_ssc = !!(I915_READ(PCH_DREF_CONTROL) &
16213                                             DREF_SSC1_ENABLE);
16214
16215                 if (dev_priv->vbt.lvds_use_ssc != bios_lvds_use_ssc) {
16216                         DRM_DEBUG_KMS("SSC %sabled by BIOS, overriding VBT which says %sabled\n",
16217                                      bios_lvds_use_ssc ? "en" : "dis",
16218                                      dev_priv->vbt.lvds_use_ssc ? "en" : "dis");
16219                         dev_priv->vbt.lvds_use_ssc = bios_lvds_use_ssc;
16220                 }
16221         }
16222
16223         /*
16224          * Maximum framebuffer dimensions, chosen to match
16225          * the maximum render engine surface size on gen4+.
16226          */
16227         if (INTEL_GEN(dev_priv) >= 7) {
16228                 dev->mode_config.max_width = 16384;
16229                 dev->mode_config.max_height = 16384;
16230         } else if (INTEL_GEN(dev_priv) >= 4) {
16231                 dev->mode_config.max_width = 8192;
16232                 dev->mode_config.max_height = 8192;
16233         } else if (IS_GEN(dev_priv, 3)) {
16234                 dev->mode_config.max_width = 4096;
16235                 dev->mode_config.max_height = 4096;
16236         } else {
16237                 dev->mode_config.max_width = 2048;
16238                 dev->mode_config.max_height = 2048;
16239         }
16240
16241         if (IS_I845G(dev_priv) || IS_I865G(dev_priv)) {
16242                 dev->mode_config.cursor_width = IS_I845G(dev_priv) ? 64 : 512;
16243                 dev->mode_config.cursor_height = 1023;
16244         } else if (IS_GEN(dev_priv, 2)) {
16245                 dev->mode_config.cursor_width = 64;
16246                 dev->mode_config.cursor_height = 64;
16247         } else {
16248                 dev->mode_config.cursor_width = 256;
16249                 dev->mode_config.cursor_height = 256;
16250         }
16251
16252         DRM_DEBUG_KMS("%d display pipe%s available.\n",
16253                       INTEL_INFO(dev_priv)->num_pipes,
16254                       INTEL_INFO(dev_priv)->num_pipes > 1 ? "s" : "");
16255
16256         for_each_pipe(dev_priv, pipe) {
16257                 ret = intel_crtc_init(dev_priv, pipe);
16258                 if (ret) {
16259                         drm_mode_config_cleanup(dev);
16260                         return ret;
16261                 }
16262         }
16263
16264         intel_shared_dpll_init(dev);
16265         intel_update_fdi_pll_freq(dev_priv);
16266
16267         intel_update_czclk(dev_priv);
16268         intel_modeset_init_hw(dev);
16269
16270         intel_hdcp_component_init(dev_priv);
16271
16272         if (dev_priv->max_cdclk_freq == 0)
16273                 intel_update_max_cdclk(dev_priv);
16274
16275         /* Just disable it once at startup */
16276         i915_disable_vga(dev_priv);
16277         intel_setup_outputs(dev_priv);
16278
16279         drm_modeset_lock_all(dev);
16280         intel_modeset_setup_hw_state(dev, dev->mode_config.acquire_ctx);
16281         drm_modeset_unlock_all(dev);
16282
16283         for_each_intel_crtc(dev, crtc) {
16284                 struct intel_initial_plane_config plane_config = {};
16285
16286                 if (!crtc->active)
16287                         continue;
16288
16289                 /*
16290                  * Note that reserving the BIOS fb up front prevents us
16291                  * from stuffing other stolen allocations like the ring
16292                  * on top.  This prevents some ugliness at boot time, and
16293                  * can even allow for smooth boot transitions if the BIOS
16294                  * fb is large enough for the active pipe configuration.
16295                  */
16296                 dev_priv->display.get_initial_plane_config(crtc,
16297                                                            &plane_config);
16298
16299                 /*
16300                  * If the fb is shared between multiple heads, we'll
16301                  * just get the first one.
16302                  */
16303                 intel_find_initial_plane_obj(crtc, &plane_config);
16304         }
16305
16306         /*
16307          * Make sure hardware watermarks really match the state we read out.
16308          * Note that we need to do this after reconstructing the BIOS fb's
16309          * since the watermark calculation done here will use pstate->fb.
16310          */
16311         if (!HAS_GMCH(dev_priv))
16312                 sanitize_watermarks(dev);
16313
16314         /*
16315          * Force all active planes to recompute their states. So that on
16316          * mode_setcrtc after probe, all the intel_plane_state variables
16317          * are already calculated and there is no assert_plane warnings
16318          * during bootup.
16319          */
16320         ret = intel_initial_commit(dev);
16321         if (ret)
16322                 DRM_DEBUG_KMS("Initial commit in probe failed.\n");
16323
16324         return 0;
16325 }
16326
16327 void i830_enable_pipe(struct drm_i915_private *dev_priv, enum pipe pipe)
16328 {
16329         struct intel_crtc *crtc = intel_get_crtc_for_pipe(dev_priv, pipe);
16330         /* 640x480@60Hz, ~25175 kHz */
16331         struct dpll clock = {
16332                 .m1 = 18,
16333                 .m2 = 7,
16334                 .p1 = 13,
16335                 .p2 = 4,
16336                 .n = 2,
16337         };
16338         u32 dpll, fp;
16339         int i;
16340
16341         WARN_ON(i9xx_calc_dpll_params(48000, &clock) != 25154);
16342
16343         DRM_DEBUG_KMS("enabling pipe %c due to force quirk (vco=%d dot=%d)\n",
16344                       pipe_name(pipe), clock.vco, clock.dot);
16345
16346         fp = i9xx_dpll_compute_fp(&clock);
16347         dpll = DPLL_DVO_2X_MODE |
16348                 DPLL_VGA_MODE_DIS |
16349                 ((clock.p1 - 2) << DPLL_FPA01_P1_POST_DIV_SHIFT) |
16350                 PLL_P2_DIVIDE_BY_4 |
16351                 PLL_REF_INPUT_DREFCLK |
16352                 DPLL_VCO_ENABLE;
16353
16354         I915_WRITE(FP0(pipe), fp);
16355         I915_WRITE(FP1(pipe), fp);
16356
16357         I915_WRITE(HTOTAL(pipe), (640 - 1) | ((800 - 1) << 16));
16358         I915_WRITE(HBLANK(pipe), (640 - 1) | ((800 - 1) << 16));
16359         I915_WRITE(HSYNC(pipe), (656 - 1) | ((752 - 1) << 16));
16360         I915_WRITE(VTOTAL(pipe), (480 - 1) | ((525 - 1) << 16));
16361         I915_WRITE(VBLANK(pipe), (480 - 1) | ((525 - 1) << 16));
16362         I915_WRITE(VSYNC(pipe), (490 - 1) | ((492 - 1) << 16));
16363         I915_WRITE(PIPESRC(pipe), ((640 - 1) << 16) | (480 - 1));
16364
16365         /*
16366          * Apparently we need to have VGA mode enabled prior to changing
16367          * the P1/P2 dividers. Otherwise the DPLL will keep using the old
16368          * dividers, even though the register value does change.
16369          */
16370         I915_WRITE(DPLL(pipe), dpll & ~DPLL_VGA_MODE_DIS);
16371         I915_WRITE(DPLL(pipe), dpll);
16372
16373         /* Wait for the clocks to stabilize. */
16374         POSTING_READ(DPLL(pipe));
16375         udelay(150);
16376
16377         /* The pixel multiplier can only be updated once the
16378          * DPLL is enabled and the clocks are stable.
16379          *
16380          * So write it again.
16381          */
16382         I915_WRITE(DPLL(pipe), dpll);
16383
16384         /* We do this three times for luck */
16385         for (i = 0; i < 3 ; i++) {
16386                 I915_WRITE(DPLL(pipe), dpll);
16387                 POSTING_READ(DPLL(pipe));
16388                 udelay(150); /* wait for warmup */
16389         }
16390
16391         I915_WRITE(PIPECONF(pipe), PIPECONF_ENABLE | PIPECONF_PROGRESSIVE);
16392         POSTING_READ(PIPECONF(pipe));
16393
16394         intel_wait_for_pipe_scanline_moving(crtc);
16395 }
16396
16397 void i830_disable_pipe(struct drm_i915_private *dev_priv, enum pipe pipe)
16398 {
16399         struct intel_crtc *crtc = intel_get_crtc_for_pipe(dev_priv, pipe);
16400
16401         DRM_DEBUG_KMS("disabling pipe %c due to force quirk\n",
16402                       pipe_name(pipe));
16403
16404         WARN_ON(I915_READ(DSPCNTR(PLANE_A)) & DISPLAY_PLANE_ENABLE);
16405         WARN_ON(I915_READ(DSPCNTR(PLANE_B)) & DISPLAY_PLANE_ENABLE);
16406         WARN_ON(I915_READ(DSPCNTR(PLANE_C)) & DISPLAY_PLANE_ENABLE);
16407         WARN_ON(I915_READ(CURCNTR(PIPE_A)) & MCURSOR_MODE);
16408         WARN_ON(I915_READ(CURCNTR(PIPE_B)) & MCURSOR_MODE);
16409
16410         I915_WRITE(PIPECONF(pipe), 0);
16411         POSTING_READ(PIPECONF(pipe));
16412
16413         intel_wait_for_pipe_scanline_stopped(crtc);
16414
16415         I915_WRITE(DPLL(pipe), DPLL_VGA_MODE_DIS);
16416         POSTING_READ(DPLL(pipe));
16417 }
16418
16419 static void
16420 intel_sanitize_plane_mapping(struct drm_i915_private *dev_priv)
16421 {
16422         struct intel_crtc *crtc;
16423
16424         if (INTEL_GEN(dev_priv) >= 4)
16425                 return;
16426
16427         for_each_intel_crtc(&dev_priv->drm, crtc) {
16428                 struct intel_plane *plane =
16429                         to_intel_plane(crtc->base.primary);
16430                 struct intel_crtc *plane_crtc;
16431                 enum pipe pipe;
16432
16433                 if (!plane->get_hw_state(plane, &pipe))
16434                         continue;
16435
16436                 if (pipe == crtc->pipe)
16437                         continue;
16438
16439                 DRM_DEBUG_KMS("[PLANE:%d:%s] attached to the wrong pipe, disabling plane\n",
16440                               plane->base.base.id, plane->base.name);
16441
16442                 plane_crtc = intel_get_crtc_for_pipe(dev_priv, pipe);
16443                 intel_plane_disable_noatomic(plane_crtc, plane);
16444         }
16445 }
16446
16447 static bool intel_crtc_has_encoders(struct intel_crtc *crtc)
16448 {
16449         struct drm_device *dev = crtc->base.dev;
16450         struct intel_encoder *encoder;
16451
16452         for_each_encoder_on_crtc(dev, &crtc->base, encoder)
16453                 return true;
16454
16455         return false;
16456 }
16457
16458 static struct intel_connector *intel_encoder_find_connector(struct intel_encoder *encoder)
16459 {
16460         struct drm_device *dev = encoder->base.dev;
16461         struct intel_connector *connector;
16462
16463         for_each_connector_on_encoder(dev, &encoder->base, connector)
16464                 return connector;
16465
16466         return NULL;
16467 }
16468
16469 static bool has_pch_trancoder(struct drm_i915_private *dev_priv,
16470                               enum pipe pch_transcoder)
16471 {
16472         return HAS_PCH_IBX(dev_priv) || HAS_PCH_CPT(dev_priv) ||
16473                 (HAS_PCH_LPT_H(dev_priv) && pch_transcoder == PIPE_A);
16474 }
16475
16476 static void intel_sanitize_crtc(struct intel_crtc *crtc,
16477                                 struct drm_modeset_acquire_ctx *ctx)
16478 {
16479         struct drm_device *dev = crtc->base.dev;
16480         struct drm_i915_private *dev_priv = to_i915(dev);
16481         struct intel_crtc_state *crtc_state = to_intel_crtc_state(crtc->base.state);
16482         enum transcoder cpu_transcoder = crtc_state->cpu_transcoder;
16483
16484         /* Clear any frame start delays used for debugging left by the BIOS */
16485         if (crtc->active && !transcoder_is_dsi(cpu_transcoder)) {
16486                 i915_reg_t reg = PIPECONF(cpu_transcoder);
16487
16488                 I915_WRITE(reg,
16489                            I915_READ(reg) & ~PIPECONF_FRAME_START_DELAY_MASK);
16490         }
16491
16492         if (crtc_state->base.active) {
16493                 struct intel_plane *plane;
16494
16495                 /* Disable everything but the primary plane */
16496                 for_each_intel_plane_on_crtc(dev, crtc, plane) {
16497                         const struct intel_plane_state *plane_state =
16498                                 to_intel_plane_state(plane->base.state);
16499
16500                         if (plane_state->base.visible &&
16501                             plane->base.type != DRM_PLANE_TYPE_PRIMARY)
16502                                 intel_plane_disable_noatomic(crtc, plane);
16503                 }
16504
16505                 /*
16506                  * Disable any background color set by the BIOS, but enable the
16507                  * gamma and CSC to match how we program our planes.
16508                  */
16509                 if (INTEL_GEN(dev_priv) >= 9)
16510                         I915_WRITE(SKL_BOTTOM_COLOR(crtc->pipe),
16511                                    SKL_BOTTOM_COLOR_GAMMA_ENABLE |
16512                                    SKL_BOTTOM_COLOR_CSC_ENABLE);
16513         }
16514
16515         /* Adjust the state of the output pipe according to whether we
16516          * have active connectors/encoders. */
16517         if (crtc_state->base.active && !intel_crtc_has_encoders(crtc))
16518                 intel_crtc_disable_noatomic(&crtc->base, ctx);
16519
16520         if (crtc_state->base.active || HAS_GMCH(dev_priv)) {
16521                 /*
16522                  * We start out with underrun reporting disabled to avoid races.
16523                  * For correct bookkeeping mark this on active crtcs.
16524                  *
16525                  * Also on gmch platforms we dont have any hardware bits to
16526                  * disable the underrun reporting. Which means we need to start
16527                  * out with underrun reporting disabled also on inactive pipes,
16528                  * since otherwise we'll complain about the garbage we read when
16529                  * e.g. coming up after runtime pm.
16530                  *
16531                  * No protection against concurrent access is required - at
16532                  * worst a fifo underrun happens which also sets this to false.
16533                  */
16534                 crtc->cpu_fifo_underrun_disabled = true;
16535                 /*
16536                  * We track the PCH trancoder underrun reporting state
16537                  * within the crtc. With crtc for pipe A housing the underrun
16538                  * reporting state for PCH transcoder A, crtc for pipe B housing
16539                  * it for PCH transcoder B, etc. LPT-H has only PCH transcoder A,
16540                  * and marking underrun reporting as disabled for the non-existing
16541                  * PCH transcoders B and C would prevent enabling the south
16542                  * error interrupt (see cpt_can_enable_serr_int()).
16543                  */
16544                 if (has_pch_trancoder(dev_priv, crtc->pipe))
16545                         crtc->pch_fifo_underrun_disabled = true;
16546         }
16547 }
16548
16549 static bool has_bogus_dpll_config(const struct intel_crtc_state *crtc_state)
16550 {
16551         struct drm_i915_private *dev_priv = to_i915(crtc_state->base.crtc->dev);
16552
16553         /*
16554          * Some SNB BIOSen (eg. ASUS K53SV) are known to misprogram
16555          * the hardware when a high res displays plugged in. DPLL P
16556          * divider is zero, and the pipe timings are bonkers. We'll
16557          * try to disable everything in that case.
16558          *
16559          * FIXME would be nice to be able to sanitize this state
16560          * without several WARNs, but for now let's take the easy
16561          * road.
16562          */
16563         return IS_GEN(dev_priv, 6) &&
16564                 crtc_state->base.active &&
16565                 crtc_state->shared_dpll &&
16566                 crtc_state->port_clock == 0;
16567 }
16568
16569 static void intel_sanitize_encoder(struct intel_encoder *encoder)
16570 {
16571         struct drm_i915_private *dev_priv = to_i915(encoder->base.dev);
16572         struct intel_connector *connector;
16573         struct intel_crtc *crtc = to_intel_crtc(encoder->base.crtc);
16574         struct intel_crtc_state *crtc_state = crtc ?
16575                 to_intel_crtc_state(crtc->base.state) : NULL;
16576
16577         /* We need to check both for a crtc link (meaning that the
16578          * encoder is active and trying to read from a pipe) and the
16579          * pipe itself being active. */
16580         bool has_active_crtc = crtc_state &&
16581                 crtc_state->base.active;
16582
16583         if (crtc_state && has_bogus_dpll_config(crtc_state)) {
16584                 DRM_DEBUG_KMS("BIOS has misprogrammed the hardware. Disabling pipe %c\n",
16585                               pipe_name(crtc->pipe));
16586                 has_active_crtc = false;
16587         }
16588
16589         connector = intel_encoder_find_connector(encoder);
16590         if (connector && !has_active_crtc) {
16591                 DRM_DEBUG_KMS("[ENCODER:%d:%s] has active connectors but no active pipe!\n",
16592                               encoder->base.base.id,
16593                               encoder->base.name);
16594
16595                 /* Connector is active, but has no active pipe. This is
16596                  * fallout from our resume register restoring. Disable
16597                  * the encoder manually again. */
16598                 if (crtc_state) {
16599                         struct drm_encoder *best_encoder;
16600
16601                         DRM_DEBUG_KMS("[ENCODER:%d:%s] manually disabled\n",
16602                                       encoder->base.base.id,
16603                                       encoder->base.name);
16604
16605                         /* avoid oopsing in case the hooks consult best_encoder */
16606                         best_encoder = connector->base.state->best_encoder;
16607                         connector->base.state->best_encoder = &encoder->base;
16608
16609                         if (encoder->disable)
16610                                 encoder->disable(encoder, crtc_state,
16611                                                  connector->base.state);
16612                         if (encoder->post_disable)
16613                                 encoder->post_disable(encoder, crtc_state,
16614                                                       connector->base.state);
16615
16616                         connector->base.state->best_encoder = best_encoder;
16617                 }
16618                 encoder->base.crtc = NULL;
16619
16620                 /* Inconsistent output/port/pipe state happens presumably due to
16621                  * a bug in one of the get_hw_state functions. Or someplace else
16622                  * in our code, like the register restore mess on resume. Clamp
16623                  * things to off as a safer default. */
16624
16625                 connector->base.dpms = DRM_MODE_DPMS_OFF;
16626                 connector->base.encoder = NULL;
16627         }
16628
16629         /* notify opregion of the sanitized encoder state */
16630         intel_opregion_notify_encoder(encoder, connector && has_active_crtc);
16631
16632         if (INTEL_GEN(dev_priv) >= 11)
16633                 icl_sanitize_encoder_pll_mapping(encoder);
16634 }
16635
16636 void i915_redisable_vga_power_on(struct drm_i915_private *dev_priv)
16637 {
16638         i915_reg_t vga_reg = i915_vgacntrl_reg(dev_priv);
16639
16640         if (!(I915_READ(vga_reg) & VGA_DISP_DISABLE)) {
16641                 DRM_DEBUG_KMS("Something enabled VGA plane, disabling it\n");
16642                 i915_disable_vga(dev_priv);
16643         }
16644 }
16645
16646 void i915_redisable_vga(struct drm_i915_private *dev_priv)
16647 {
16648         intel_wakeref_t wakeref;
16649
16650         /*
16651          * This function can be called both from intel_modeset_setup_hw_state or
16652          * at a very early point in our resume sequence, where the power well
16653          * structures are not yet restored. Since this function is at a very
16654          * paranoid "someone might have enabled VGA while we were not looking"
16655          * level, just check if the power well is enabled instead of trying to
16656          * follow the "don't touch the power well if we don't need it" policy
16657          * the rest of the driver uses.
16658          */
16659         wakeref = intel_display_power_get_if_enabled(dev_priv,
16660                                                      POWER_DOMAIN_VGA);
16661         if (!wakeref)
16662                 return;
16663
16664         i915_redisable_vga_power_on(dev_priv);
16665
16666         intel_display_power_put(dev_priv, POWER_DOMAIN_VGA, wakeref);
16667 }
16668
16669 /* FIXME read out full plane state for all planes */
16670 static void readout_plane_state(struct drm_i915_private *dev_priv)
16671 {
16672         struct intel_plane *plane;
16673         struct intel_crtc *crtc;
16674
16675         for_each_intel_plane(&dev_priv->drm, plane) {
16676                 struct intel_plane_state *plane_state =
16677                         to_intel_plane_state(plane->base.state);
16678                 struct intel_crtc_state *crtc_state;
16679                 enum pipe pipe = PIPE_A;
16680                 bool visible;
16681
16682                 visible = plane->get_hw_state(plane, &pipe);
16683
16684                 crtc = intel_get_crtc_for_pipe(dev_priv, pipe);
16685                 crtc_state = to_intel_crtc_state(crtc->base.state);
16686
16687                 intel_set_plane_visible(crtc_state, plane_state, visible);
16688
16689                 DRM_DEBUG_KMS("[PLANE:%d:%s] hw state readout: %s, pipe %c\n",
16690                               plane->base.base.id, plane->base.name,
16691                               enableddisabled(visible), pipe_name(pipe));
16692         }
16693
16694         for_each_intel_crtc(&dev_priv->drm, crtc) {
16695                 struct intel_crtc_state *crtc_state =
16696                         to_intel_crtc_state(crtc->base.state);
16697
16698                 fixup_active_planes(crtc_state);
16699         }
16700 }
16701
16702 static void intel_modeset_readout_hw_state(struct drm_device *dev)
16703 {
16704         struct drm_i915_private *dev_priv = to_i915(dev);
16705         enum pipe pipe;
16706         struct intel_crtc *crtc;
16707         struct intel_encoder *encoder;
16708         struct intel_connector *connector;
16709         struct drm_connector_list_iter conn_iter;
16710         int i;
16711
16712         dev_priv->active_pipes = 0;
16713
16714         for_each_intel_crtc(dev, crtc) {
16715                 struct intel_crtc_state *crtc_state =
16716                         to_intel_crtc_state(crtc->base.state);
16717
16718                 __drm_atomic_helper_crtc_destroy_state(&crtc_state->base);
16719                 memset(crtc_state, 0, sizeof(*crtc_state));
16720                 __drm_atomic_helper_crtc_reset(&crtc->base, &crtc_state->base);
16721
16722                 crtc_state->base.active = crtc_state->base.enable =
16723                         dev_priv->display.get_pipe_config(crtc, crtc_state);
16724
16725                 crtc->base.enabled = crtc_state->base.enable;
16726                 crtc->active = crtc_state->base.active;
16727
16728                 if (crtc_state->base.active)
16729                         dev_priv->active_pipes |= BIT(crtc->pipe);
16730
16731                 DRM_DEBUG_KMS("[CRTC:%d:%s] hw state readout: %s\n",
16732                               crtc->base.base.id, crtc->base.name,
16733                               enableddisabled(crtc_state->base.active));
16734         }
16735
16736         readout_plane_state(dev_priv);
16737
16738         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
16739                 struct intel_shared_dpll *pll = &dev_priv->shared_dplls[i];
16740
16741                 pll->on = pll->info->funcs->get_hw_state(dev_priv, pll,
16742                                                         &pll->state.hw_state);
16743
16744                 if (IS_ELKHARTLAKE(dev_priv) && pll->on &&
16745                     pll->info->id == DPLL_ID_EHL_DPLL4) {
16746                         pll->wakeref = intel_display_power_get(dev_priv,
16747                                                                POWER_DOMAIN_DPLL_DC_OFF);
16748                 }
16749
16750                 pll->state.crtc_mask = 0;
16751                 for_each_intel_crtc(dev, crtc) {
16752                         struct intel_crtc_state *crtc_state =
16753                                 to_intel_crtc_state(crtc->base.state);
16754
16755                         if (crtc_state->base.active &&
16756                             crtc_state->shared_dpll == pll)
16757                                 pll->state.crtc_mask |= 1 << crtc->pipe;
16758                 }
16759                 pll->active_mask = pll->state.crtc_mask;
16760
16761                 DRM_DEBUG_KMS("%s hw state readout: crtc_mask 0x%08x, on %i\n",
16762                               pll->info->name, pll->state.crtc_mask, pll->on);
16763         }
16764
16765         for_each_intel_encoder(dev, encoder) {
16766                 pipe = 0;
16767
16768                 if (encoder->get_hw_state(encoder, &pipe)) {
16769                         struct intel_crtc_state *crtc_state;
16770
16771                         crtc = intel_get_crtc_for_pipe(dev_priv, pipe);
16772                         crtc_state = to_intel_crtc_state(crtc->base.state);
16773
16774                         encoder->base.crtc = &crtc->base;
16775                         encoder->get_config(encoder, crtc_state);
16776                 } else {
16777                         encoder->base.crtc = NULL;
16778                 }
16779
16780                 DRM_DEBUG_KMS("[ENCODER:%d:%s] hw state readout: %s, pipe %c\n",
16781                               encoder->base.base.id, encoder->base.name,
16782                               enableddisabled(encoder->base.crtc),
16783                               pipe_name(pipe));
16784         }
16785
16786         drm_connector_list_iter_begin(dev, &conn_iter);
16787         for_each_intel_connector_iter(connector, &conn_iter) {
16788                 if (connector->get_hw_state(connector)) {
16789                         connector->base.dpms = DRM_MODE_DPMS_ON;
16790
16791                         encoder = connector->encoder;
16792                         connector->base.encoder = &encoder->base;
16793
16794                         if (encoder->base.crtc &&
16795                             encoder->base.crtc->state->active) {
16796                                 /*
16797                                  * This has to be done during hardware readout
16798                                  * because anything calling .crtc_disable may
16799                                  * rely on the connector_mask being accurate.
16800                                  */
16801                                 encoder->base.crtc->state->connector_mask |=
16802                                         drm_connector_mask(&connector->base);
16803                                 encoder->base.crtc->state->encoder_mask |=
16804                                         drm_encoder_mask(&encoder->base);
16805                         }
16806
16807                 } else {
16808                         connector->base.dpms = DRM_MODE_DPMS_OFF;
16809                         connector->base.encoder = NULL;
16810                 }
16811                 DRM_DEBUG_KMS("[CONNECTOR:%d:%s] hw state readout: %s\n",
16812                               connector->base.base.id, connector->base.name,
16813                               enableddisabled(connector->base.encoder));
16814         }
16815         drm_connector_list_iter_end(&conn_iter);
16816
16817         for_each_intel_crtc(dev, crtc) {
16818                 struct intel_bw_state *bw_state =
16819                         to_intel_bw_state(dev_priv->bw_obj.state);
16820                 struct intel_crtc_state *crtc_state =
16821                         to_intel_crtc_state(crtc->base.state);
16822                 struct intel_plane *plane;
16823                 int min_cdclk = 0;
16824
16825                 memset(&crtc->base.mode, 0, sizeof(crtc->base.mode));
16826                 if (crtc_state->base.active) {
16827                         intel_mode_from_pipe_config(&crtc->base.mode, crtc_state);
16828                         crtc->base.mode.hdisplay = crtc_state->pipe_src_w;
16829                         crtc->base.mode.vdisplay = crtc_state->pipe_src_h;
16830                         intel_mode_from_pipe_config(&crtc_state->base.adjusted_mode, crtc_state);
16831                         WARN_ON(drm_atomic_set_mode_for_crtc(crtc->base.state, &crtc->base.mode));
16832
16833                         /*
16834                          * The initial mode needs to be set in order to keep
16835                          * the atomic core happy. It wants a valid mode if the
16836                          * crtc's enabled, so we do the above call.
16837                          *
16838                          * But we don't set all the derived state fully, hence
16839                          * set a flag to indicate that a full recalculation is
16840                          * needed on the next commit.
16841                          */
16842                         crtc_state->base.mode.private_flags = I915_MODE_FLAG_INHERITED;
16843
16844                         intel_crtc_compute_pixel_rate(crtc_state);
16845
16846                         if (dev_priv->display.modeset_calc_cdclk) {
16847                                 min_cdclk = intel_crtc_compute_min_cdclk(crtc_state);
16848                                 if (WARN_ON(min_cdclk < 0))
16849                                         min_cdclk = 0;
16850                         }
16851
16852                         drm_calc_timestamping_constants(&crtc->base,
16853                                                         &crtc_state->base.adjusted_mode);
16854                         update_scanline_offset(crtc_state);
16855                 }
16856
16857                 dev_priv->min_cdclk[crtc->pipe] = min_cdclk;
16858                 dev_priv->min_voltage_level[crtc->pipe] =
16859                         crtc_state->min_voltage_level;
16860
16861                 for_each_intel_plane_on_crtc(&dev_priv->drm, crtc, plane) {
16862                         const struct intel_plane_state *plane_state =
16863                                 to_intel_plane_state(plane->base.state);
16864
16865                         /*
16866                          * FIXME don't have the fb yet, so can't
16867                          * use intel_plane_data_rate() :(
16868                          */
16869                         if (plane_state->base.visible)
16870                                 crtc_state->data_rate[plane->id] =
16871                                         4 * crtc_state->pixel_rate;
16872                 }
16873
16874                 intel_bw_crtc_update(bw_state, crtc_state);
16875
16876                 intel_pipe_config_sanity_check(dev_priv, crtc_state);
16877         }
16878 }
16879
16880 static void
16881 get_encoder_power_domains(struct drm_i915_private *dev_priv)
16882 {
16883         struct intel_encoder *encoder;
16884
16885         for_each_intel_encoder(&dev_priv->drm, encoder) {
16886                 struct intel_crtc_state *crtc_state;
16887
16888                 if (!encoder->get_power_domains)
16889                         continue;
16890
16891                 /*
16892                  * MST-primary and inactive encoders don't have a crtc state
16893                  * and neither of these require any power domain references.
16894                  */
16895                 if (!encoder->base.crtc)
16896                         continue;
16897
16898                 crtc_state = to_intel_crtc_state(encoder->base.crtc->state);
16899                 encoder->get_power_domains(encoder, crtc_state);
16900         }
16901 }
16902
16903 static void intel_early_display_was(struct drm_i915_private *dev_priv)
16904 {
16905         /* Display WA #1185 WaDisableDARBFClkGating:cnl,glk */
16906         if (IS_CANNONLAKE(dev_priv) || IS_GEMINILAKE(dev_priv))
16907                 I915_WRITE(GEN9_CLKGATE_DIS_0, I915_READ(GEN9_CLKGATE_DIS_0) |
16908                            DARBF_GATING_DIS);
16909
16910         if (IS_HASWELL(dev_priv)) {
16911                 /*
16912                  * WaRsPkgCStateDisplayPMReq:hsw
16913                  * System hang if this isn't done before disabling all planes!
16914                  */
16915                 I915_WRITE(CHICKEN_PAR1_1,
16916                            I915_READ(CHICKEN_PAR1_1) | FORCE_ARB_IDLE_PLANES);
16917         }
16918 }
16919
16920 static void ibx_sanitize_pch_hdmi_port(struct drm_i915_private *dev_priv,
16921                                        enum port port, i915_reg_t hdmi_reg)
16922 {
16923         u32 val = I915_READ(hdmi_reg);
16924
16925         if (val & SDVO_ENABLE ||
16926             (val & SDVO_PIPE_SEL_MASK) == SDVO_PIPE_SEL(PIPE_A))
16927                 return;
16928
16929         DRM_DEBUG_KMS("Sanitizing transcoder select for HDMI %c\n",
16930                       port_name(port));
16931
16932         val &= ~SDVO_PIPE_SEL_MASK;
16933         val |= SDVO_PIPE_SEL(PIPE_A);
16934
16935         I915_WRITE(hdmi_reg, val);
16936 }
16937
16938 static void ibx_sanitize_pch_dp_port(struct drm_i915_private *dev_priv,
16939                                      enum port port, i915_reg_t dp_reg)
16940 {
16941         u32 val = I915_READ(dp_reg);
16942
16943         if (val & DP_PORT_EN ||
16944             (val & DP_PIPE_SEL_MASK) == DP_PIPE_SEL(PIPE_A))
16945                 return;
16946
16947         DRM_DEBUG_KMS("Sanitizing transcoder select for DP %c\n",
16948                       port_name(port));
16949
16950         val &= ~DP_PIPE_SEL_MASK;
16951         val |= DP_PIPE_SEL(PIPE_A);
16952
16953         I915_WRITE(dp_reg, val);
16954 }
16955
16956 static void ibx_sanitize_pch_ports(struct drm_i915_private *dev_priv)
16957 {
16958         /*
16959          * The BIOS may select transcoder B on some of the PCH
16960          * ports even it doesn't enable the port. This would trip
16961          * assert_pch_dp_disabled() and assert_pch_hdmi_disabled().
16962          * Sanitize the transcoder select bits to prevent that. We
16963          * assume that the BIOS never actually enabled the port,
16964          * because if it did we'd actually have to toggle the port
16965          * on and back off to make the transcoder A select stick
16966          * (see. intel_dp_link_down(), intel_disable_hdmi(),
16967          * intel_disable_sdvo()).
16968          */
16969         ibx_sanitize_pch_dp_port(dev_priv, PORT_B, PCH_DP_B);
16970         ibx_sanitize_pch_dp_port(dev_priv, PORT_C, PCH_DP_C);
16971         ibx_sanitize_pch_dp_port(dev_priv, PORT_D, PCH_DP_D);
16972
16973         /* PCH SDVOB multiplex with HDMIB */
16974         ibx_sanitize_pch_hdmi_port(dev_priv, PORT_B, PCH_HDMIB);
16975         ibx_sanitize_pch_hdmi_port(dev_priv, PORT_C, PCH_HDMIC);
16976         ibx_sanitize_pch_hdmi_port(dev_priv, PORT_D, PCH_HDMID);
16977 }
16978
16979 /* Scan out the current hw modeset state,
16980  * and sanitizes it to the current state
16981  */
16982 static void
16983 intel_modeset_setup_hw_state(struct drm_device *dev,
16984                              struct drm_modeset_acquire_ctx *ctx)
16985 {
16986         struct drm_i915_private *dev_priv = to_i915(dev);
16987         struct intel_crtc_state *crtc_state;
16988         struct intel_encoder *encoder;
16989         struct intel_crtc *crtc;
16990         intel_wakeref_t wakeref;
16991         int i;
16992
16993         wakeref = intel_display_power_get(dev_priv, POWER_DOMAIN_INIT);
16994
16995         intel_early_display_was(dev_priv);
16996         intel_modeset_readout_hw_state(dev);
16997
16998         /* HW state is read out, now we need to sanitize this mess. */
16999
17000         /* Sanitize the TypeC port mode upfront, encoders depend on this */
17001         for_each_intel_encoder(dev, encoder) {
17002                 enum phy phy = intel_port_to_phy(dev_priv, encoder->port);
17003
17004                 /* We need to sanitize only the MST primary port. */
17005                 if (encoder->type != INTEL_OUTPUT_DP_MST &&
17006                     intel_phy_is_tc(dev_priv, phy))
17007                         intel_tc_port_sanitize(enc_to_dig_port(&encoder->base));
17008         }
17009
17010         get_encoder_power_domains(dev_priv);
17011
17012         if (HAS_PCH_IBX(dev_priv))
17013                 ibx_sanitize_pch_ports(dev_priv);
17014
17015         /*
17016          * intel_sanitize_plane_mapping() may need to do vblank
17017          * waits, so we need vblank interrupts restored beforehand.
17018          */
17019         for_each_intel_crtc(&dev_priv->drm, crtc) {
17020                 crtc_state = to_intel_crtc_state(crtc->base.state);
17021
17022                 drm_crtc_vblank_reset(&crtc->base);
17023
17024                 if (crtc_state->base.active)
17025                         intel_crtc_vblank_on(crtc_state);
17026         }
17027
17028         intel_sanitize_plane_mapping(dev_priv);
17029
17030         for_each_intel_encoder(dev, encoder)
17031                 intel_sanitize_encoder(encoder);
17032
17033         for_each_intel_crtc(&dev_priv->drm, crtc) {
17034                 crtc_state = to_intel_crtc_state(crtc->base.state);
17035                 intel_sanitize_crtc(crtc, ctx);
17036                 intel_dump_pipe_config(crtc_state, NULL, "[setup_hw_state]");
17037         }
17038
17039         intel_modeset_update_connector_atomic_state(dev);
17040
17041         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
17042                 struct intel_shared_dpll *pll = &dev_priv->shared_dplls[i];
17043
17044                 if (!pll->on || pll->active_mask)
17045                         continue;
17046
17047                 DRM_DEBUG_KMS("%s enabled but not in use, disabling\n",
17048                               pll->info->name);
17049
17050                 pll->info->funcs->disable(dev_priv, pll);
17051                 pll->on = false;
17052         }
17053
17054         if (IS_G4X(dev_priv)) {
17055                 g4x_wm_get_hw_state(dev_priv);
17056                 g4x_wm_sanitize(dev_priv);
17057         } else if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv)) {
17058                 vlv_wm_get_hw_state(dev_priv);
17059                 vlv_wm_sanitize(dev_priv);
17060         } else if (INTEL_GEN(dev_priv) >= 9) {
17061                 skl_wm_get_hw_state(dev_priv);
17062         } else if (HAS_PCH_SPLIT(dev_priv)) {
17063                 ilk_wm_get_hw_state(dev_priv);
17064         }
17065
17066         for_each_intel_crtc(dev, crtc) {
17067                 u64 put_domains;
17068
17069                 crtc_state = to_intel_crtc_state(crtc->base.state);
17070                 put_domains = modeset_get_crtc_power_domains(crtc_state);
17071                 if (WARN_ON(put_domains))
17072                         modeset_put_power_domains(dev_priv, put_domains);
17073         }
17074
17075         intel_display_power_put(dev_priv, POWER_DOMAIN_INIT, wakeref);
17076
17077         intel_fbc_init_pipe_state(dev_priv);
17078 }
17079
17080 void intel_display_resume(struct drm_device *dev)
17081 {
17082         struct drm_i915_private *dev_priv = to_i915(dev);
17083         struct drm_atomic_state *state = dev_priv->modeset_restore_state;
17084         struct drm_modeset_acquire_ctx ctx;
17085         int ret;
17086
17087         dev_priv->modeset_restore_state = NULL;
17088         if (state)
17089                 state->acquire_ctx = &ctx;
17090
17091         drm_modeset_acquire_init(&ctx, 0);
17092
17093         while (1) {
17094                 ret = drm_modeset_lock_all_ctx(dev, &ctx);
17095                 if (ret != -EDEADLK)
17096                         break;
17097
17098                 drm_modeset_backoff(&ctx);
17099         }
17100
17101         if (!ret)
17102                 ret = __intel_display_resume(dev, state, &ctx);
17103
17104         intel_enable_ipc(dev_priv);
17105         drm_modeset_drop_locks(&ctx);
17106         drm_modeset_acquire_fini(&ctx);
17107
17108         if (ret)
17109                 DRM_ERROR("Restoring old state failed with %i\n", ret);
17110         if (state)
17111                 drm_atomic_state_put(state);
17112 }
17113
17114 static void intel_hpd_poll_fini(struct drm_device *dev)
17115 {
17116         struct intel_connector *connector;
17117         struct drm_connector_list_iter conn_iter;
17118
17119         /* Kill all the work that may have been queued by hpd. */
17120         drm_connector_list_iter_begin(dev, &conn_iter);
17121         for_each_intel_connector_iter(connector, &conn_iter) {
17122                 if (connector->modeset_retry_work.func)
17123                         cancel_work_sync(&connector->modeset_retry_work);
17124                 if (connector->hdcp.shim) {
17125                         cancel_delayed_work_sync(&connector->hdcp.check_work);
17126                         cancel_work_sync(&connector->hdcp.prop_work);
17127                 }
17128         }
17129         drm_connector_list_iter_end(&conn_iter);
17130 }
17131
17132 void intel_modeset_driver_remove(struct drm_device *dev)
17133 {
17134         struct drm_i915_private *dev_priv = to_i915(dev);
17135
17136         flush_workqueue(dev_priv->modeset_wq);
17137
17138         flush_work(&dev_priv->atomic_helper.free_work);
17139         WARN_ON(!llist_empty(&dev_priv->atomic_helper.free_list));
17140
17141         /*
17142          * Interrupts and polling as the first thing to avoid creating havoc.
17143          * Too much stuff here (turning of connectors, ...) would
17144          * experience fancy races otherwise.
17145          */
17146         intel_irq_uninstall(dev_priv);
17147
17148         /*
17149          * Due to the hpd irq storm handling the hotplug work can re-arm the
17150          * poll handlers. Hence disable polling after hpd handling is shut down.
17151          */
17152         intel_hpd_poll_fini(dev);
17153
17154         /* poll work can call into fbdev, hence clean that up afterwards */
17155         intel_fbdev_fini(dev_priv);
17156
17157         intel_unregister_dsm_handler();
17158
17159         intel_fbc_global_disable(dev_priv);
17160
17161         /* flush any delayed tasks or pending work */
17162         flush_scheduled_work();
17163
17164         intel_hdcp_component_fini(dev_priv);
17165
17166         drm_mode_config_cleanup(dev);
17167
17168         intel_overlay_cleanup(dev_priv);
17169
17170         intel_gmbus_teardown(dev_priv);
17171
17172         destroy_workqueue(dev_priv->modeset_wq);
17173
17174         intel_fbc_cleanup_cfb(dev_priv);
17175 }
17176
17177 /*
17178  * set vga decode state - true == enable VGA decode
17179  */
17180 int intel_modeset_vga_set_state(struct drm_i915_private *dev_priv, bool state)
17181 {
17182         unsigned reg = INTEL_GEN(dev_priv) >= 6 ? SNB_GMCH_CTRL : INTEL_GMCH_CTRL;
17183         u16 gmch_ctrl;
17184
17185         if (pci_read_config_word(dev_priv->bridge_dev, reg, &gmch_ctrl)) {
17186                 DRM_ERROR("failed to read control word\n");
17187                 return -EIO;
17188         }
17189
17190         if (!!(gmch_ctrl & INTEL_GMCH_VGA_DISABLE) == !state)
17191                 return 0;
17192
17193         if (state)
17194                 gmch_ctrl &= ~INTEL_GMCH_VGA_DISABLE;
17195         else
17196                 gmch_ctrl |= INTEL_GMCH_VGA_DISABLE;
17197
17198         if (pci_write_config_word(dev_priv->bridge_dev, reg, gmch_ctrl)) {
17199                 DRM_ERROR("failed to write control word\n");
17200                 return -EIO;
17201         }
17202
17203         return 0;
17204 }
17205
17206 #if IS_ENABLED(CONFIG_DRM_I915_CAPTURE_ERROR)
17207
17208 struct intel_display_error_state {
17209
17210         u32 power_well_driver;
17211
17212         struct intel_cursor_error_state {
17213                 u32 control;
17214                 u32 position;
17215                 u32 base;
17216                 u32 size;
17217         } cursor[I915_MAX_PIPES];
17218
17219         struct intel_pipe_error_state {
17220                 bool power_domain_on;
17221                 u32 source;
17222                 u32 stat;
17223         } pipe[I915_MAX_PIPES];
17224
17225         struct intel_plane_error_state {
17226                 u32 control;
17227                 u32 stride;
17228                 u32 size;
17229                 u32 pos;
17230                 u32 addr;
17231                 u32 surface;
17232                 u32 tile_offset;
17233         } plane[I915_MAX_PIPES];
17234
17235         struct intel_transcoder_error_state {
17236                 bool available;
17237                 bool power_domain_on;
17238                 enum transcoder cpu_transcoder;
17239
17240                 u32 conf;
17241
17242                 u32 htotal;
17243                 u32 hblank;
17244                 u32 hsync;
17245                 u32 vtotal;
17246                 u32 vblank;
17247                 u32 vsync;
17248         } transcoder[5];
17249 };
17250
17251 struct intel_display_error_state *
17252 intel_display_capture_error_state(struct drm_i915_private *dev_priv)
17253 {
17254         struct intel_display_error_state *error;
17255         int transcoders[] = {
17256                 TRANSCODER_A,
17257                 TRANSCODER_B,
17258                 TRANSCODER_C,
17259                 TRANSCODER_D,
17260                 TRANSCODER_EDP,
17261         };
17262         int i;
17263
17264         BUILD_BUG_ON(ARRAY_SIZE(transcoders) != ARRAY_SIZE(error->transcoder));
17265
17266         if (!HAS_DISPLAY(dev_priv))
17267                 return NULL;
17268
17269         error = kzalloc(sizeof(*error), GFP_ATOMIC);
17270         if (error == NULL)
17271                 return NULL;
17272
17273         if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv))
17274                 error->power_well_driver = I915_READ(HSW_PWR_WELL_CTL2);
17275
17276         for_each_pipe(dev_priv, i) {
17277                 error->pipe[i].power_domain_on =
17278                         __intel_display_power_is_enabled(dev_priv,
17279                                                          POWER_DOMAIN_PIPE(i));
17280                 if (!error->pipe[i].power_domain_on)
17281                         continue;
17282
17283                 error->cursor[i].control = I915_READ(CURCNTR(i));
17284                 error->cursor[i].position = I915_READ(CURPOS(i));
17285                 error->cursor[i].base = I915_READ(CURBASE(i));
17286
17287                 error->plane[i].control = I915_READ(DSPCNTR(i));
17288                 error->plane[i].stride = I915_READ(DSPSTRIDE(i));
17289                 if (INTEL_GEN(dev_priv) <= 3) {
17290                         error->plane[i].size = I915_READ(DSPSIZE(i));
17291                         error->plane[i].pos = I915_READ(DSPPOS(i));
17292                 }
17293                 if (INTEL_GEN(dev_priv) <= 7 && !IS_HASWELL(dev_priv))
17294                         error->plane[i].addr = I915_READ(DSPADDR(i));
17295                 if (INTEL_GEN(dev_priv) >= 4) {
17296                         error->plane[i].surface = I915_READ(DSPSURF(i));
17297                         error->plane[i].tile_offset = I915_READ(DSPTILEOFF(i));
17298                 }
17299
17300                 error->pipe[i].source = I915_READ(PIPESRC(i));
17301
17302                 if (HAS_GMCH(dev_priv))
17303                         error->pipe[i].stat = I915_READ(PIPESTAT(i));
17304         }
17305
17306         for (i = 0; i < ARRAY_SIZE(error->transcoder); i++) {
17307                 enum transcoder cpu_transcoder = transcoders[i];
17308
17309                 if (!INTEL_INFO(dev_priv)->trans_offsets[cpu_transcoder])
17310                         continue;
17311
17312                 error->transcoder[i].available = true;
17313                 error->transcoder[i].power_domain_on =
17314                         __intel_display_power_is_enabled(dev_priv,
17315                                 POWER_DOMAIN_TRANSCODER(cpu_transcoder));
17316                 if (!error->transcoder[i].power_domain_on)
17317                         continue;
17318
17319                 error->transcoder[i].cpu_transcoder = cpu_transcoder;
17320
17321                 error->transcoder[i].conf = I915_READ(PIPECONF(cpu_transcoder));
17322                 error->transcoder[i].htotal = I915_READ(HTOTAL(cpu_transcoder));
17323                 error->transcoder[i].hblank = I915_READ(HBLANK(cpu_transcoder));
17324                 error->transcoder[i].hsync = I915_READ(HSYNC(cpu_transcoder));
17325                 error->transcoder[i].vtotal = I915_READ(VTOTAL(cpu_transcoder));
17326                 error->transcoder[i].vblank = I915_READ(VBLANK(cpu_transcoder));
17327                 error->transcoder[i].vsync = I915_READ(VSYNC(cpu_transcoder));
17328         }
17329
17330         return error;
17331 }
17332
17333 #define err_printf(e, ...) i915_error_printf(e, __VA_ARGS__)
17334
17335 void
17336 intel_display_print_error_state(struct drm_i915_error_state_buf *m,
17337                                 struct intel_display_error_state *error)
17338 {
17339         struct drm_i915_private *dev_priv = m->i915;
17340         int i;
17341
17342         if (!error)
17343                 return;
17344
17345         err_printf(m, "Num Pipes: %d\n", INTEL_INFO(dev_priv)->num_pipes);
17346         if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv))
17347                 err_printf(m, "PWR_WELL_CTL2: %08x\n",
17348                            error->power_well_driver);
17349         for_each_pipe(dev_priv, i) {
17350                 err_printf(m, "Pipe [%d]:\n", i);
17351                 err_printf(m, "  Power: %s\n",
17352                            onoff(error->pipe[i].power_domain_on));
17353                 err_printf(m, "  SRC: %08x\n", error->pipe[i].source);
17354                 err_printf(m, "  STAT: %08x\n", error->pipe[i].stat);
17355
17356                 err_printf(m, "Plane [%d]:\n", i);
17357                 err_printf(m, "  CNTR: %08x\n", error->plane[i].control);
17358                 err_printf(m, "  STRIDE: %08x\n", error->plane[i].stride);
17359                 if (INTEL_GEN(dev_priv) <= 3) {
17360                         err_printf(m, "  SIZE: %08x\n", error->plane[i].size);
17361                         err_printf(m, "  POS: %08x\n", error->plane[i].pos);
17362                 }
17363                 if (INTEL_GEN(dev_priv) <= 7 && !IS_HASWELL(dev_priv))
17364                         err_printf(m, "  ADDR: %08x\n", error->plane[i].addr);
17365                 if (INTEL_GEN(dev_priv) >= 4) {
17366                         err_printf(m, "  SURF: %08x\n", error->plane[i].surface);
17367                         err_printf(m, "  TILEOFF: %08x\n", error->plane[i].tile_offset);
17368                 }
17369
17370                 err_printf(m, "Cursor [%d]:\n", i);
17371                 err_printf(m, "  CNTR: %08x\n", error->cursor[i].control);
17372                 err_printf(m, "  POS: %08x\n", error->cursor[i].position);
17373                 err_printf(m, "  BASE: %08x\n", error->cursor[i].base);
17374         }
17375
17376         for (i = 0; i < ARRAY_SIZE(error->transcoder); i++) {
17377                 if (!error->transcoder[i].available)
17378                         continue;
17379
17380                 err_printf(m, "CPU transcoder: %s\n",
17381                            transcoder_name(error->transcoder[i].cpu_transcoder));
17382                 err_printf(m, "  Power: %s\n",
17383                            onoff(error->transcoder[i].power_domain_on));
17384                 err_printf(m, "  CONF: %08x\n", error->transcoder[i].conf);
17385                 err_printf(m, "  HTOTAL: %08x\n", error->transcoder[i].htotal);
17386                 err_printf(m, "  HBLANK: %08x\n", error->transcoder[i].hblank);
17387                 err_printf(m, "  HSYNC: %08x\n", error->transcoder[i].hsync);
17388                 err_printf(m, "  VTOTAL: %08x\n", error->transcoder[i].vtotal);
17389                 err_printf(m, "  VBLANK: %08x\n", error->transcoder[i].vblank);
17390                 err_printf(m, "  VSYNC: %08x\n", error->transcoder[i].vsync);
17391         }
17392 }
17393
17394 #endif